Search code examples
phpfile-upload

Check file extension in upload form in PHP


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';
}

Solution

  • Using if( $ext !== 'gif') might not be efficient. What if you allow like 20 different extensions?

    Try:

    $allowed = array('gif', 'png', 'jpg');
    $filename = $_FILES['video_file']['name'];
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if (!in_array($ext, $allowed)) {
        echo 'error';
    }