简体   繁体   English

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

[英]How to upload file from local to server using curl in php?

I want to upload the file from local to server using curl in php and without using the form (which is html). 我想使用php中的curl将文件从本地上传到服务器,而不使用表单(即html)。

My php version is 5.2.6. 我的php版本是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. 我尝试了许多不同的方法,并进行了很多研究(使用php中的curl将文件上传到服务器),但是Google解决方案无法解决我的问题。

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 无法写入文件

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. 要将文件发送到服务器,必须将服务器配置为接受POST请求,并且您必须通过该端点发送文件。

If you have a form, do you send it to: "user.com/user/fromLocal.txt" ?? 如果您有表单,您会将其发送到:“ 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. 您必须使用curl创建表单数据,并将其发送到准备接受您的请求的服务器。 There are different ways to accomplish that. 有不同的方法可以做到这一点。 And the most simple is exactly to send a form using curl and not the HTML. 最简单的就是使用curl而不是HTML发送表单。 But absolutly you cannot write a file like that in a server. 但是绝对不能在服务器中写入类似的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM