Thursday, March 27, 2014

[PHP][Solved] PHP can’t move uploaded file or image

If using php to upload file (image is a type of file), the image you selected would be placed into a temporary folder (image may may disappear) and you should set code to move to another folder for you to use .
In my case is user can upload file but can’t move the file. That’s mean the image can upload to the temporary folder but can’t move to the folder you want.

To solve the problem, at usual you should check the these 2 things first:

  1. Permission of your folder to upload files. Is that allowed you upload files? (if you want know more, you can search “chmod setting” in google)
  2. Is your upload path existed? (Is the folder you want to place the file exist? If not, maybe you should new some folders..)


The code in this article is from www.scriptime.blogspot.in , that’s is for “PHP Ajax image upload without refresh” and I have taken a part of it to be the example.
For detailed information, you can visit the link at the end of this article to download the full code.

* * *
<?php
$uploaddir = 'http://www.terrapins233.com/includes/images';
$file = $uploaddir ."scriptime_".basename($_FILES['uploadfile']['name']);
$file_name= "scriptime".$_FILES['uploadfile']['name'];

if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
  echo "success";
} else {
echo "error";
?>

According the answer by Webnet in stackoverflow :
$path cannot be a URL, it must be a local path such as /home/user/public_html/

But I don’t know my local path at server, so I go download some php example code about php uploading image for the reference.
The thing I found is most of them using relative path but not the local path be the uploaded files destination.
I have tried that and found works.

<?php
$uploaddir = '../images';
$file = $uploaddir ."scriptime_".basename($_FILES['uploadfile']['name']);
$file_name= "scriptime".$_FILES['uploadfile']['name'];

if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
  echo "success";
} else {
echo "error";
?>
About the reason why caused this problem, why can not use url. It's answered by Loïc Février in stackoverflow.
The upload directory path should be a path on the system, so that we can move the file from temporary folder to another system file.
An URL can't tell the php where the file should be moved in the system (the server).

Reference:
http://stackoverflow.com/questions/3856032/move-uploaded-file-failure
http://www.scriptime.blogspot.in/2012/12/simple-ajax-image-upload.html

No comments :

Post a Comment