1

I trying to upload a photo to my server using PHP but the script always goes to the else statement and I can not work out why.

if (isset($_POST['submit'])) {

$image=($_FILES['image']['name']);
$target = "../../portfolio/photos";
$target = $target . basename( $_FILES['image']['name']);


if(move_uploaded_file($_FILES['image']['name'], $target))
{
    $sql_addProduct = "INSERT INTO photos (img_url) VALUES '$image'";
    $queryresult_add = mysql_query($sql_addProduct);

    echo "The file ". basename( $_FILES['image']['name']). " has been uploaded succesfully";
}
else {
    //Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}}

Can anyone shed any light on this issue?

3
  • 1
    Did you try to validate the $_FILES first? Commented Aug 6, 2011 at 15:55
  • Read the Docs: Handling file uploads - this section of the manual has all information you need for your code as well as examples and user-comments with useful hints. Commented Aug 6, 2011 at 15:56
  • BTW: If you fixed your file issue, protect your database against SQL-Injection via the uploaded file-name. Commented Aug 6, 2011 at 16:04

2 Answers 2

4
move_uploaded_file($_FILES['image']['name']

should be:

move_uploaded_file($_FILES['image']['tmp_name']
Sign up to request clarification or add additional context in comments.

3 Comments

Correct! move_uploaded_file returns false if the filename is not valid.
In other words: ['name'] is the filename as provided by the client. ['tmp_name'] is the temporary file that PHP stored the upload in, and is what you need to use as the 'source' for the move command.
I have replaced 'name' with 'tmp_name' and now receive this error Warning: move_uploaded_file(../../robyn/photos/imagetest.jpg) [function.move-uploaded-file]: failed to open stream: No such file or director
0

Check $_FILES["image"]["error"] if file is correctly uploaded. Then it may be useful (and more secure) to check if it is image with getimagesize($_FILES["image"]["tmp_name"]);. Then you can move it with move_uploaded_file($_FILES["image"]["tmp_name"], $target); If it still not working, check if directory is writtable is_writable($target);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.