What steps should be taken to ensure proper syntax and path handling in PHP file upload scripts?

To ensure proper syntax and path handling in PHP file upload scripts, it is important to sanitize user input, validate file types, and use secure file paths. This helps prevent security vulnerabilities such as directory traversal attacks and file execution exploits.

// Sanitize user input
$filename = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);

// Validate file types
$allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
$file_extension = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
    die('Invalid file type.');
}

// Use secure file paths
$upload_dir = '/path/to/upload/directory/';
$target_file = $upload_dir . basename($filename);

if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}