What potential pitfalls should be avoided when using the move_uploaded_file function in PHP?
One potential pitfall to avoid when using the move_uploaded_file function in PHP is not properly sanitizing the file path before moving the uploaded file. This can lead to security vulnerabilities such as directory traversal attacks. To prevent this, always validate and sanitize the file path before using it in the move_uploaded_file function. Additionally, make sure to set appropriate file permissions on the destination folder to prevent unauthorized access.
$uploadDir = '/path/to/uploaded/files/';
$filename = basename($_FILES['file']['name']);
$destination = $uploadDir . $filename;
// Validate and sanitize the file path
if (strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
die('Invalid file path');
}
// Move the uploaded file to the destination folder
if (move_uploaded_file($_FILES['file']['tmp_name'], $destination)) {
echo 'File uploaded successfully';
} else {
echo 'Failed to upload file';
}