我想設(shè)定一個(gè)簡(jiǎn)單的 HTTP 服務(wù)(使用 PHP)來(lái)使用 Linux curl 和 Windows Powershell 從另一臺(tái)電腦接收檔案。我讀過(guò)網(wǎng)路資源,包括PHP無(wú)法上傳檔案到伺服器?使用 cURL 將 POST 資料與文件一起上傳。這些帖子幫助我解決了參數(shù)問(wèn)題,但不是全部。
這是我的程式碼(請(qǐng)參閱此處)
<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } ?>
這是我使用的命令並收到錯(cuò)誤回應(yīng)。
# bash curl -X POST -F "id=fileToUpload" -F "fileToUpload=@null.txt" http://127.0.0.1/upload.php
這是/var/apache2/error.log
[Sun Aug 27 05:13:13.392185 2023] [php7:warn] [pid 77733] [client 127.0.0.1:54732] PHP Warning: move_uploaded_file(uploads/null.txt): failed to open stream: No such file or directory in /var/www/html/upload.php on line 5 [Sun Aug 27 05:13:13.392251 2023] [php7:warn] [pid 77733] [client 127.0.0.1:54732] PHP Warning: move_uploaded_file(): Unable to move '/tmp/phpynhUuv' to 'uploads/null.txt' in /var/www/html/upload.php on line 5
上傳狀態(tài)
$ ll > total 8 > drwxr-xr-x 2 root root 4096 Aug 27 05:08 html > drwxrwxrwx 2 www-data www-data 4096 Jun 2 22:38 uploads
誰(shuí)能告訴我我的程式碼有什麼問(wèn)題嗎?任何意見(jiàn)將不勝感激。
附註感謝ADyson和hanshenrik的慷慨指導(dǎo)。這個(gè)問(wèn)題是由兩個(gè)方面造成的:(1)使用-F作為curl命令,(2)更正PHP路徑以適合我的資料夾設(shè)定。
-d
以application/x-www-form-urlencoded
格式發(fā)送數(shù)據(jù),PHP 自動(dòng)將其解析為$_POST
超全域變量,而您的程式碼嘗試從$_FILES
超全域變數(shù)讀取上傳的文件,該文件據(jù)我所知,PHP僅解析multipart/form-data
-requests,並且要使curl發(fā)送multipart/form-data
請(qǐng)求,請(qǐng)使用-F
curl -F @null.txt http://127.0.0.1/upload.php