php Curl 返回 400 个错误的请求(带有空格的 url)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12342149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Curl returns 400 bad request (url with spaces)
提问by yAnTar
When i use curl library and try to get image from url i get 400 bad request error. 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
当我使用 curl 库并尝试从 url 获取图像时,我收到 400 个错误的请求错误。我发现问题出在编码 url 上。但在我的情况下它不起作用,因为我的网址 - 它是服务器端图像的路径 - 就像
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 错误。
回答by Wim Molenberghs
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);
回答by Alexander Yancharuk
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. urlencode()is only kept for legacy use. For more details look at this SO answer.
rawurlencode()必须始终是首选。urlencode()仅保留用于遗留用途。有关更多详细信息,请查看此 SO 答案。
回答by Explosion Pills
You can't urlencode the entire string because that will encode the slashes and others that you need to remain unencoded. If spaces are your only problem, this will do:
您不能对整个字符串进行 urlencode,因为这将对斜杠和其他需要保持未编码的斜杠进行编码。如果空格是您唯一的问题,则可以这样做:
str_replace(' ', '+', $url);

