PHP strip unknown file extension - php

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'];

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

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.

PHP: Crop file/directory path

I have a long path like this - /home/user/www/domain.net/public_html/system/dir/file.php, and I want crop this to get something like - /system/dir/file.php.
Now I am using this code:
$filename = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $filename);
$filename = join(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $filename), -3, 3));
And it works, but I think there is a better solution.. Anyone know?
Thanks in advance.
You can use regex instead. See this sample:
$sFileName = '/home/user/www/domain.net/public_html/system/dir/file.php';
$iCropCount = 3;
$sResult = preg_replace('#.*?((\/[^\/]+){'.$iCropCount.'})$#', '$1', $sFileName));
//var_dump($sResult);
Operations with DIRECTORY_SEPARATOR are omitted (since main sense of sample above are not in them)
I think you only need the web directory. So you can explode with /public_html as it is always going to be there.
E.g :
$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
$path = explode('/public_html', $filename);
echo $path[1];
I found other solution:
$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
explode($_SERVER['DOCUMENT_ROOT'], $filename);
$filename = end($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));

How can I change a file's extension using PHP?

How can I change a file's extension using PHP?
Ex: photo.jpg to photo.exe
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
my.file.name.jpg
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
substr_replace($file , 'png', strrpos($file , '.') +1)
Will change any extension to what you want. Replace png with what ever your desired extension would be.
Replace extension, keep path information
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '')
. $info['filename']
. '.'
. $new_extension;
}
You may use the rename(string $from, string $to, ?resource $context = null) function.
Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:
function replace_extension($filename, $new_extension) {
return preg_replace('/\..+$/', '.' . $new_extension, $filename);
}
Then use the rename() function to rename the file with the new filename.
Just replace it with regexp:
$filename = preg_replace('"\.bmp$"', '.jpg', $filename);
You can also extend this code to remove other image extensions, not just bmp:
$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
For regex fans,
modified version of Thanh Trung's 'preg_replace' solution that will always contain the new extension (so that if you write a file conversion program, you won't accidentally overwrite the source file with the result) would be:
preg_replace('/\.[^.]+$/', '.', $file) . $extension
Better way:
substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension
Changes made only on extension part. Leaves other info unchanged.
It's safe.
You could use basename():
$oldname = 'path/photo.jpg';
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe';
Or for all extensions:
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';
Finally use rename():
rename($oldname, $newname);
Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:
answer by Tony Maro (pathinfo) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.
answer by Matt (substr_replace) took 0.000010013580322266 seconds.
answer by Jeremy Ruten (preg_replace) took 0.00070095062255859 seconds.
Therefore, I would suggest substr_replace, since it's simpler and faster than others.
Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn't beat substr_replace:
$parts = explode('.', $inpath);
$parts[count( $parts ) - 1] = 'exe';
$outpath = implode('.', $parts);
I like the strrpos() approach because it is very fast and straightforward — however, you must first check to ensure that the filename has any extension at all. Here's a function that is extremely performant and will replace an existing extension or add a new one if none exists:
function replace_extension($filename, $extension) {
if (($pos = strrpos($filename , '.')) !== false) {
$filename = substr($filename, 0, $pos);
}
return $filename . '.' . $extension;
}
I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:
// Converts image file extensions to all lowercase
$currentdir = opendir($gallerydir);
while(false !== ($file = readdir($currentdir))) {
if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {
$srcfile = "$gallerydir/$file";
$filearray = explode(".",$file);
$count = count($filearray);
$pos = $count - 1;
$filearray[$pos] = strtolower($filearray[$pos]);
$file = implode(".",$filearray);
$dstfile = "$gallerydir/$file";
rename($srcfile,$dstfile);
}
}
This worked for my purposes.

Categories