What are some common PHP scripts used for file uploads?
When working with file uploads in PHP, it is important to ensure that the uploaded files are handled securely to prevent any security vulnerabilities. Common PHP scripts used for file uploads include checking file size, file type, and file extensions to ensure that only allowed files are uploaded. Additionally, it is important to move the uploaded files to a secure directory on the server and sanitize the file names to prevent any malicious scripts from being executed.
<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
// Specify allowed file types
$allowed_types = array('pdf', 'doc', 'docx');
// Get file extension
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
// Check if file extension is allowed
if(in_array($file_ext, $allowed_types)){
// Move uploaded file to secure directory
move_uploaded_file($file_tmp, "uploads/" . $file_name);
echo "File uploaded successfully!";
} else {
echo "Invalid file type. Allowed file types are pdf, doc, docx.";
}
} else {
echo "Error uploading file.";
}
?>