exploding string to remove path - php

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"
?>

Related

How to get filename without folder and filetype

I need to process all xml-files of a folder:
foreach(glob("folder/*.xml") as $file) {
$reader = new XMLReader;
$reader->open($file);
// need to know the filename
}
While processing the files, I need to know the filename. i.e. if file = "folder/file.xml" I want to get "file". How do I do that? Do I need to use RegEx?
You can try the basename() function
echo basename($file, ".xml")
http://php.net/manual/en/function.basename.php
Use basename
basename($file_name, ".xml");
This will remove the extension from your file and get only base name.
You can use pathinfo for this
echo pathinfo($file, PATHINFO_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);

Uploading images from a url naming dilemma

Let's say I have an image URL
http://website.com/content/image.png
I want to grab that image and place it in my own server, but I want to rename it beforehand so I can store the location in the database.
I am using the following code:
$url = 'http://website.com/content/image.png';
/* Extract the filename */
$filename = substr($url, strrpos($url, '/') + 1);
/* Save file wherever you want */
file_put_contents('upload/'.$filename, file_get_contents($url));
If I want to rename the file to something entirely new, but keep the extension in tact, how can I accomplish that? Also will this work if there is more content in the url?
For example instead of:
url here/content/image.png
It would be:
url here/content/stuff/images/image.png
I am basically trying to write a universal function that will take a URL to an image, upload it to my server, and rename that image to what I want while keeping the extension in tact.
First- You need to check if your webserver can access URL's from another server.
Second- Assuming you can:
$url = 'http://website.com/content/image.png';
$extension = end(explode(".", $url));
$filename = "the_filename_you_want.".$extension;
file_put_contents('upload/'.$filename, file_get_contents($url));
<?php
$url = 'http://www.bla.org/img/derp.jpg';
$extension = end(explode('.', $url));
file_put_contents('/tmp/image.'.$extension, file_get_contents($url));
$filename = substr($url, strrpos($url, '.'));
You need pathinfo:
$url = 'http://website.com/content/image.png';
$path = parse_url($url, PHP_URL_PATH);
/* Extract the filename and extension */
$filename = pathinfo($path, PATHINFO_FILENAME);
$extension = pathinfo($path, PATHINFO_EXTENSION);
/* Save file wherever you want */
file_put_contents('upload/' . $filename . '.' . $extension, file_get_contents($url));
You might want to look at parse_url() function to get at the various URL components.
Like:
$url_parts = parse_url($url);
$uri = $url_parts['path'];
Then use pathinfo() to break up the components of the URI into path, filename, extension, etc.
$uri_info = pathinfo($uri);
$dir_name = $uri_info['dirname'];
$file_name = $uri_info['filename'];
$file_basename = $uri_info['basename'];
$file_extension = $uri_info['extension'];

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

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