What potential pitfalls should be considered when trying to save images directly instead of displaying them in PHP?

When saving images directly in PHP, potential pitfalls to consider include security vulnerabilities such as allowing users to upload malicious files, insufficient validation of file types, and the risk of overwriting existing files. To mitigate these risks, always validate file types, sanitize user input, generate unique filenames, and store files in a secure directory outside of the web root.

// Example code snippet to save an image file securely in PHP

// Validate file type
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_extensions)) {
    die("Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.");
}

// Generate unique filename
$filename = uniqid() . '.' . $file_extension;

// Move uploaded file to secure directory
$upload_dir = 'uploads/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir);
}
move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $filename);

echo "Image uploaded successfully.";