简体   繁体   中英

Cant move uploaded file using php move_uploaded_file()

I have a page which allows users to post an advert on my website. This page allows them to upload multiple photos of the product in question.

I currently have two forms. The first handles details of the product, while the second is a dropzone (using dropzone.js) allowing them to upload photos. I am keen to keep these forms split as the photos could potentially be very large and I would prefer them to upload instantly rather than waiting for the user to press submit. This should save time overall.

Therefore, when the photos are put into dropzone, they are uploaded to a tmp directory (in case the user does not post the entire advert). Once the user submits the first form, I am using move_uploaded_file() to move the file to its permanent location. This is the code I am using:

for ($loop=1; $loop<=6; $loop++) {

    // Retrieve filename and path
    $file_path = "image_".$loop;
    $tmp_path = $form_data[$file_path]; // $form_data is an array of POST data and contains the file_path of the image in the tmp dir

    // Move file
    $destination_path = 'images/adverts/'.$advert->id;
    $success = move_uploaded_file($tmp_path, $destination_path);

}

However, move_uploaded_file() is not working. After consulting the documentation, I can see that move_uploaded_file() checks to see whether the file was uploaded using HTTP POST (which it was). To be sure, I ran a quick test to see whether is_uploaded_file() returned TRUE on my uploaded file, but it didn't.

How does is_uploaded_file() determine whether a file was uploaded or not? I was wondering whether by the time I come to move the file, php has forgotten it has been uploaded? Is there any other reason my file would not pass this?

Many thanks

I think Ive got to the bottom of this...

move_uploaded_file() only seems to work in the function that the POST data is sent to. In my case, I had two separate POST requests sent. The first from dropzone.js which stored the image in a tmp directory. If I had run the is_uploaded_file() in the function that received that POST request, it returned TRUE.

However, once uploaded to a tmp directory, I then inserted paths in hidden fields in the second form. I was trying to run move_uploaded_file() (which in turn uses is_uploaded_file()) in the function which receives the POST data from the second form. However, as the file was not part of this POST data (just the path to the tmp dir), is_uploaded_file() then returned false.

I hope that helps someone...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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