Mucca019
Mucca019

Reputation: 201

php upload file restrictions

Im trying to limit my upload to only upload file extensions with a pdf. I've previously got the upload working but with any extension using ;

$form = $_FILES['form']['name'];
$upload = "forms/$form";
move_uploaded_file($_FILES['form']['tmp_name'],$upload);

I'm now trying to adjust this to only upload pdf, Using the following;

if (isset($_FILES['file']))
    $exten = explode( "." , $_FILES['form']['name']);
    $exten = $exten[1];
    $form = $_FILES['form']['name'];
    $upload = "forms/$form";

    if (
        ($exten == "pdf")
    ||  ($exten == "PDF")){
    move_uploaded_file($_FILES['form']['tmp_name'] , $upload);

    }

However the files are not uploading to the directory anymore plus it accepts any extension. It is entering the filename within my database. I followed a tutorial for this but not sure where I've gone wrong

Upvotes: 2

Views: 92

Answers (2)

Artem Ilchenko
Artem Ilchenko

Reputation: 1035

You can check file type this way:

if ($_FILES['form']['type'] == 'application/pdf') {
    move_uploaded_file($_FILES['form']['tmp_name'] , $_FILES['form']['name']);
}

$_FILES['form']['type'] contains MIME type of uploaded file

http://php.net/manual/en/features.file-upload.post-method.php

Upvotes: 1

Ace_Gentile
Ace_Gentile

Reputation: 244

to get file extension try pathinfo with PATHINFO_EXTENSION parameter, it will save you time

You should also use strtolower function to make a comparison because for example .PdF/.PDf extensions will be unexpectedly rejected by the condition you wrote

if (isset($_FILES['file'])) {
    $exten = pathinfo($_FILES['form']['name'], PATHINFO_EXTENSION);
    $form = $_FILES['form']['name'];
    $upload = "forms/$form";

    if (strtolower($exten) == 'pdf'){
    move_uploaded_file($_FILES['form']['tmp_name'] , $upload);

    }
}

PS: did you miss brackets after isset function or is just a copy-paste issue?

Upvotes: 1

Related Questions