PHP Getting file extension returning .file - php

When i use this function to get the file extension:
function getExtension($file){
$fileName = $_FILES[$file]['name'];
$extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
return $extension;
It just returns .file even though the file i submitted in the form was .pdf
Any suggestion to solve this?

This piece of code will return the uploaded file extension.
function getExtension($file)
{
$fileName = $_FILES[$file]['name'];
$fileArr = explode(".", $fileName);
return end($fileArr);
}

Related

Extension in php file

I created a page that can upload file to my database, but when a filename has (.), it doesnt save properly. For example I upload a file named imagefile.50.jpg, it just saves as image20.50
<?php
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = $extension[0] . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
To get the filename and extension of a file, you can use pathinfo, i.e.:
$file = "some_dir/somefile.test.php"; # $_FILES['user_image']['name']
$path_parts = pathinfo($file);
$fn = $path_parts['filename'];
$ext = $path_parts['extension'];
print $fn."\n";
print $ext;
Output:
somefile.test
php

Get an image extension from an uploaded file in Laravel

I have been trying to get the extension from an uploaded file, searching on google, I got no results.
The file already exists in a path:
\Storage::get('/uploads/categories/featured_image.jpg);
Now, How can I get the extension of this file above?
Using input fields I can get the extension like this:
Input::file('thumb')->getClientOriginalExtension();
Thanks.
Tested in laravel 5.5
$extension = $request->file('file')->extension();
The Laravel way
Try this:
$foo = \File::extension($filename);
Yet another way to do it:
//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();
You can use the pathinfo() function built into PHP for that:
$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];
Or more concisely, you can pass an option get get it directly;
$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);
If you just want the extension, you can use pathinfo:
$ext = pathinfo($file_path, PATHINFO_EXTENSION);
//working code from laravel 5.2
public function store(Request $request)
{
$file = $request->file('file');
if($file)
{
$extension = $file->clientExtension();
}
echo $extension;
}
return $picName = time().'.'.$request->file->extension();
The time() function will make the image unique then the .$request->file->extension() gets the image extension for you.
You can use this it works well with Laravel 6 and above.
Do something like this:
if($request->hasFile('video')){
$video=$request->file('video');
$filename=str_random(20).".".$video->extension();
$path = Storage::putFileAs(
'/', $video, $filename
);
$data['video']=$filename;
}
Or can use the Extension Splitter Trickster::getExtention() function of https://github.com/secrethash/trickster
Trickster::getExtention('some-funny.image.jpg');
It returns jpg

PHP move_uploaded_file dynamic file name - files have no extension

I want to upload some GPX (XML technically) files to the server and rename them with dynamic file names (such as 0.gpx, 1.gpx ... ). I can not figure out how to do this with the move_uploaded_file function as it only creates the files extensionless. I get a 'name' file instead of a 'name.gpx' file.
Shouldn't it use the PATHINFO_EXTENSION of the uploadef file automatically to create the file with the right extension?
I have tried to call the function like this:
$filename = 0;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$filename++;
Even if I try to create a string with the extension it does not work:
$tmp = 0;
$ext = pathinfo($name, PATHINFO_EXTENSION);
$filename = $tmp + "." + $ext;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Help please?
File name should have the extension. This works fine for me to find the extension:
$temp = explode(".", $_FILES["uploadfiles"]["name"]);
$extension = end($temp);
echo $extension; // Display the extension
$tmp = 0;
$filename = $tmp.".".$extension;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Hope this helps.
I don't think temporary files have an extension.
You could manually add "gpx" to the name :
$tmp = 0;
$filename = $tmp . ".gpx";
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Or maybe check the mimetype and craft the appropriate extension out of it.
Or take the extension in $_FILES['uploadfiled']['name'], match it in a whitelist, and append it to your final filename.

How to check for the correct file extension in PHP?

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?
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.
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
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";
}
$extension=strtolower(pathinfo($_FILES['upload_csv']['tmp_name'], PATHINFO_EXTENSION));
if($ext != "csv")
{
$errors[] = "Sorry, but only CSV files are supported";
}

Why this php file upload validation script not working?

Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.

Categories