How to check file extension in upload form in PHP

0 votes

I check the file extension for upload or not uploaded. My example methods worked, but now I need to understand if my methods (using pathinfo) is true. Is there another better and faster way?

$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if ($ext !== 'gif' || $ext !== 'png' || $ext !== 'jpg') {
    echo 'error';
}
Nov 8, 2020 in PHP by kartik
• 37,510 points
14,967 views

1 answer to this question.

0 votes

Hello @kartik,

Using if( $ext !== 'gif') might not be efficient. 

Try:

$allowed = array('gif', 'png', 'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
    echo 'error';
}
answered Nov 8, 2020 by Niroj
• 82,860 points

Related Questions In PHP

0 votes
0 answers
0 votes
1 answer

How to check whether property exists in object or class in php?

Hello @kartik, Using  property_exists( mixed $class , string $property ...READ MORE

answered Oct 1, 2020 in PHP by Niroj
• 82,860 points
4,984 views
0 votes
1 answer

How to Check for a Specific Type of Object in PHP

Hello @kartik, You can use instanceof: if ($pdo instanceof PDO) ...READ MORE

answered Oct 30, 2020 in PHP by Niroj
• 82,860 points
1,137 views
0 votes
1 answer

How to check if a string is an email address in PHP?

Hello, Try this without regular expressions: <?php ...READ MORE

answered Nov 3, 2020 in PHP by Niroj
• 82,860 points
2,297 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...