PHP: Crop file/directory path - php

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

Related

Laravel - Create custom name while uploading image using storage

I am trying to upload a file using laravel Storage i.e
$request->file('input_field_name')->store('directory_name'); but it is saving the file in specified directory with random string name.
Now I want to save the uploaded file with custom name i.e current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.
Use storeAs() instead:
$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
You can use below code :
Use File Facade
use Illuminate\Http\File;
Make Following Changes in Your Code
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
For more detail : Laravel Filesystem And storeAs as mention by #Alexey Mezenin
Hope this code will help :)
You also can try like this
$ImgValue = $request->service_photo;
$getFileExt = $ImgValue->getClientOriginalExtension();
$uploadedFile = time()'.'.$getFileExt;
$uploadDir = public_path('UPLOAS_PATH');
$ImgValue->move($uploadDir, $uploadedFile);
Thanks,
Try with following work :
$image = time() .'_'. $request->file('image')->getClientOriginalName();
$path = base_path() . '/public/uploads/';
$request->file('image')->move($path, $image);
You can also try this one.
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
public function getNewFileName($filename, $extension, $path)
{
$i = 1;
$new_filename = $filename . '.' . $extension;
while (File::exists($path . $new_filename))
$new_filename = $filename . '_' . $i++ . '.' . $extension;
return $new_filename;
}

exploding string to remove path

My script is returning the following path.
/home/vol14_2/project.com/b22_16126933/test.project.com/htdocs/php/api.php
I want to remove the rest and end up with the file name.
I know I have to explode the string, I just don't really know how to go about it.
use basename
echo basename("/home/vol14_2/project.com/b22_16126933/test.project.com/htdocs/php/api.php");
//api.php
OR pathinfo
$path_parts = pathinfo('/home/vol14_2/project.com/b22_16126933/test.project.com/htdocs/php/api.php');
echo $path_parts['basename']; // since PHP 5.2.0
//api.php
<?php
$path = "/home/vol14_2/project.com/b22_16126933/test.project.com/htdocs/php/api.php";
$file = basename($path); // $file is set to "api.php"
$file = basename($path, ".php"); // $file is set to "api"
?>

PHP RegEx extract filename

I need your help with a RegEx in PHP
I have something like:
vacation.jpg and I am looking for a RegEx which extracts me only the 'vacation' of the filename.
Can someone help me?
Don't use a regex for this - use basename:
$fileName = basename($fullname, ".jpg");
You can use pathinfo instead of Regex.
$file = 'vacation.jpg';
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo $filename;
And if you really need regex, this one will do it:
$success = preg_match('~([\w\d-_]+)\.[\w\d]{1,4}~i', $original_string, $matches);
Inside matches you will have first part of file name.
Better answers have already been provided, but here's another alternative!
$fileName = "myfile.jpg";
$name = str_replace(substr($fileName, strpos($fileName,".")), "", $fileName);
You don't need regex for this.
Approach 1:
$str = 'vacation.jpg';
$parts = explode('.', basename($str));
if (count($parts) > 1) array_pop($parts);
$filename = implode('.', $parts);
Approach 2 (better, use pathinfo()):
$str = 'vacation.jpg';
$filename = pathinfo($str, PATHINFO_FILENAME);

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

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