Get an image extension from an uploaded file in Laravel - php

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

Related

PHP Getting file extension returning .file

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);
}

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.

Check file extension with PHP

I was wondering how to make PHP to check what extension it have, and then execute a code. For example, lets see it's a .mp3 file then it would execute: echo 'This is a mp3 file.'; Of course not with that code of course - but more advanced.
Anyhow, got any ideas etc?
Use the pathinfo() function to isolate the extension of the file and then use that value in an if statement.
There are multiple ways to do this. If all you are doing is checking for mp3, just explode on the period, pop the last one and then see if the string equal.
for example:
$name = "song.mp3";
$parts = explode('.', $name);
$extension = array_pop($parts);
if( $extension == 'mp3'){
echo 'This is a mp3 file.';
}
If you are checking for a wide variety of extensions and they are uploaded use
$_FILES['file']['type'];
Check this two options to do it:
$filename = 'music.mp3'
$ext = substr(strrchr($filename, '.'), 1);
or
$filename = 'music.mp3';
$ext = pathinfo($filename, PATHINFO_EXTENSION);
Hope it helps :)
You can use filetype() or $_FILES[$file][type] to get the file type
.
try this
$file_name = "test.txt";
$extension = pathinfo($file_name);
echo "Your file extension is ".$extension ['extension'];
If you want to properly detect a file's type, use Fileinfo.
Example ripped for PHP's comments:
<?php
$fi = new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));

better way to see if file has certain extention

I'm doing this right now in my code to see if a file name has the extension .txt, but I think it basically checks if it contains .txt and not necessarily ends with .txt. Does php have a better way to do extension checking instead of using strpos?
strpos($filename,'.txt') !== false
You can use the pathinfo() function to get the extension of the file:
$info = pathinfo($pathToFile);
$ext = $info['extension'];
and then check if the extension is one of the allowed:
$validExtensions = array("txt", "doc");
if (in_array($ext, $validExtensions) {
//more code
}
Use the following code, it couldn't get any better:
$ext = pathinfo('test.txt', PATHINFO_EXTENSION);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
strpos is okay, you have to just keep in mind that you need not first but last dot.
and use strrpos(), note the double "r".
You can allow multiple extensions by adding to the array.
$allowed = array('txt');
if (in_array(pathinfo($filename, PATHINFO_EXTENSION), $allowed)){
// Has the correct file extension
}
or a simpler version which allows only txt extensions could be:
if (pathinfo($filename, PATHINFO_EXTENSION) == 'txt'){
// Has the correct file extension
}

PHP strip unknown file extension

I understand that using PHP's basename() function you can strip a known file extension from a path like so,
basename('path/to/file.php','.php')
but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?
Thanks in advance!
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.
$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);
The value of $filename will be file.
You can extract the extension using pathinfo and cut it off.
// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");
Note the . before $ext
$filename = preg_replace('#\.([^\.]+)$#', '', $filename);
You can try with this:
$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));
Try this:-
$path = 'path/to/file.php';
$pathParts = pathinfo( $path );
$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];

Categories