php 如何使用curl和php上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15200632/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:45:53  来源:igfitidea点击:

how to upload file using curl with php

phpcurlupload

提问by Hadidi44

I want to know how to upload file using cURL or anything else in PHP. I have searched in google many times but no results.

我想知道如何使用 cURL 或 PHP 中的任何其他内容上传文件。我在谷歌搜索了很多次,但没有结果。

In other words, the user sees a file upload button on a form, the form gets posted to my php script, then my php script needs to re-post it to another script (eg on another server).

换句话说,用户在表单上看到一个文件上传按钮,表单被发布到我的 php 脚本,然后我的 php 脚本需要将它重新发布到另一个脚本(例如在另一台服务器上)。

I have this code to receive the file and upload it

我有这个代码来接收文件并上传它

code :

代码 :

echo"".$_FILES['userfile']."";
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if ( isset($_FILES["userfile"]) ) {
    echo '<p><font color="#00FF00" size="7">Uploaded</font></p>';
    if (move_uploaded_file
($_FILES["userfile"]["tmp_name"], $uploadfile))
echo $uploadfile;
    else echo '<p><font color="#FF0000" size="7">Failed</font></p>';
}

I want the code to send the file to receiver file.

我希望代码将文件发送到接收器文件。

回答by karthik

Use:

用:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

你也可以参考:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

PHP 5.5+ 的重要提示:

Now we should use https://wiki.php.net/rfc/curl-file-uploadbut if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

现在我们应该使用https://wiki.php.net/rfc/curl-file-upload但如果您仍然想使用这种已弃用的方法,那么您需要设置curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);