What are the best practices for restricting file formats to only jpg and png in PHP?
To restrict file formats to only jpg and png in PHP, you can use the `$_FILES` superglobal array to check the file type before allowing it to be uploaded. You can use the `pathinfo()` function to get the file extension and then use an `if` statement to only allow jpg and png files to be uploaded.
// Check if the file is a jpg or png before allowing upload
$allowedFormats = ['jpg', 'png'];
$fileName = $_FILES['file']['name'];
$fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
if (!in_array($fileExt, $allowedFormats)) {
echo "Only jpg and png files are allowed.";
exit;
}
// Continue with the file upload process
Keywords
Related Questions
- How can PHP developers ensure proper data validation and sanitization when inserting user input into a MySQL database?
- How can the environment variables like HOME or COMPOSER_HOME affect the execution of shell commands in PHP?
- How can user experience be improved by implementing automatic loading of list items while scrolling in PHP?