Check file extension with PHP - 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));

Related

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

How to dynamically determine unknown file extension from file in web folder [duplicate]

I want get uploaded image extension.
As I know, best way is getimagesize() function.
but this function's mime, returns image/jpeg when image has .jpg or also .JPEG extension.
How can get exactly extension?
$ext = pathinfo($filename, PATHINFO_EXTENSION);
you can use image_type_to_extension function with image type returned by getimagesize:
$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);
You can also use strrpos and substr functions to get extension of any file
$filePath="images/ajax-loader.gif";
$type=substr($filePath,strrpos($filePath,'.')+1);
echo "file type=".$type;
output: gif
if you want extension like .gif
$type=substr($filePath,strrpos($filePath,'.')+0);
output: .gif
$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);
One more way to do it:
$ext = strrchr($filename, "."); // .jpg
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);
You can also explode the file name with dots and take the end of the array as follows:
$ext = end(explode('.', 'image.name.gif'));
According to: Two different ways to find file extension in PHP
And a new way for you lol:
$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];
For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetype function. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

Get image extension

I want get uploaded image extension.
As I know, best way is getimagesize() function.
but this function's mime, returns image/jpeg when image has .jpg or also .JPEG extension.
How can get exactly extension?
$ext = pathinfo($filename, PATHINFO_EXTENSION);
you can use image_type_to_extension function with image type returned by getimagesize:
$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);
You can also use strrpos and substr functions to get extension of any file
$filePath="images/ajax-loader.gif";
$type=substr($filePath,strrpos($filePath,'.')+1);
echo "file type=".$type;
output: gif
if you want extension like .gif
$type=substr($filePath,strrpos($filePath,'.')+0);
output: .gif
$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);
One more way to do it:
$ext = strrchr($filename, "."); // .jpg
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);
You can also explode the file name with dots and take the end of the array as follows:
$ext = end(explode('.', 'image.name.gif'));
According to: Two different ways to find file extension in PHP
And a new way for you lol:
$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];
For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetype function. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

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