How to check for the correct file extension in PHP?

3.3k views Asked by At

So basically, I am simply just trying to check for the correct file extension on a file that is being uploaded.

I know, this question has been answered on here a few times before, although I keep getting the same error and there is no solution or suggestions out there to why this is happening.

Here is my code:

$file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
$ext = pathinfo($file, PATHINFO_EXTENSION);

if($ext != "csv")
{
    $errors[] = "Sorry, but only CSV files are supported";
}

Here is my error:

Warning: pathinfo() expects parameter 1 to be string

I have tried around 3 other alternatives now, all using pathinfo(). Although, the exact same error is still shown.

Does anyone have any suggestions to why this is happening?

4

There are 4 answers

0
AudioBubble On BEST ANSWER

Your problem is here:

$file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
$ext = pathinfo($file, PATHINFO_EXTENSION);

fopen returns a file handle for use reading and writing a file, but pathinfo is expecting a string containing a filename (optionally, with a path), but you're giving it a file handle.

You should, in any case, be looking at $_FILES['upload_csv']['name'], which is the original name of the file, and extracting the file extension from that.

0
Alberto Alibaba On
 $extension=strtolower(pathinfo($_FILES['upload_csv']['tmp_name'], PATHINFO_EXTENSION));
 if($ext != "csv")
 {
   $errors[] = "Sorry, but only CSV files are supported";
 }
1
Saurabh Chandra Patel On
$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"
0
Ben Wong On

You can simply read the extension from the name of the file. There is no need to fopen the file.

$allowedTypes = 'csv, xls, xlsx';

function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
}

$filename = stripslashes($_FILES[$fileElementName]['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);

$allowedTypes = explode(',',ltrim(rtrim($allowedTypes,','),','));
array_walk($allowedTypes, create_function('&$val', '$val =    ltrim(trim($val),".");')); 

if (!in_array($extension, $allowedTypes))   
{
    $errors[] = "Sorry, but only CSV files are supported";
}