简体   繁体   中英

Check file PDF or image before upload

I am studying PHP but I don't get the right way by myself. I'd like having Img always required (and I check this in the form input required attribute) but I can decide if upload PDF or not. The script doesn't continue if I don't select both.

I have this:

    // image select from form
    $img = basename($_FILES['img']['name']);
    $allow_img = array('jpg', 'png', 'jpeg');
    $ext_img = explode('.', strtolower($_FILES['img']['name']));
    $type_img= end($ext_img);

    //pdf select from form
    $pdf = basename($_FILES['pdf']['name']);
    $allow_pdf = array('pdf');
    $ext_pdf = explode('.', strtolower($_FILES['pdf']['name']));
    $type_pdf= end($ext_pdf);

    if ($img || $pdf) {
        if(!in_array($type_img, $allow_img) || !in_array($type_pdf, $allow_pdf) ) {
         echo "<p><a href='../admin.php'><img style='border:none;' src='../../img/arrow-left.png' /></a>Only jpg, png, jpeg and PDF.</p>";       
        } 
    }

Here you go a super fast way to accomplish this:

$filename = $_FILES['img']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

// allowed extensions
$allowed = array('jpeg', 'png', 'jpeg', 'gif');

if (in_array($ext, $allowed)) {
    echo "<p><a href='../admin.php'><img style='border:none;' src='../../img/arrow-left.png' /></a>Only jpg, png, jpeg and PDF.</p>";       
}

That's it :)

You need javascript for this.

Before you send return, you have check type of file.

Most likely the second basename() call crashes, since no $_FILES['pdf'] is present when no pdf file is uploaded. But you don't even check for an error here... Take a look into the http servers error log file, most likely you will see the error there.

That said: always look into the log files if something unexpected happens. And always test for a variables existance before you use it. And always do error checking when calling some function which might not return what you expect.

You can use pathinfo() inbuilt php function,

 $File = $_FILES['image']['name'];
 $Infos = pathinfo($File);
 echo $extension = $info[extension];

 echo "<pre>"; print_r($Infos); echo "</pre>";
 $extension = strtolower( $extension);
 if( $extension=='pdf'){
    // do your stuff
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM