How to solve the problem of "cannot move" error when Curl uploads files to PHP
P粉904191507
P粉904191507 2024-02-17 18:51:11
0
1
445

I want to set up a simple HTTP service (using PHP) to receive files from another computer using Linux curl and Windows Powershell. I have read from internet sources including PHP cannot upload files to server? Use cURL to upload POST data along with the file. These posts helped me solve the parameter problem, but not all.

This is my code (see here)

<?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.";
}
?>

This is the command I used and received the error response.

# bash
curl -X POST -F "id=fileToUpload" -F "fileToUpload=@null.txt" http://127.0.0.1/upload.php

This is /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

Upload status

$ 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

Can anyone tell me what's wrong with my code? Any advice would be greatly appreciated.

P.S. Thanks to ADyson and hanshenrik for their generous guidance. This problem was caused by two things: (1) using -F as the curl command, (2) correcting the PHP path to fit my folder setup.

P粉904191507
P粉904191507

reply all(1)
P粉348088995

-d Send data in application/x-www-form-urlencoded format, PHP automatically parses it into a $_POST superglobal variable, and you The code tries to read the uploaded file from the $_FILES superglobal variable, which as far as I know PHP only parses multipart/form-data-requests, and to make curl send multipart/form-data request, please use -F

curl -F @null.txt http://127.0.0.1/upload.php
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template