dongwuwei0718
2019-02-11 08:23
浏览 531
已采纳

如何使用php中的curl将文件从本地上传到服务器?

I want to upload the file from local to server using curl in php and without using the form (which is html).

My php version is 5.2.6.

I have tried many different way and make many research about (upload file to server using curl in php), but the solution in google cannot solve my problem.

Below is my code:

// open file descriptor
$fp = fopen ("user.com/user/fromLocal.txt", 'w+') or die('Unable to write a file'); 

// file to download
$ch = curl_init('C:/wamp/www/user/fromLocal.txt');
// enable SSL if needed
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

// output to file descriptor
curl_setopt($ch, CURLOPT_FILE, $fp);          
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
// set large timeout to allow curl to run for a longer time
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);     
curl_setopt($ch, CURLOPT_USERAGENT, 'any');
// Enable debug output
curl_setopt($ch, CURLOPT_VERBOSE, true);

echo $ch;
echo $fp;
curl_exec($ch);
curl_close($ch);                               
fclose($fp);

Expected output:

The file can upload to server and view.

Actual output:

Unable to write the file

图片转代码服务由CSDN问答提供 功能建议

我想在php中使用curl将文件从本地上传到服务器而不使用表单(这是html) 。

我的php版本是5.2.6。

我尝试了很多不同的方法并进行了很多研究(使用curl将文件上传到服务器) PHP),但谷歌的解决方案无法解决我的问题。

以下是我的代码:

  //打开文件描述符
  $ fp = fopen(“user.com/user/fromLocal.txt”,“w +”)或死亡(“无法写入文件”);  
 
 //要下载的文件
 $ ch = curl_init('C:/wamp/www/user/fromLocal.txt'); 
 //如果需要,启用SSL 
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false)  ;  
 
 //输出到文件描述符
curl_setopt($ ch,CURLOPT_FILE,$ fp);  
 ncurl_setopt($ ch,CURLOPT_FOLLOWLOCATION,TRUE); 
 //设置大超时以允许curl运行更长时间
curl_setopt($ ch,CURLOPT_TIMEOUT,1000);  
 ncurl_setopt($ ch,CURLOPT_USERAGENT,'any'); 
 //启用调试输出
curl_setopt($ ch,CURLOPT_VERBOSE,true); 
 
echo $ ch; 
echo $ fp; 
curl_exec($ ch);  
curl_close($ CH);  
 nclclose($ fp); 
   
 
 

预期输出:

该文件可以上传到服务器并查看。

实际输出:

< p>无法写入文件
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyi1921 2019-02-11 08:28
    已采纳

    I think you miss important information.

    fopen ("user.com/user/fromLocal.txt", 'w+')
    

    this means nothing. To send a file to the server the server has to be configured to accept a POST request and you have to send the file through that endpoint.

    If you have a form, do you send it to: "user.com/user/fromLocal.txt" ?? You have to create the form data with curl and send it to a server ready to accept your request. There are different ways to accomplish that. And the most simple is exactly to send a form using curl and not the HTML. But absolutly you cannot write a file like that in a server.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题