PHP

PHP Menu

PHP

File Upload - PHP Advance

All sorts of files can be uploaded using PHP. They can be images, videos, text and even executable files. To do this, first enable the file_uploads setting to on in the php.ini file.

The first step in uploading files in PHP is to create an HTML Form. The form method="POST" and enctype="multipart/form-data" are required for the file upload.

<!DOCTYPE html>
<html>
<body>

<form action="uploader.php" method="post" enctype="multipart/form-data">
        Upload Image:
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Then, create the PHP script for uploader.php. the image_uploads directory should be created inside the directory of the uploader.php file.

<?php

$target_dir = "image_uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
             echo "File is an image - " . $check["mime"] . ".";
             $uploadOk = 1;
        } else {
             echo "File is not an image.";
             $uploadOk = 0;
        }
}

Below are some scripts to help with checking and adding restrictions on your uploader script.

The following code snippet restricts file upload to JPG, JPEG, PNG and GIF files only:

if($FileType != "jpg" && $FileType != "png" && $FileType != "jpeg" && $FileType != "gif" ) {
    echo "Invalid File Type.";
        $uploadOk = 0;
}

The following code snippet restricts file upload up to 1MB only:

if ($_FILES["fileToUpload"]["size"] > 1000000) {
        echo "File is too large.";
        $uploadOk = 0;
}

The following code snippet checks if the file to be uploaded already exists in the image_uploads directory:

if (file_exists($target_file)) {
        echo "File already exists";
        $uploadOk = 0;
}

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods