How can the pathinfo() function be used effectively in PHP file upload scripts?

When handling file uploads in PHP, the pathinfo() function can be used effectively to extract information about the uploaded file, such as the file extension or filename. This can be useful for validating file types, renaming files, or storing file information in a database. By using pathinfo() in conjunction with file upload scripts, developers can ensure that the uploaded files are processed correctly and securely.

<?php

// Check if file is uploaded
if(isset($_FILES['file'])){
    $file_name = $_FILES['file']['name'];
    
    // Get file extension using pathinfo()
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    
    // Validate file extension
    if($file_extension == 'jpg' || $file_extension == 'png' || $file_extension == 'pdf'){
        // Process the file upload
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $file_name);
        echo 'File uploaded successfully!';
    } else {
        echo 'Invalid file type. Only JPG, PNG, and PDF files are allowed.';
    }
}
?>