How can the move_uploaded_file function in PHP be used to securely store uploaded files on the server?
When using the move_uploaded_file function in PHP to store uploaded files on the server, it is important to validate and sanitize the file name before moving it to the desired directory. This helps prevent security vulnerabilities such as directory traversal attacks. Additionally, setting the correct file permissions on the target directory can also enhance security.
// Validate and sanitize the file name
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Move the uploaded file to the target directory
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}