How can PHP functions like move_uploaded_file() and chmod() be used securely and efficiently in file upload scripts?

To use PHP functions like move_uploaded_file() and chmod() securely and efficiently in file upload scripts, it is important to validate user input, sanitize file names, set proper file permissions, and store uploaded files in a secure directory outside the web root. Additionally, consider implementing file type and size checks to prevent malicious uploads.

// Example of a secure file upload script using move_uploaded_file() and chmod()

// Set upload directory outside web root
$uploadDirectory = '/path/to/upload/directory/';

// Validate file type and size
$allowedTypes = array('jpg', 'jpeg', 'png', 'gif');
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    $newFileName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    
    // Move uploaded file to secure directory
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $newFileName)) {
        // Set proper file permissions
        chmod($uploadDirectory . $newFileName, 0644);
        echo 'File uploaded successfully.';
    } else {
        echo 'Failed to upload file.';
    }
} else {
    echo 'Invalid file type or size.';
}