What are the potential security risks of directly saving files to a specific directory in PHP?

Directly saving files to a specific directory in PHP can pose security risks such as allowing malicious files to be uploaded and executed on the server, exposing sensitive information, and potentially overwriting existing files. To mitigate these risks, it is important to validate and sanitize user input, restrict file types and sizes, and set proper file permissions on the target directory.

// Example of saving a file to a specific directory in PHP with security measures

// Define the target directory where files will be saved
$targetDir = 'uploads/';

// Validate and sanitize the uploaded file
if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $targetFile = $targetDir . basename($_FILES['file']['name']);
    
    // Check file type and size
    $fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
    $allowedTypes = array('jpg', 'jpeg', 'png', 'pdf');
    $maxFileSize = 5 * 1024 * 1024; // 5MB
    
    if(in_array($fileType, $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
        // Move the uploaded file to the target directory
        move_uploaded_file($_FILES['file']['tmp_name'], $targetFile);
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}