我有以下 PHP 代码-
<?php
$uploaddir = getcwd().'/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
我想做的是,通过向脚本发送 HTTP header 来上传文本文件。这是我要发送的 header -
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------556304871068
POST 内容-
-----------------------------556304871068\r\n
Content-Disposition: form-data; name="MAX_FILE_SIZE"\r\n
\r\n
512000\r\n
-----------------------------556304871068\r\n
Content-Disposition: form-data; name="userfile"; filename="example.txt"\r\n
Content-Type: text/plain\r\n
\r\n
ThisText\r\n
\r\n
-----------------------------556304871068--\r\n
但是它在响应中返回错误信息-
<br />
<b>Notice</b>: Undefined index: userfile in <b>C:\HostingSpaces\Test\mysite.com\wwwroot\admin\upload.php</b> on line <b>4</b><br />
<pre><br />
我不明白为什么会出现这个错误以及如何解决这个问题。
注意:当我正常上传文件(使用 HTML 上传页面)时,PHP 脚本运行良好。
编辑:HTML 表单代码:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
最佳答案
这是一个通过 POST 使用 php/cURL 发送文件的简单脚本:
<?php
$target_url = 'http://127.0.0.1/accept.php';
//This needs to be the full path to the file you want to send.
$file_name_with_full_path = realpath('./sample.jpeg');
/* curl will accept an array here too.
* Many examples I found showed a url-encoded string instead.
* Take note that the 'key' in the array will be the key that shows up in the
* $_FILES array of the accept script. and the at sign '@' is required before the
* file name.
*/
$post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
这里是接受文件的相应脚本。
<?php
$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
echo "\n<hr />\n";
print_r($_POST);
print "</pr" . "e>\n";
?>
关于使用 HTTP header 上传 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677911/