senty
senty

Reputation: 12847

File::extension() doesn't work with if in Laravel

I have run into a weird problem. I am using File::extension($file) and actually getting the answer as 'pdf'. I var_dump() the File::extension($file) and it shows the value if string with 3 characters that is 'pdf' for sure.

Then I try to compare it in an if statement, but it goes into the if statement where it shouldn't. It's such a weird behaviour.

$fileType = File::extension($request->frequencyPlan->getClientOriginalName());

if ($fileType != 'pdf' || $fileType != 'doc') {
    return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};

Am I missing out something?


P.S: For those who are wondering, I couldn't use mimeType validator because I get another error

'Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'

and I think the upper if statement should work anyway.

Upvotes: 1

Views: 1079

Answers (2)

MohamedSabil83
MohamedSabil83

Reputation: 1559

Try this:

$fileType = $request->frequencyPlan->extension();

if ($fileType !== 'pdf' && $fileType !== 'doc') {
  return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};

and for your other issues:

'Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'

Hosting server:

  • contact the hosting provider and tell him to enable this extension php_fileinfo.

Local hosting:

  • what's your operating system?

Upvotes: 3

patricus
patricus

Reputation: 62288

Your if statement has a logic error.

When $fileType is equal to pdf, your if condition will still evaluate to true. $fileType != 'pdf' will be false, but the second half, $fileType != 'doc' is true, and since you have "or"ed these conditions together, the result is true.

Let $fileType = 'pdf'.
Then $fileType != 'pdf' is false.
Then $fileType != 'doc' is true.

Therefore, ($fileType != 'pdf' || $fileType != 'doc') === (false || true) === (true), which enters the if branch.

I'm assuming you want to enter the if branch if the extension is not "pdf" and is not "doc".

Your code should be:

if ($fileType != 'pdf' && $fileType != 'doc') {
    return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};

Upvotes: 1

Related Questions