What are the best practices for using move_uploaded_file and copy functions in PHP?
When using the move_uploaded_file and copy functions in PHP to handle file uploads, it is important to ensure proper security measures are in place to prevent potential vulnerabilities such as directory traversal attacks. To mitigate these risks, it is recommended to validate and sanitize user input, check file extensions, and set appropriate file permissions.
// Example of using move_uploaded_file with proper security measures
$uploadDir = 'uploads/';
$allowedExtensions = ['jpg', 'jpeg', 'png'];
if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if(in_array($fileExtension, $allowedExtensions)) {
$newFilePath = $uploadDir . $fileName;
move_uploaded_file($fileTmpName, $newFilePath);
echo 'File uploaded successfully.';
} else {
echo 'Invalid file extension.';
}
}