Creating a file upload form

Creating a file upload form

In PHP programming, developers can create a file data upload form on a dedicated web server host location, where Internet users can manually select and upload desired files and data to the server. The created HTML form sends the upload file to the server location via the HTTP protocol, and the PHP server handles the upload file processing, such as validating and processing attributes like where to store the uploaded file, file extension type, maximum file upload size, etc.

Creating a file upload form

File upload form creation process in PHP programming.

  • Create the form in HTML – The created HTML form must have the enctype attribute or attribute set to multipart/form-data to allow the desired file to be uploaded.
  • Handle the uploaded file on the PHP server – After the user submits the form data information to the online PHP server, PHP will process the uploaded user file by applying the $_FILES superglobal variable.

HTML form format for user file data upload.

Here you find an example of a basic, simple HTML form that allows random Internet users to manually select and upload files to a website or webpage.

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8″>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<title>Simple Html File Upload Form</title>

</head>

<body>

<h2>Select file to Upload</h2>

<form action=”upload.php” method=”POST” enctype=”multipart/form-data”>

<label for=”fileUpload”>Select a file</label>

<input type=”file” name=”fileUpload” id=”fileUpload” required>

<br><br>

<input type=”submit” value=”Upload File”>

</form>

</body>

</html>

File Upload Form Explanation.

  • enctype=”multipart/form-data” – This HTML form attribute is required to upload a user-selected file. This method allows HTML user-selected form data to be sent to a dedicated web server in binary data format.
  • type=”file” – This is an HTML form file input field type that allows random Internet users to select the desired upload file.

PHP Program Code to Handle File Uploads in PHP Programming.

After creating the HTML user form, we now create the upload.php file, which helps process the user form file uploaded via the HTML form.

Here, the following checks will be performed on the uploaded file.

  • This will check the user-selected file to see if it has been successfully uploaded to the dedicated server location.
  • The server validates the uploaded file type and file size.
  • Moves the file uploaded by a random user to the desired web directory on the dedicated web server location.

So, let’s create a PHP script to manage user-selected file uploads in PHP.

<?php

// here it used to Check if the html form was submitted and a file is uploaded or not

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’ && isset($_FILES[‘fileUpload’])) {

    // it used to Get the complete details about file

    $file = $_FILES[‘fileUpload’];    // use for file upload method

    $fileName = $file[‘name’];        // used to display Original file name

    $fileTmpName = $file[‘tmp_name’]; // used to display Temporary file name on the server

    $fileSize = $file[‘size’];        // used to get info about File size in bytes

    $fileError = $file[‘error’];      // it display file Error code (if any) possible

    $fileType = $file[‘type’];        // it used to check file MIME type

    // it used to Define allowed file types (ex, images file only)

    $allowedTypes = [‘image/jpeg’, ‘image/png’, ‘image/gif’]; // it allow jpeg,png, gif file type

    // it allow maximum file upload size (ex, 2 MB max size)

    $maxFileSize = 2 * 1024 * 1024; // set here 2 MB file upload in bytes

    // her if statement Check errors for file upload

    if ($fileError !== 0) {

        echo “display error during file uploading process”;

        exit;

    }

    // here it Check file size (ex, fule limit to 2MB max )

    if ($fileSize > $maxFileSize) {

        echo “The uploaded file is too large, please keep it in size less than 2MB”;

        exit;

    }

    // here it Check file type (ex, allow only images file to upload)

    if (!in_array($fileType, $allowedTypes)) {

        echo “unsupported image file type, please upload Only JPG, PNG, and GIF files”;

        exit;

    }

    // we can set manualthe upload image directory

    $uploadDir = ‘uploads/’;

    // here it Make sure the upload image directory must exists, if not exist, it create it

    if (!is_dir($uploadDir)) {

        mkdir($uploadDir, 0001, true);

    }

    // here it Generate a unique upload image file name for the file to avoid overwriting risk

    $uniqueFileName = uniqid(”, true) . ‘.’ . pathinfo($fileName, PATHINFO_EXTENSION);

    // here it Define the upload image file target path

    $targetPath = $uploadDir . $uniqueFileName;

    // here it used to Move the uploaded image file from the temporary location to the target location path

    if (move_uploaded_file($fileTmpName, $targetPath)) {

        echo “File uploaded process success <br>”;

        echo “File name: ” . $uniqueFileName . “<br>”;

        echo “File size: ” . round($fileSize / 1024, 2) . ” KB<br>”;

        echo “File type: ” . $fileType . “<br>”;

    } else {

        echo “Unsucessfull file move or the uploaded file operation”;

    }

}

?>

PHP File Upload Source Code Explanation.

  • $_FILES[‘fileUpload’] – This superglobal variable holds information about the uploaded image file, including the image file name, file size, temporary file location, file error code, and MIME type.
  • Upload File Error Check – This checks the uploaded image file code to see if there were any file errors during the upload process using the $_FILES[‘fileUpload’][‘error’] method. If the file upload error is not 0, it displays a problem, such as a partial upload or a server file error.
  • Upload File Size Check – This checks the upload file size limit, such as the maximum allowed file size limit, to ensure that the uploaded image does not exceed 2 MB.
  • Upload File Type Check – This allows only files with the allowed MIME image file extension type, such as image/jpeg, image/png, etc., to be uploaded to the server. You can adjust the $allowedTypes array to add other file types if needed.
  • Directory Check and Creation – If the upload directory (uploads/) does not exist in the target location, this PHP script will create one using the mkdir() DOS command with True permissions (0001).
  • Renaming the upload file – To prevent similar-named image files from being overwritten, we create a unique file name using uniqid() and add the file extension using the pathinfo() function.
  • Moving the file location – The image file uploaded to the server is moved from its temporary location on the web server to the target directory using the move_uploaded_file() function.

Creating an upload directory in a dedicated location.

Always ensure that the upload file directory already exists on your server, otherwise this PHP program script will create it automatically first. Ensure that the web directory can be created from the web server, and its permissions are set to true, e.g., 0001 for testing.

File upload security considerations.

  • File type validation – Always check the upload file type format extension and MIME type to prevent harmful files from being uploaded to the server, such as .php files or executable files.
  • File size limit – Set a valid maximum file upload limit to prevent random users from uploading large files that could fill up the dedicated web server storage space.
  • Use unique filenames – To prevent files with the same name from being overwritten when uploaded to the server, create unique filenames using methods like the uniqid() function.
  • File permissions – Ensure that the upload directory is compatible with the write attributes, but not publicly executable on the server, to avoid potential security risks on the web server.

A summary of the upload file form in PHP.

  • Create upload HTML form – Here, a form with the HTML form attribute enctype=”multipart/form-data” grants permission to a random Internet user to upload selected desired files.
  • PHP upload file handling – In this, a PHP program source code script uses $_FILES to process the uploaded file, check for upload file errors, check the upload file type, check the maximum file upload size, and move the file to the correct directory.
  • Upload file security – Always validate file extension type, file upload size limit and use unique filename to avoid any kind of conflicts and security risks in uploaded files.

Leave a Reply