cURL将文件上传到MS Windows上的远程服务器

当我使用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 - 工作     
已邀请:
如果您使用的是Windows,则文件路径分隔符将不是Linux样式
/
。 一个显而易见的尝试是
$post=array('image'=>'@'.getcwd().'imagesimage.jpg');
看看是否有效。 如果你想使你的脚本可移植以便它可以在Windows或Linux上运行,你可以使用PHP的预定义常量
DIRECTORY_SEPARATOR
$post=array('image'=>'@'.getcwd().'images' . DIRECTORY_SEPARATOR .'image.jpg');
    
从理论上讲,你的代码不应该在任何unix或windows中工作(我的意思是上传)。从代码中考虑这部分:
'image'=>'@'.getcwd().'images/image.jpg'
在Windows
getcwd()
返回
F:Worktemp
在Linux中它返回
/root/work/temp
所以,你的上面的代码将编译如下: Windows:
'image'=>'@F:Worktempimages/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
    
你应该试试
var_dump($body)
看看
$body
真的包含什么。使用cURL的配置方式,
$body
将包含服务器的响应或失败时的错误。没有办法用
echo
来区分空响应或假。请求可能正常通过,服务器只返回任何内容。 但是,正如其他人所说,您的文件路径似乎无效。
getcwd()
不输出最终
/
,您需要添加一个才能使代码正常工作。既然你说它适用于linux,即使没有丢失的斜杠,我也想知道它是如何找到你的文件的。 我建议你创建一个相对于正在运行的PHP脚本的文件路径,或者提供一个绝对路径,而不是依赖于
getcwd()
,这可能不会返回你期望的内容。
getcwd()
的值在整个系统中是不可预测的,并且不是非常便携。 例如,如果您尝试POST的文件与PHP脚本位于同一文件夹中:
$post = array('image' => '@image.jpg');
就足够了。如果需要,提供绝对路径:
$post = array('image' => '@/home/youruser/yourdomain/image.jpg');
正如Terence所说,如果你需要你的代码可以在Linux和Linux之间移植。 Windows,考虑使用PHP的预定义常量
DIRECTORY_SEPARATOR
$url = "http://yoursite.com/upload.php";
// imagesimage.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     
如果使用xampp  确保在php.ini配置文件中 行号952未取消注释    即    如果是行
   ;extension=php_curl.dll
然后成功
  extension=php_curl.dll
    
我认为,更好的方法是:
$imgpath = implode(DIRECTORY_SEPARATOR, array(getcwd(), 'images', 'image.jpg'));
$post = array('image'=>'@'.$imgpath);
    

要回复问题请先登录注册