Script for PHP upload image file to Server using move_uploaded_file()

PHP is a high level server side programming language. To upload an image file first you need to update the php.ini file. Open the php.ini file. Search “file_uploads”. Update the line “file_uploads = On”.

Then to upload the file you need to Create HTML. Look at the example below. Here I have a input type=”file” control & a submit button. Both these controls are inside the form element. With form I am using post method to send my image files to the server. Finally after successful uploading showing File Name, Size & Type to the user using a UL li element.

To restrict user on file type to upload I created an array “expensions”. Here you can declare any specific file type you want to allow the user. In this example I allowed “jpeg”,”jpg”,”png”.

During file upload to track the errors I am with one more array “errorlog”. In case of a failure I am displaying the error details using echo function.

Script for PHP upload image

<?php
if(isset($_FILES['uploader'])){

$errorlog = array();

$fileSize = $_FILES['uploader']['size'];
$fileType = $_FILES['uploader']['type'];
$fileTemp = $_FILES['uploader']['tmp_name'];
$fileName = $_FILES['uploader']['name'];

$fileExtension = strtolower(end(explode('.',$_FILES['uploader']['name'])));

$expensions= array("jpeg","jpg","png");

if(in_array($fileExtension,$expensions)=== false){
$errorlog[] = "This file type is not allowed, Select a JPEG or PNG file.";
}

if($fileSize > 2097152){
$errorlog[] = 'Your file size is more than 2 MB. Upload a file less then 2 MB.';
}

if(empty($errors)==true){
move_uploaded_file($fileTemp,"images/".$fileName);
echo "Successfully Uploaded.";
}
else {
print_r($errorlog);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploader" />
<input type="submit"/>
<ul>
<li>Sent File - <?php echo $_FILES['uploader']['name']; ?></li>
<li>File Size - <?php echo $_FILES['uploader']['size']; ?></li>
<li>File Type - <?php echo $_FILES['uploader']['type']; ?></li>
</ul>
</form>
</body>
</html>

Security Considerations

When handling file uploads, security is paramount. Here are some best practices to enhance security:

## 1. Validate File Types

Always validate the file type and only allow specific types of files to be uploaded. This reduces the risk of malicious files being uploaded.

## 2. Rename Uploaded Files

To prevent overwriting existing files and to avoid potential security risks, rename uploaded files. Use a unique identifier, such as a timestamp or a random string, in the filename.

“`php $newFileName = time() . ‘_’ . basename($fileName); $dest_path = $uploadFileDir . $newFileName; “`

## 3. Restrict File Size

Limit the size of uploaded files to prevent denial-of-service attacks. This can be done through PHP settings and additional validation in the upload script.

## 4. Set Proper Permissions

Ensure that the upload directory has appropriate permissions. It should be writable by the web server, but not executable. This reduces the risk of executing uploaded files.

## 5. Use HTTPS

Always use HTTPS for your server to encrypt data during transmission. This prevents man-in-the-middle attacks where data can be intercepted.

Error Handling

Error handling is critical in file uploads. PHP provides various error codes that can help diagnose issues. Below is a brief explanation of common error codes:

UPLOAD_ERR_OK (0): No error, the file uploaded successfully.
UPLOAD_ERR_INI_SIZE (1): The uploaded file exceeds the `upload_max_filesize` directive in `php.ini`.
UPLOAD_ERR_FORM_SIZE (2): The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form.
UPLOAD_ERR_PARTIAL (3): The uploaded file was only partially uploaded. – UPLOAD_ERR_NO_FILE (4): No file was uploaded.

Conclusion

Uploading image files to a server using PHP involves multiple steps, from creating an HTML form to implementing server-side validation and security measures. By following best practices—such as restricting file types, renaming files, and validating content—developers can ensure a robust and secure file upload system. Always test the implementation thoroughly to handle edge cases and provide meaningful feedback to users. Properly managing file uploads enhances both functionality and security in web applications.