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 the hierarchy of constant definitions in inherited classes be efficiently compared and analyzed?
- Wie kann man sinnvoll ein Template erweitern, um das gewünschte Vorhaben umzusetzen, anstatt JS mit PHP zu mischen?
- What are the recommended best practices for handling file uploads in PHP to prevent common pitfalls?