PHP strrchr find the next to the last not the last ocurrence - php

I was using the strrchr PHP function with substr and strrpos to find the file name in a string with the full path like:
/images/onepiece.jpg returns
onepiece.jpg
but now I need to a function to find not the last "/" but the one next to the last:
/images/anime/onepiece.jpg returning anime/onepiece.jpg or /anime/onepiece.jpg
And as strrchr - 1 doesn't work, hehehe :), how can I achieve that?
[SOLVED]
Using PHP pathinfo() as #middaparka and #Shakti Singh said, I've change the way I get the image string from the MySQL database. Now it can have subfolders, as was my initial intention.
<?php
/*
* pathinfo() parameters:
* PATHINFO_DIRNAME = 1
* PATHINFO_BASENAME = 2
* PATHINFO_EXTENSION = 4
* PATHINFO_FILENAME = 8
* */
$slash = '/';
$mainpath = 'store/image/';
$thumbspath = 'cache/';
$path = $imgsrow->photo; //gets the string containing the partial path and the name of the file from the database
$dirname = pathinfo($path, 1); //gets the partial directory string
$basename = pathinfo($path, 2); //gets the name of the file with the extension
$extension = pathinfo($path, 4); //gets the extension of the file
$filename = pathinfo($path, 8); //gets the name of the file
$dims = '-100x100.'; //string of size of the file to append to the file name
$image = $mainpath . $path; //mainpath + path is the full string for the original/full size file
$thumbs = $mainpath . $thumbspath . $dirname . $slash . $filename . $dims . $extension; //string to point to the thumb image generated from the full size file
?>
<img src="<?= $thumbs; ?>" width="100" height="100" alt="<?= $row->description; ?>" />
<br />
<img src="<?= $image; ?>" width="500" height="500" alt="<?= $row->description; ?>" />

To be honest, it would be a lot easier to use the pathinfo or dirname functions to decompose directory paths.
For example:
$filename = pathinfo('/images/onepiece.jpg', PATHINFO_BASENAME);
$directory = dirname('/images/onepiece.jpg');
You may have to use a mix of these to obtain what you're after but they will at least be OS "safe" (i.e.: will handle both Linux/Linux and Windows path styles).
In terms of the specific problem you have, you should be able to use the following cross-platform solution to get what you need:
<?php
$sourcePath = '/images/anime/onepiece.jpg';
$filename = pathinfo($sourcePath, PATHINFO_BASENAME);
$directories = explode(DIRECTORY_SEPARATOR, pathinfo($sourcePath, PATHINFO_DIRNAME));
echo $directories[count($directories) -1] . DIRECTORY_SEPARATOR . $filename;
?>

I would suggest to use explode to split the path into its segments:
$segments = explode('/', $path);
Then you can use $segments[count($segments)-1] to get the last path segment.
And for for last two segments you can use array_slice with implode to put them back together:
$lastTwoSegments = implode('/', array_slice($segments, -2));

you need to use pathinfo function
pathinfo ($path, PATHINFO_FILENAME );

Dude, just make a temp string to hold the string you want to find. Find the last occurrence, replace it with something, like x, and then find the new last occurrence, which is the second to last occurrence.

Related

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

Getting the actual document root in PHP?

I'm not sure exactly where this script will be running, so it must be able to access this directory from anywhere.
I'm trying to create a list of images by getting the image file names from a directory, filtering them until I only have the image formats I want, then displaying them using an <img> tag.
The first bit went really well. Outputting the HTML is proving to be a problem.
While I can use $_SERVER["DOCUMENT_ROOT"] to work with the directories in PHP, it's problematic to output that value as part of the path in thetag'ssrc` attribute.
Here is my current code:
$unkwown_files = scandir($_SERVER['DOCUMENT_ROOT'] . "/path/images");
foreach($unkwown_files as $file) {
$exploded_filename = explode(".", $file);
$file_type = array_pop($exploded_filename);
$accepted_filetypes = [
"png",
"jpg",
"gif",
"jpeg"
];
$picture_names = [];
if (in_array($file_type, $accepted_filetypes)) {
$picture_names[] = $file;
}
}
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
A slightly different approach for you that filters files by extension from the outset.
$dir = $_SERVER['DOCUMENT_ROOT'] . "/path/images/";
/*
glob() searches for files/paths that match the pattern in braces and returns the results
as an array.
The '*' is a wildcard character as you would expect.
The flag 'GLOB_BRACE' expands the string so that it tries to match each
( From the manual: GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' )
*/
$col = glob( $dir . "*.{jpg,png,gif,jpeg}", GLOB_BRACE );
/*
Iterate through the results, with each one being the filepath to the file found.
As the glob() function searched for the required types we don't need to check
if they are in the allowed types array.
Because you do not wish to display the fullpath to the image, a relative path is
preferred - thus we remove, from the path, the document root.
*/
foreach( $col as $index => $file ){
$path_to_image = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $file );
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Try this out
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images/" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}

How do I get a File Extension in PHP if I only have the File Name?

I have the path to an image file /files/uploads/1 but as you can see, I don't have an extension so I can't display the image. How can I get the extension of the file so I can display it? Thanks!
EDIT: Here is come code I have tried. BMP, PNG, JPG, JPEG and GIF are the only possible extensions, but $path ends up never getting assigned a value.
$exts = array('bmp','png','jpg','jpeg','gif');
foreach ($exts as $ext) {
if (file_exists("/files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
Personally, I had a problem where I had an unnecessary slash (/) before my path in the file_exists check, but the solution to the question is still the same.
$exts = array('bmp','png','jpg','jpeg','gif','swf','psd','tiff','jpc','jp2','jpx','jb2','swc','iff','wbmp','xbm','ico');
foreach ($exts as $ext) {
if (file_exists("files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
You don't need a file extension to show an image.
<img src="/files/uploads/1">
Will show the image. It's the same way the placehold.it images work
<img src="http://placehold.it/350x150">
First of all , I think when you get the file name for the image that means no need to add extension , so you have the file name and image folder
it should simply look like this :
$fullpath = ('uploadword/'.$filename);
// then call it
<img src='".$fullpath."'>
The normal scenario to upload all the images in specific folder then get the filename and save it in data base
move_uploaded_file($file_tmp,"upload/".$filename);
Some professional make it more sophisticated to make filename unique ,because they expected some duplicated values and many reasons , here is one simple technique :
$anynameorfunction = "";// random number etc...
$newname = $anynameorfunction.$filename;
move_uploaded_file($file_tmp,"upload/".$newname);
So, when they call it again it should be simple like this
$fullpath = ('uploadword/'.$newname);
// then call it
<img src='".$newname."'>
This is in very simple way and i wish you get what i mean

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

Categories