upload file but directory doesn't exist

2k Views Asked by At

I'm a newbie programmer doing his best to self learn PHP. I'm trying to get a file upload to work, and I'm having some problems. The file seems to successfully upload, but it's temporary location is a location that doesn't exist on the server.

Here's the code I'm using to upload the file:

<?php       
if (isset($_POST['submit']))
{
$imgfile = $_FILES['imgfile']['name'];
$temp = $_FILES['imgfile']['tmp_name'];
$type = $_FILES['imgfile']['type'];

if (!empty($imgfile))
{
        $dbc = mysqli_connect('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME')
    or die('Error connecting to database');
    $query = "INSERT INTO photos VALUES(0, '$imgfile',NOW(), '$temp', '$type')";

        mysqli_query($dbc,$query);

        //clear the form                    
    $imgfile = "";

        mysqli_close($dbc);
    }
}
?>
<form enctype = "multipart/form-data" method = "POST" action = "<?php
echo $_SERVER['PHP_SELF']; ?>">

<label for = "imgfile">Filename:</label>
<input type = "file" id = "imgfile" name = "imgfile"  />
<br />
<input type = "submit" value = "upload" name = "submit" id = "submit" /> 
</form>

These are some examples of locations that the $_FILES['tmp_name'] variable says it's being stored:

/tmp/phpWw6aut

or

/tmp/php4bzVfE

The default temporary directory set in the php.ini file is root/tmp. So that part is right, but then there's that weird /phpgarbage folder supposedly inside the tmp folder that each file is saying that it's in. Only thing is, that those folders don't exist on the server.

Any thoughts? Let me know if there's anything I can be more specific about. This is a first time programming related post for me, so let me know if there's any more information I should be sharing.

Thank you for your time!

3

There are 3 best solutions below

2
On BEST ANSWER

You have to save the image in order to be able to access it later. To do this, add the following code:

$path = "uploads/images/";
if (is_uploaded_file($_FILES['imgfile']['tmp_name'])) {
    move_uploaded_file($_FILES["imgfile"]["tmp_name"], $path . $_FILES["imgfile"]["name"]);
}

after the following lines:

if (!empty($imgfile))
{

Note that the $path must be writeable. And now the filename becomes $path.$_FILES["imgfile"]["name"]. Also make sure to implement some security checks, your code is vurnerable.

0
On

You need to move it from temp storage to your directory...

if (is_uploaded_file( $_FILES['imgfile']['tmp_name'] )) {
    move_uploaded_file( $_FILES['imgfile']['tmp_name'], '/path/filename.jpg' );
}
0
On

Try using this method to control where you want to store the file. http://us.php.net/manual/en/function.move-uploaded-file.php