Are there specific security considerations to keep in mind when saving files in PHP?

When saving files in PHP, it is important to consider security measures to prevent unauthorized access or malicious file uploads. One common security consideration is to validate file extensions and content types to ensure that only allowed file types are uploaded. Additionally, it is recommended to store uploaded files outside of the web root directory to prevent direct access to the files.

// Validate file extension and content type
$allowedExtensions = ['jpg', 'png', 'pdf'];
$allowedContentTypes = ['image/jpeg', 'image/png', 'application/pdf'];

$uploadedFile = $_FILES['file'];
$extension = pathinfo($uploadedFile['name'], PATHINFO_EXTENSION);
$contentType = mime_content_type($uploadedFile['tmp_name']);

if (!in_array($extension, $allowedExtensions) || !in_array($contentType, $allowedContentTypes)) {
    die('Invalid file type.');
}

// Move uploaded file to secure directory outside of web root
$uploadDir = '/path/to/secure/directory/';
$uploadPath = $uploadDir . basename($uploadedFile['name']);

if (move_uploaded_file($uploadedFile['tmp_name'], $uploadPath)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}