[英]Curl returns 400 bad request (url with spaces)
When i use curl library and try to get image from url i get 400 bad request error.当我使用 curl 库并尝试从 url 获取图像时,我收到 400 bad request 错误。 I founded that problem is with encoding url.
我发现这个问题与编码网址有关。 But in my case it's not work, because my url - it's path to image on server side - like
但在我的情况下,它不起作用,因为我的网址 - 它是服务器端图像的路径 - 就像
http://example.com/images/products/product 1.jpg
I understand that user spaces in name files it's bad practice, but it's not my server and not i created those files.我知道名称文件中的用户空间是不好的做法,但它不是我的服务器,也不是我创建的那些文件。
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, urlencode($url));
echo $ret = curl_exec($ch);
When i use urlencode function - curl return http_code = 0当我使用 urlencode 函数时 - curl 返回 http_code = 0
Updated更新
$url = str_replace(' ', '+', $url);
doesn't work, server return 404 error.不起作用,服务器返回 404 错误。
Does this maybe work? 这可能有用吗?
$url = 'http://host/a b.img';
$url = str_replace(" ", '%20', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
echo $ret = curl_exec($ch);
You need to use rawurlencode() function: 您需要使用rawurlencode()函数:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, rawurlencode($url));
echo $ret = curl_exec($ch);
rawurlencode() must be always preferred. rawurlencode()必须始终是首选。 urlencode() is only kept for legacy use.
urlencode()仅保留用于旧版使用。 For more details look at this SO answer .
有关更多详细信息, 请参见此SO答案 。
You can't urlencode the entire string because that will encode the slashes and others that you need to remain unencoded. 您不能对整个字符串进行urlencode,因为这将对斜杠和其他需要保持未编码状态的字符串进行编码。 If spaces are your only problem, this will do:
如果只有空格是您的问题,它将这样做:
str_replace(' ', '+', $url);
Using curl has more challenges than other ways.使用 curl 比其他方式面临更多挑战。 Simply use shell_exec
只需使用 shell_exec
$cmd = "curl -k -v -X POST 'https://serveraddress:8243/?foo=bar' -H 'Authorization: Basic cEZ.....h'";
$result = shell_exec($cmd);
$output = json_decode($result,true);
print_r($output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.