How can the PHP function move_uploaded_file() be used to handle file uploads securely?

When using the PHP function move_uploaded_file() to handle file uploads securely, it is important to validate and sanitize the file before moving it to the desired location. This can help prevent malicious files from being uploaded to the server and executed. Additionally, setting the appropriate permissions on the upload directory can further enhance security.

// Validate and sanitize the uploaded file
$allowed_extensions = array('jpg', 'jpeg', 'png');
$upload_dir = 'uploads/';
$target_file = $upload_dir . basename($_FILES['file']['name']);
$upload_ok = true;

$extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if (!in_array($extension, $allowed_extensions)) {
    echo "Invalid file format. Only JPG, JPEG, and PNG files are allowed.";
    $upload_ok = false;
}

// Move the uploaded file to the desired location if validation passes
if ($upload_ok) {
    if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";
    }
}