How can PHP developers ensure that the file path used for uploading files is valid and secure?

To ensure that the file path used for uploading files is valid and secure, PHP developers can use the realpath() function to resolve the path to its absolute form and check if it exists within a specified directory. Additionally, developers should sanitize user input to prevent directory traversal attacks and only allow certain file extensions to be uploaded.

$uploadDir = '/path/to/upload/directory/';

if(isset($_FILES['file'])) {
    $fileName = $_FILES['file']['name'];
    $fileTmp = $_FILES['file']['tmp_name'];
    
    $uploadPath = realpath($uploadDir) . '/' . basename($fileName);
    
    if(strpos($uploadPath, realpath($uploadDir)) !== 0) {
        die('Invalid file path');
    }
    
    // Additional validation and file upload logic here
}