bush man bush man - 1 year ago 34
PHP Question

Php upload image to directory

Ive been experimenting with the upload capability of php, I have been looking at this tutorial on w3school.


I installed this script on MYDOMAIN.com/New.html


<form action="upload_file.php" method="post"
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">


And then I put this snippet on MYDOMAIN.com/upload_file.php

$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
if ($_FILES["file"]["error"] > 0)
echo "Error: " . $_FILES["file"]["error"] . "<br>";
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
echo "Invalid file";

Now there is a very high chance that im just a really confused person but what I assume that is suppose to do is take the file I put into the New.html file and if it is a image file upload it onto my directory but instead its just outputting Invalid file Im not sure what to do any help is great hope to hear back soon thank you

Ivo Ivo
Answer Source

The problem of your script is that you are probably trying to upload a file higher that your limit is! You specified a really low max filesize! Print out your $_FILES var to get information about what's wrong ;)

However, in order to move the file to your folder you still need to use move_uploaded_file:

$allow = array("jpg", "jpeg", "gif", "png");

$todir = 'uploads/';

if ( !!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
    $info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file

    if ( in_array( end($info), $allow) ) // is this file allowed
        if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
            // the file has been moved correctly
        // error this file ext is not allowed