Handling file uploads securely with PHP

Handling file uploads securely with PHP

Managing the file upload process in PHP programming in a secure manner is helpful in protecting a dedicated web server or web application from malicious file activities that could put a dedicated web server host or application in a dangerous situation. PHP programming provides users with several built-in functions for file uploading. It’s important to use these functions carefully, as they may allow security vulnerabilities for your server.

Handling file uploads securely with PHP

To ensure a secure file upload process in PHP programming, best practices should be followed and proper security checks and precautions should be applied to file uploads.

File Type Validation in PHP.

One of the most important security checks when uploading forms in PHP programming is validating file type extensions. While allowing Internet users to upload files arbitrarily can leave dedicated website servers vulnerable to malicious files like PHP web scripts, which can be executed on the web server without administrator permission.

How to Secure File Type Validation in PHP Programming.

  • In PHP programming, use the form file upload extension check as well as the MIME file type check ($_FILES[‘file’][‘type]) method.
  • When uploading files, don’t rely solely on the file extension, such as .jpg, as it can be easily manipulated.
  • Upload File Content Information: Apply the getimagesize() function to image files to verify the content.

Example of checking MIME types in a PHP file upload.

$allowedTypes = [‘image/jpeg’, ‘image/png’, ‘image/gif’];

$fileType = $_FILES[‘fileUpload’][‘type’];

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

echo “Display Error – Only permitted JPG, PNG, and GIF image files”;

exit;

}

For additional file upload security, for uploaded image files, use the getimagesize() function to verify that the uploaded file is a real image.

if ($fileError === 0) {

$imageDetails = getimagesize($fileTmpName);

if ($imageDetails === false) {

echo “Display Error – Your uploaded image file is not a valid image format”;

exit;

}

}

Limit the size of uploaded files on the server.

Permitting random online users to upload large amounts of files can create unnecessary storage load on your dedicated web server. This can threaten a denial of service (DoS) attack by using up extra disk storage space or memory on your web server.

How to limit the upload file size?

  • Use the $_FILES[‘file’][‘size’] array method to check the file size of a random user upload.
  • Fix the maximum image file upload size limit at 2 MB.

Example of checking the upload file size in PHP.

$maxFileSize = 2 * 1024 * 1024; // set the upload image file size to a maximum of 2MB in bytes

if ($_FILES[‘fileUpload’][‘size’] > $maxFileSize) {

echo “Display Error – The upload file is too large, Maximum upload size is 2 MB.”;

exit;

}

With this, developers can manually limit the image file upload size in the PHP configuration file php.ini on their web hosting service.

upload_max_filesize = 2M

post_max_size = 10M

Use the move_uploaded_file() method instead of copy() in file uploads.

Always apply the built-in PHP function move_uploaded_file() to move a user-selected uploaded image file from its temporary storage location to the desired directory. This ensures that the image file is actually uploaded, and not manipulated during the file upload process.

Example of move_uploaded_file() for moving a file upload in PHP.

$targetPath = $uploadDir . $uniqueFileName;

if (move_uploaded_file($_FILES[‘fileUpload’][‘tmp_name’], $targetPath)) {

echo “Upload file process success”;

} else {

echo “Display Error – Failed process to move the uploaded file”;

}

Generate unique file names for uploaded image files

To prevent random users from overwriting uploaded image files or from allowing an attacker to replace a file with a malicious file, especially if they succeed in uploading a file with the same name as an existing file, always use file names with specific names.

A simple and effective method for generating files with specific names during the file upload process is to apply the uniqid() function.

Example of generating a unique file name in PHP.

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

The method above ensures that each file uploaded by a random user will have a specific unique name, thereby avoiding any possible conflicts in file storage locations.

Check the upload image file extension.

MIME type validation of the uploaded image file is important here. Developers should also check the upload file extension to ensure it matches the specified format type. For example, .exe or .php files should never be allowed to be uploaded to a live server, especially in publicly available server directories.

Example to validate the upload image file extension.

$allowedExtensions = [‘jpg’, ‘jpeg’, ‘png’, ‘gif’];

$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

if (!in_array($fileExtension, $allowedExtensions)) {

echo “Display Error – unsupported file extension, only supported extensions are JPG, PNG, and GIF formats”;

exit;

}

Ensure a secure file upload directory for upload files.

In the upload image file location, ensure that the upload file directories are not publicly available. Store uploaded image files in web directories outside the publicly available root, or block or control file execution with .htaccess to prevent them from being executed.

