Can you provide examples of common vulnerabilities in PHP file upload systems and how to avoid them?

One common vulnerability in PHP file upload systems is allowing users to upload executable files, which can lead to remote code execution. To avoid this, always validate the file type and only allow specific file extensions to be uploaded. Additionally, store uploaded files outside of the web root directory to prevent direct access to them.

// Check file type before allowing upload
$allowedExtensions = array('jpg', 'png', 'pdf');
$uploadedFileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($uploadedFileExtension, $allowedExtensions)) {
    die('Invalid file type. Only JPG, PNG, and PDF files are allowed.');
}

// Move uploaded file to a secure directory outside of the web root
$targetDirectory = '/path/to/secure/directory/';
$targetFile = $targetDirectory . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}