1

I have this code and i want to upload image with it's own name.

<?php
print_r($_FILES);
$new_image_name = "foto1.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"]
,"/home/izmircic/public_html/upload/".$new_image_name);?>  

I tried

<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["name"], "/home/izmircic/public_html/upload/");
?>  

but it didn't work.

2
  • 2
    your first code is near to your goal, just use $_FILES["file"]["name"] instead of $new_image_name) Commented Jul 17, 2013 at 6:47
  • Use tmp_name as it is a dangerous way! Dont forgot to sanitize the tmp_name to block all filename like ../index.php by example and block all php script (like C99 shell) Commented Jul 17, 2013 at 6:52

3 Answers 3

1

The arguments to move_uploaded_file() are the current path including filename and the destination path including filename.

It should be:

move_uploaded_file($_FILES["file"]["tmp_name"] ,"/home/izmircic/public_html/upload/".$_FILES["file"]["name"]);

You should also test for the return value, to see if it failed or not:

$moved = move_uploaded_file($_FILES["file"]["tmp_name"] ,"/home/izmircic/public_html/upload/".$_FILES["file"]["name"]);

if($moved){
    echo 'success';
} else {
    echo 'failed';
}

By allowing uploaded files to keep their original name, you need to validate it for whatever you're doing, for example if you only want images then check the file extension and load the image into the GD library to verify it's actually an image.

For best security it would be better to store the files outside of the document root and use a PHP script to serve them as needed, and preferably with a generated filename instead of allowing the uploader to choose.

Sign up to request clarification or add additional context in comments.

1 Comment

Not the tmp_name, the name is what should be validated. tmp_name is meaningless, it's just a random filename with the temp path.
0
try this
<?php

print_r($_FILES);
$new_image_name = "foto1.jpg";  // remove this one and replace $_FILES["file"]["name"]
move_uploaded_file($_FILES["file"]["tmp_name"]
        , "/home/izmircic/public_html/upload/" . $_FILES["file"]["name"]);
?>

1 Comment

Thanks gayan! Akam said it too. Thanks all of you.
0

I think this might work for you

move_uploaded_file($_FILES["file"]["tmp_name"],".//home/izmircic/public_html/upload/".$_FILES["file"]["name"]);

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.