PHP – File Upload Filter ($_FILES)

If you allow you users to upload files to your web server you will probably want to create some restrictions. You can block uploads based off of file size, extension, or if a filename already exists.

Prerequisites:

  • Basic LAMP, or Web Server Administration 
    • Verify folder has WRITE permission for OTHER
  • Basic PHP
  • Basic HTML

in_array()

file_exists()

pathinfo()

basename()

move_file_upload()

$_FILE

LAMP Server

  • Create a “pics” directory in the Public Web Directory (/var/www/html)
  • Verify folder has at least a w– permission.

PHP.ini

  • Location on demo system: /etc/php/7.2/apache2/php.ini
  • Set File Uploads to: file_uploads = On
  • Modify Max File size if needed: upload_max_filesize =2M

fileUpload.php

<?php

$dir = "./folder/";
$filename = $dir.basename($_FILES['Upload']['name']);
$filenameArray = pathinfo($filename);
$ext = array("jpeg","jpg","gif");
$isGood = 0;

if (file_exists($filename)) {
    echo "The file already exists<br>";
    $isGood = 1;
}

if ($_FILES['Upload']['size'] > 50000) {
    echo "File is over 50kB in size<br>";
    $isGood = 1;
}

if (!in_array($filenameArray['extension'],$ext)) {
    echo "File Type is not Allowed (Upload jpeg, jpg,gif)<br>";
    $isGood = 1;
}

if ($isGood != 1) {
    if (move_uploaded_file($_FILES['Upload']['tmp_name'], $filename)){
        echo "<p>File was uploaded --> ".$_FILES['Upload']['name'];
    } else {
     echo "Upload failed".$_FILES['Upload']['name'];
    }
}

?>
<br>
<a href="./fileUpload.html">Back</a>

fileUpload.html

<html>
<head></head>
<body>
    <h1>File Upload Form</h1>

    <form action="fileUpload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="Upload">
        <input type="submit">
    </form>
</body>

</html>

Be the first to comment

Leave a Reply