For example, if developers are storing files in the upload folder itself, ensure that the following code is present in .htaccess within this upload folder.

# it Prevent access to the upload files directories

<Files “*.php”>

deny from all

</Files>

Upload Directory Permissions – Ensure that the upload image directories have secure permissions (typically 755 or 775), and avoid setting them to world-writable (i.e., 777).

Example of moving upload files to a secure directory.

$uploadDir = ‘../uploads/’; // Here it uploads the image outside the public web directory

if (!is_dir($uploadDir)) {

mkdir($uploadDir, 0775, true); // Here it helps to create a web directory with secure permissions

}

Validate the upload image file path.

Web directory traversal attack where a malicious intruder or attacker uploads a file with a path like ../../../../etc/passwd. To prevent such activities, always clean the file path and ensure it does not contain any dangerous characters like ../.

Example of cleaning the upload file path.

$fileName = basename($_FILES[‘fileUpload’][‘name’]); // Here this code is used to remove any path information

$targetPath = $uploadDir . $fileName; // Here it displays the full path to move the uploaded file

// Here it ensures the file does not contain any dangerous paths or file components

if (strpos($fileName, ‘..’) !== false || strpos($fileName, ‘/’) !== false) {

echo “Display Error – unsupported file name”;

exit;

}

Upload File Permissions.

After uploading a file to a web directory, ensure the upload file has proper permissions. Do not set file permissions to 777, as this would allow any user to modify and update the uploaded file. Instead, use file permissions of 644 or 755, depending on the specific purpose of the file.

Restrict file uploads by upload file type.

Here, the developer should clearly define what types of files your application will accept. For example, if you only need to upload image files, apply it by checking the MIME type and file extension in the file upload, and avoid uploading unnecessary file formats like .exe, .php, .js, etc.

Restrict the file upload process to certain users in the upload file.

If necessary, restrict or limit any type of file upload to certain users. This allows you to manage access to your webpage or web app only for authenticated users, special admin roles, or users with specific permissions.

File upload error handling and logging.

Properly manage errors generated in the file upload process and log any file upload attempts, especially failed upload attempts. This will help you identify any malicious or sensitive activities in your application.

if ($_FILES[‘fileUpload’][‘error’] !== 0) {

echo “Display Error – Some of the problems during file upload”;

exit;

}

Example of a secure file upload script in PHP.

Here’s a simple, secure file upload script you can implement on your web server or application to securely process file uploads.

<?php

// this code help us to Handle file upload process securely

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

    $file = $_FILES[‘fileUpload’];

    $fileName = basename($file[‘name’]);

    $fileTmpName = $file[‘tmp_name’];

    $fileSize = $file[‘size’];

    $fileError = $file[‘error’];

    $fileType = $file[‘type’];

    // below code help us to only Allowed file types and max upload size is 2 MB

    $allowedTypes = [‘image/jpeg’, ‘image/png’, ‘image/gif’];

    $maxFileSize = 2 * 1024 * 1024;  // here it restrict upload file size is only 2MB

    // this code used to Check for upload file errors

    if ($fileError !== 0) {

        echo “Display Error – generate issue during file uploading”;

        exit;

    }

    // this code used to Check the upload file max size

    if ($fileSize > $maxFileSize) {

        echo “Display Error – upload file is too large. only max file upload size is 2MB”;

        exit;

    }

    // here it used to Check file type

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

        echo “Display Error – Invalid file extension, it support only types is – JPG, PNG, GIF”;

        exit;

    }

    // this code help to Generate unique filename for all upload file

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

    $uploadDir = ‘uploads/’;

    // this code Create a upload directory if it doesn’t exist with permission

    if (!is_dir($uploadDir)) {

        mkdir($uploadDir, 0775, true);

    }

    $targetPath = $uploadDir . $uniqueFileName;

    // this code used to Move the uploaded file from temporary location to permanent location

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

        echo ” file upload success”;

    } else {

        echo “Display Error – unable to move the uploaded file”;

    }

}

?>

php file upload handling conclusion.

  • By properly following these steps, you can manage the file upload process in PHP in a secure manner.
  • You can verify the upload file type and file size.
  • Use unique file names to prevent the upload file from overwriting.
  • Here, you should first ensure that your upload file directories are secure and protected, and that no executable source code is compatible.
  • Always clean upload file paths and check for dangerous characters.
  • Limit upload file types to only those needed.

Leave a Reply