user2389087
user2389087

Reputation: 1762

php file upload and move to folder

This is my php code

<?php
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("upload/" . $_FILES["file"]["name"]))
        {
            echo $_FILES["file"]["name"] . " already exists. ";
        }
        else
        {
            mkdir("upload/".$title, 0700);
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/".$title . $_FILES["file"]["name"]);
            echo "Stored in: " ."upload/".$title . $_FILES["file"]["name"];
        }
    }
?> 

Simple file upload according to W3C, however i added the mkdir to create a directory based on the title the user input.

The folder creates fine but the file won't move into it, not sure if this is something simple i thought but use the concatenate '.' i could just define the file location like i had with mkdir

The HTML is simple just input type = file and and input text type for the title

Upvotes: 0

Views: 17000

Answers (2)

Amal
Amal

Reputation: 76646

You're missing a slash in your path, as pointed out by @Grim above. I'd like to explain why:

echo "Stored in: " ."upload/".$title . $_FILES["file"]["name"];
                                  --^

Changing it to the following should fix the problem:

echo "Stored in: " ."upload/".$title . "/" . $_FILES["file"]["name"];

Your path is incorrect and move_uploaded_file will be unable to find the file in the specified path and your code won't work as you expect it to.

Without the slash, this is what your function would actually look like (assuming you define $title variable somewhere in between):

upload/fooFilename

You actually need:

upload/foo/Filename

Hope this helps!

Upvotes: 0

Grim...
Grim...

Reputation: 16953

You need a / after $title to use the new folder.

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

Upvotes: 3

Related Questions