How do I save user uploaded files (images) to a specific file instead of the root directory with php?

StackOverflow https://stackoverflow.com/questions/23586612

  •  19-07-2023
  •  | 
  •  

Question

Ok, in my website users can upload images as their profile photos and I save them as $username.jpg so all the image file names are unique. Problem is they all get saved in my root directory making everything there a big mess. So what kind of script will I be needing to automatically save all the photos in a folder called "profileimages"?

This is pretty much the code I have for the moment.

Select an image: <br/> <input type="file" name="profilepicture" size="10" />;

if ($_FILES) {
    if($_FILES['profilepicture']['name']){
        $name = $_FILES['profilepicture']['name'];

        switch($_FILES['profilepicture']['type']){
            case 'image/jpeg': $ext = 'jpg'; break;
            default: $ext = ''; break;
        }

        if ($ext == ''){
            echo '<script> alert("Your uploaded file is of the wrong file type, only jpeg image file types are accepted"); </script>';
        }

        if ($ext){
            $profimg = "$user.$ext";
            move_uploaded_file($_FILES['profilepicture']['tmp_name'], $profimg);
        }
    }
}
Was it helpful?

Solution

You can simple change line

move_uploaded_file($_FILES['profilepicture']['tmp_name'], $profimg);

into

move_uploaded_file($_FILES['profilepicture']['tmp_name'], 'profileimages/'.$profimg);

Of course directory profileimages must exist and have enough permissions to move there file

OTHER TIPS

Just edit the second parameter of move_uploaded_file, like so:

move_uploaded_file($_FILES['profilepicture']['tmp_name'], "profileimg/".$profimg);

The second parameter is the destination.

To make sure that the directory (with possible subdirectorys) is existing you could use as mkdir:

mkdir("/dir1/dir2", 0, true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top