当我使用linux并尝试使用这个脚本将文件上传到远程服务器时,一切都很好。但是如果我使用Windows,那么脚本就不能工作了。剧本:
$url="http://site.com/upload.php";
$post=array('image'=>'@'.getcwd().'images/image.jpg');
$this->ch=curl_init();
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
$body = curl_exec($this->ch);
echo $body; // << on Windows empty result我做错什么了?
PHP 5.3
Windows 7-不工作,Ubuntu Linux 10.10 -工作
发布于 2014-01-06 16:16:22
如果您使用的是Windows,您的文件路径分隔符将是\,而不是Linux样式的/。
一件显而易见的事就是
$post=array('image'=>'@'.getcwd().'images\image.jpg');看看能不能行。
如果您想使您的脚本可移植,以便它可以在Windows或Linux上运行,则可以使用PHP预定义常数 DIRECTORY_SEPARATOR
$post=array('image'=>'@'.getcwd().'images' . DIRECTORY_SEPARATOR .'image.jpg');发布于 2014-01-06 18:59:18
理论上,您的代码不应该在任何unix或windows中工作(我指的是上载)。从代码中考虑这一部分:
'image'=>'@'.getcwd().'images/image.jpg'在windows中,getcwd()返回F:\Work\temp
在Linux中,它返回/root/work/temp。
因此,上面的代码将编译如下:
Windows:'image'=>'@F:\Work\tempimages/image.jpg'
Linux:'image'=>'@/root/work/tempimages/image.jpg'
由于您提到它在linux中对您有效,这意味着/root/work/tempimages/image.jpg以某种方式存在于您的文件系统中。
我的PHP版本:
Linux:PHP 5.1.6
Windows:PHP 5.3.2
发布于 2014-01-11 01:50:49
您应该尝试var_dump($body)来查看$body真正包含的内容。按照配置cURL的方式,$body将包含服务器的响应或失败时的false。使用echo无法区分空响应或false。有可能请求正在正常运行,而服务器只是没有返回任何内容。
但是,正如其他人所说的,您的文件路径似乎无效。getcwd()不输出最终的/,您需要添加一个来使代码工作。既然您说它在linux上工作,即使没有缺少的斜杠,我也想知道它是如何找到您的文件的。
我建议您创建一个相对于正在运行的PHP脚本的文件的路径,或者提供一个绝对路径,而不依赖于可能不返回所期望的getcwd()。getcwd()的值在不同的系统中是不可预测的,并且不是很可移植的。
例如,如果要发布的文件与PHP脚本位于同一个文件夹中:
$post = array('image' => '@image.jpg');就足够了。如果需要,提供一个绝对路径:$post = array('image' => '@/home/youruser/yourdomain/image.jpg');
正如Terence所说,如果您需要在Linux和Windows之间移植代码,请考虑使用PHP预定义常数 DIRECTORY_SEPARATOR
$url = "http://yoursite.com/upload.php";
// images\image.jpg on Windows images/image.jpg on Linux
$post = array('image' => '@images'.DIRECTORY_SEPARATOR.'image.jpg');
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
$body = curl_exec($this->ch);
var_dump($body);getcwd() cURL
https://stackoverflow.com/questions/4846667
复制相似问题