What is the potential issue with the code provided for uploading and displaying an image in PHP?
The potential issue with the code provided is that it is vulnerable to file upload attacks if not properly sanitized. To solve this issue, it is important to validate and sanitize the uploaded file to ensure it is an actual image file before allowing it to be displayed.
// Validate and sanitize the uploaded file
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$upload_folder = 'uploads/';
if(isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
$file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(in_array($file_extension, $allowed_extensions)) {
$file_path = $upload_folder . $_FILES['image']['name'];
move_uploaded_file($_FILES['image']['tmp_name'], $file_path);
// Display the uploaded image
echo '<img src="' . $file_path . '" alt="uploaded image">';
} else {
echo 'Invalid file format. Only JPG, JPEG, PNG, GIF files are allowed.';
}
}
Related Questions
- What is the difference between using a while loop and a foreach loop when retrieving and displaying data in PHP?
- Are there any alternative methods in PHP or JavaScript to achieve the same functionality without using exec functions?
- What steps can be taken to ensure that HTML code within a text file is properly displayed when read and output in PHP?