在传递目标URL到curl时出现一个奇怪的问题。如果我对curl进行硬编码,则不会出现任何错误。
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Response;
use Closure;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class CurlGlobal
{
# Headers received and read by our callback
private $headers = array();
private $url;
public function header_callback($handle, $header)
{
$len = strlen($header);
$this->headers[] = $header;
return $len;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->url = trim($request->plain_url);
//$this->url = 'https://s.ytimg.com/yts/img/favicon_96-vflW9Ec0w.png';
var_dump($this->url); //https://s.ytimg.com/yts/img/favicon_96-vflw9ec0w.png
var_dump('$request->plain_url '. $request->plain_url); // https://s.ytimg.com/yts/img/favicon_96-vflw9ec0w.png
$curl_options = array(
CURLOPT_URL => $this->url,
CURLOPT_CONNECTTIMEOUT => 60,
CURLOPT_TIMEOUT => 300,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => $request->server('HTTP_USER_AGENT'), // Change useragent to both a latest chrome & safari (image formats)
CURLOPT_FAILONERROR => true, //request failure on HTTP response >= 400
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, # Always connect to ipv4
);
$curl_options[CURLOPT_HEADERFUNCTION] = array(
&$this,
'header_callback'
);
var_dump($curl_options);
#######Execute the curl request(TODO move to another middleware) #########
# Get a cURL handle
$ch = curl_init();
# Set the options
curl_setopt_array($ch, $curl_options);
# Make the request
curl_exec($ch);
# Close the curl handle
if( ! $result = curl_exec($ch))
{
dd(curl_error($ch));
}
//dd($request->plain_url);
dd($this->headers);
return $next($request);
//return response($this->return_data);
}
}
调试信息
string(52) "https://s.ytimg.com/yts/img/favicon_96-vflW9Ec0w.png"
string(72) "$request->plain_url https://s.ytimg.com/yts/img/favicon_96-vflw9ec0w.png"
array(9) {
[10002]=>
string(52) "https://s.ytimg.com/yts/img/favicon_96-vflW9Ec0w.png"
[78]=>
int(60)
[13]=>
int(300)
[64]=>
bool(false)
[81]=>
bool(false)
[10018]=>
string(105) "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36"
[45]=>
bool(true)
[113]=>
int(1)
[20079]=>
array(2) {
[0]=>
object(App\Http\Middleware\CurlGlobal)#222 (2) {
["headers":"App\Http\Middleware\CurlGlobal":private]=>
array(0) {
}
["url":"App\Http\Middleware\CurlGlobal":private]=>
string(52) "https://s.ytimg.com/yts/img/favicon_96-vflW9Ec0w.png"
}
[1]=>
string(15) "header_callback"
}
}
如果我取消注释以下行,则不会收到任何curl错误,但我不明白为什么当前的实现无法正常工作。
//$this->url = 'https://s.ytimg.com/yts/img/favicon_96-vflW9Ec0w.png';
调试显示传递了相同的URL,但我不知道出了什么问题。