PHP Data-URI to file - php

I have a data URI I am getting from javascript and trying to save via php. I use the following code which gives a apparently corrupt image file:
$data = $_POST['logoImage'];
$uri = substr($data,strpos($data,",")+1);
file_put_contents($_POST['logoFilename'], base64_decode($uri));
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs 9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAxklEQVQYlYWQMW7CUBBE33yITYUUmwbOkBtEcgUlTa7COXIVV5RUkXKC5AxU EdyZVD4kyKxkwIrr9vd0c7Oih aopinLNsF6Qkg2XW4XJ7LGFsAAcTV6lF5/jLdbALA9XDAXYfthFQVx OrmqKYK88/7rbbMFksALieTnzu9wDYTj6f70PKsp2kwAiSvjXNcvkWpAfNZkzWa/5a9yT7fdoX7rrB7hYh2fXo9HdjPYQZu3MIU8bYIlW20y0RUlXG2Kpv/vfwLxhTaSQwWqwhAAAAAElFTkSuQmCC
Below the code is the actual image as a Data-URI. 'logoImage' is the string above, and $uri is the string minus 'image/jpeg;base64,'.

A quick look at the PHP manual yields the following:
If you want to save data that is derived from a Javascript
canvas.toDataURL() function, you have to convert blanks into plusses.
If you do not do that, the decoded data is corrupted:
$encodedData = str_replace(' ','+',$encodedData);
$decodedData = base64_decode($encodedData);

The data URI you have in your example is not a valid PNG image. This will never work and is unrelated to the code, it's related to the data.
Does not apply but might be of interest:
file_put_contents($_POST['logoFilename'], file_get_contents($data));
The idea behind: PHP itself can read the contents of data URIs (data://) so you don't need to decode it on your own.
Note that the official data URI scheme (ref: The "data" URL scheme RFC 2397) does not include a double slash ("//") after the colon (":"). PHP supports with or without the two slashes.
# RFC 2397 conform
$binary = file_get_contents($uri);
# with two slashes
$uriPhp = 'data://' . substr($uri, 5);
$binary = file_get_contents($uriPhp);

The all code that works :
$imgData = str_replace(' ','+',$_POST['image']);
$imgData = substr($imgData,strpos($imgData,",")+1);
$imgData = base64_decode($imgData);
// Path where the image is going to be saved
$filePath = $_SERVER['DOCUMENT_ROOT']. '/ima/temp2.png';
// Write $imgData into the image file
$file = fopen($filePath, 'w');
fwrite($file, $imgData);
fclose($file);

I have another way to do this with PHP.
$img = str_replace(' ','+',$img);
$i = explode(',', $img);
$imgData = array_pop($i);
$newName = 'digital_file/'. rand(10, 16) . '.' . str_replace('/', '.', mime_content_type($img) );
// data:image/png;base64
$imgData = base64_decode($imgData);
Now you can use file_put_contents($newName) to create the image file.
Produces a file with a random numerical name (e.g. "123123.image.png"). And of course it has correct mime type.

Related

get php file execution result

i'm new in php. and using php on xampp and also in real server. i have a php file that receives on image as String and saves it as image that im gonna use this file with a library in android that uploads image to php file.
the string is sent to php file but no file is saved as image. my problem is that i cant figure out how to get result of executing this php file. i cant get response with my upload library , if i could get echo from this file for test purpose, so i could test it or if i could get error log of execution of file in xampp. but i have no clue how to test php file that is not containing view so i cant echo any thing.
this is my php file code:
<?php
if($_POST){
$data = $_POST['imgBase64'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = ''.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = 'localhost/serverp/server.parhamcode.ir/'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
}
?>
try this:
<?php
file_put_contents('./debug.log', $_POST, FILE_APPEND);
then you'll get a debug.log file under the same folder as your PHP script.
you can change $_POST to any variable you want to check.
If you want to echo something in this log file :
file_put_contents('./debug.log', "any string is ok.", FILE_APPEND);

base64 image file get corrupt while uploading to php server

Similar question has been asked previously but it didn't solve my problem so i am asking here again. Actually i am uploading base64 image file to php server and i have to save it there. I tried every suggested help but nothing works for me. my code
// here is my base64 code for image
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgFBgcGBQgHBgcJCAgJDBMMDAsLDBgREg4THBgdHRsYGxofIywlHyEqIRobJjQnKi4vMTIxHiU2OjYwOi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5NM1Pw5e399aXD/8sfvfL1Ndq3iTQ0/5iVt/wFwaafFegJ/zEoP++qieGp1E4zkEMZUhJSpxS+Rl6FY3Fhfeb5TOm3b92ukluP8ARJXdGTap+9WYfGGgf8/8VUtU8YaK9jOkN0ruylaqjSp0IckHojnq1KlefPNanlE0+/Vrt03fNIa7f4Qult/aG9tm6SuEEtuk8j71+8dtbfgvU7Kw897m4VNzfxVlBNSufR47Exq4VUlbp+Be+Jc0M+vgq/3UAorn/Ft7FeamZLeTcmKK5alKUpuSZx0asIU1Fo8rWVqmGf71FFeoeWNYVTuYRMnzmiihCZWi1HUdLlC2OoXNvj/nlKy/yNdHZfE7xNDbNBeXUd/Ax2FZ4xux7MMH880UV0JJxucrbUrI9Y+GXjT/AIS2F4X08WrWyqhYTFt2B1xgY/Ou3C4h8xcD2IoorFrU06Gv4c+5P/vD+tbHIOQcZ5IoorSOxm9xQoYE+nauP8f+NE8G2Ul0NMW8Zc8ed5ecf8BNFFBKPI7/APaJ12Z8aXo2nWif9Ni8x/QqP0rCv/i7431Byv8Aa62qn+G2gRP1wT+tFFTM1gkZ0viDX75tt7rl/Kf+upH6CnQqZP8AXSyy/wC+5NFFYSOqCRa/1f3adiiis0bMh3fX86kFw69DRRVszuPzR/yzoooARQcfeNFFFID/2Q==
$src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2OTApLCBxdW... ";
// above the example of image base64 file
// and server side code in php, i have posted base64 to php
$img_part = explode(";base64,",$_POST['base64']);
$img_type_aux = explode("image/",$img_part[0]);
$ext = $img_type_aux[1];
$image_base64 = base64_decode($img_part[1]);
// i have tried all possible code like here $name = random_value+$ext
file_put_contents($name,$image_base64); // didn't work then i used str_replace
$image_base64 = str_replace(' ','+',$image_base64);
file_put_contents($name,$image_base64); // i also didn't work
$fp = fopen($name,"wb");
fwrite($fp,$image_base64); // i also didn;t work
fclose($fp);
please someone help me,
Use this function This will work.
function convertBase64toimage($image_string){
$name='test_with_new_image.jpeg';
$folderPath=$_SERVER['DOCUMENT_ROOT'] . "/test/";
$img_part = explode(";base64,",$image_string);
$img_type_aux = explode("image/",$img_part[0]);
$ext = $img_type_aux[1];
$image_base64 = base64_decode($img_part[1]);
$file = $folderPath .$name;
file_put_contents($file,$image_base64);
}
$string='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgFBgcGBQgHBgcJCAgJDBMMDAsLDBgREg4THBgdHRsYGxofIywlHyEqIRobJjQnKi4vMTIxHiU2OjYwOiwwMTD/2wBDAQgJCQwKDBcMDBcwIBsgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDD/wAARCAC1ALUDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDwOJN77fWrf9my+Q0rMu1a7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1rJ1HSfibbwbtN8SSy/wB5biK1z+BCmqGmQ/E+5u1+2a4qRLw0awRLn8QgNN3QJX7HVnS/GV/u+36/FZRH+G1iwR9W4Oaz7jRfDdlx4g8TT3zfxLcXzNn/AICpzTrf4d3F58/iPXL6+/vRtI2P1bH6Vu6f4G8PWH+p02L/AHpMv/Ouf2c5dPvdz0niKMNpv/t2Kj+O/wCBz9trPgqx+XStK+1v/ehtc/8AjxFWH8W6hN8um+G5U/2pGC/oK7GLT7KH7lvEn/AabNc6bbf664tov951FUqUl1t6GEsVRbvyNv8AvNv8rHA3U3i6/wD+WVtbpu/h5NM1Pw5e399aXD/8sfvfL1Ndq3iTQ0/5iVt/wFwaafFegJ/zEoP++qieGp1E4zkEMZUhJSpxS+Rl6FY3Fhfeb5TOm3b92ukluP8ARJXdGTap+9WYfGGgf8/8VUtU8YaK9jOkN0ruylaqjSp0IckHojnq1KlefPNanlE0+/Vrt03fNIa7f4Qult/aG9tm6SuEEtuk8j71+8dtbfgvU7Kw897m4VNzfxVlBNSufR47Exq4VUlbp+Be+Jc0M+vgq/3UAorn/Ft7FeamZLeTcmKK5alKUpuSZx0asIU1Fo8rWVqmGf71FFeoeWNYVTuYRMnzmiihCZWi1HUdLlC2OoXNvj/nlKy/yNdHZfE7xNDbNBeXUd/Ax2FZ4xux7MMH880UV0JJxucrbUrI9Y+GXjT/AIS2F4X08WrWyqhYTFt2B1xgY/Ou3C4h8xcD2IoorFrU06Gv4c+5P/vD+tbHIOQcZ5IoorSOxm9xQoYE+nauP8f+NE8G2Ul0NMW8Zc8ed5ecf8BNFFBKPI7/APaJ12Z8aXo2nWif9Ni8x/QqP0rCv/i7431Byv8Aa62qn+G2gRP1wT+tFFTM1gkZ0viDX75tt7rl/Kf+upH6CnQqZP8AXSyy/wC+5NFFYSOqCRa/1f3adiiis0bMh3fX86kFw69DRRVszuPzR/yzoooARQcfeNFFFID/2Q==';
$a=convertBase64toimage($string);
And output of the code

Get only filename from url in php without any variable values which exist in the url

I want to get filename without any $_GET variable values from a URL in php?
My URL is http://learner.com/learningphp.php?lid=1348
I only want to retrieve the learningphp.php from the URL?
How to do this?
I used basename() function but it gives all the variable values also: learntolearn.php?lid=1348 which are in the URL.
This should work:
echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
But beware of any malicious parts in your URL.
Following steps shows total information about how to get file, file with extension, file without extension. This technique is very helpful for me. Hope it will be helpful to you too.
$url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
$file = file_get_contents($url); // to get file
$name = basename($url); // to get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // to get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); //file name without extension
Is better to use parse_url to retrieve only the path, and then getting only the filename with the basename. This way we also avoid query parameters.
<?php
// url to inspect
$url = 'http://www.example.com/image.jpg?q=6574&t=987';
// parsed path
$path = parse_url($url, PHP_URL_PATH);
// extracted basename
echo basename($path);
?>
Is somewhat similar to Sultan answer excepting that I'm using component parse_url parameter, to obtain only the path.
Use parse_url() as Pekka said:
<?php
$url = 'http://www.example.com/search.php?arg1=arg2';
$parts = parse_url($url);
$str = $parts['scheme'].'://'.$parts['host'].$parts['path'];
echo $str;
?>
http://codepad.org/NBBf4yTB
In this example the optional username and password aren't output!
Your URL:
$url = 'http://learner.com/learningphp.php?lid=1348';
$file_name = basename(parse_url($url, PHP_URL_PATH));
echo $file_name;
output: learningphp.php
You can use,
$directoryURI =basename($_SERVER['SCRIPT_NAME']);
echo $directoryURI;
An other way to get only the filename without querystring is by using parse_url and basename functions :
$parts = parse_url("http://example.com/foo/bar/baz/file.php?a=b&c=d");
$filename = basename($parts["path"]); // this will return 'file.php'
Try the following code:
For PHP 5.4.0 and above:
$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);
For PHP Version < 5.4.0
$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);
$filename = pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_FILENAME );
Use parse_url to extract the path from the URL, then pathinfo returns the filename from the path
The answer there assumes you know that the URL is coming from a request, which it may very well not be. The generalized answer would be something like:
$basenameWithoutParameters = explode('?', pathinfo($yourURL, PATHINFO_BASENAME))[0];
Here it just takes the base path, and splits out and ignores anything ? and after.
$url = "learner.com/learningphp.php?lid=1348";
$l = parse_url($url);
print_r(stristr($l['path'], "/"));
Use this function:
function getScriptName()
{
$filename = baseName($_SERVER['REQUEST_URI']);
$ipos = strpos($filename, "?");
if ( !($ipos === false) ) $filename = substr($filename, 0, $ipos);
return $filename;
}
May be i am late
$e = explode("?",basename($_SERVER['REQUEST_URI']));
$filename = $e[0];

How do I use PHP to grab the name of the file?

what I want to do is PHP to look at the url and just grab the name of the file, without me needing to enter a path or anything (which would be dynamic anyway). E.G.
http://google.com/info/hello.php, I want to get the 'hello' bit.
Help?
Thanks.
You need basename and explode to get name without extension:
$name = basename($_SERVER['REQUEST_URI']);
$name_array = explode('.', $name);
echo $name_array[0];
$filename = __FILE__;
Now you can split this on the dot, for example
$filenameChunks = split(".", $filename);
$nameOfFileWithoutDotPHP = $filenameChunks[0];
This is safe way to easily grab the filename without extension
$info = pathinfo(__FILE__);
$filename = $info['filename'];
$_SERVER['REQUEST_URI'] contains the requested URI path and query. You can then use parse_url to get the path and basename to get just the file name:
basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php')
http://php.net/manual/en/function.basename.php
$file = basename(__FILE__); // hello.php
$file = explode('.',$file); // array
unset($file[count($file)-1]); // unset array key that has file extension
$file = implode('.',$file); // implode the pieces back together
echo $file; // hello
You could to this with parse_url combined with pathinfo
Here's an example
$parseResult = parse_url('http://google.com/info/hello.php');
$result = pathinfo($parseResult['path'], PATHINFO_FILENAME);
$result will contain "hello"
More info on the functions can be found here:
parse_url
pathinfo

How to remove extension from string (only real extension!)

I'm looking for a small function that allows me to remove the extension from a filename.
I've found many examples by googling, but they are bad, because they just remove part of the string with "." . They use dot for limiter and just cut string.
Look at these scripts,
$from = preg_replace('/\.[^.]+$/','',$from);
or
$from=substr($from, 0, (strlen ($from)) - (strlen (strrchr($filename,'.'))));
When we add the string like this:
This.is example of somestring
It will return only "This"...
The extension can have 3 or 4 characters, so we have to check if dot is on 4 or 5 position, and then remove it.
How can it be done?
http://php.net/manual/en/function.pathinfo.php
pathinfo — Returns information about a file path
$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'
Try this one:
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
So, this matches a dot followed by three or four characters which are not a dot or a space. The "3 or 4" rule should probably be relaxed, since there are plenty of file extensions which are shorter or longer.
From the manual, pathinfo:
<?php
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // Since PHP 5.2.0
?>
It doesn't have to be a complete path to operate properly. It will just as happily parse file.jpg as /path/to/my/file.jpg.
Use PHP basename()
(PHP 4, PHP 5)
var_dump(basename('test.php', '.php'));
Outputs: string(4) "test"
This is a rather easy solution and will work no matter how long the extension or how many dots or other characters are in the string.
$filename = "abc.def.jpg";
$newFileName = substr($filename, 0 , (strrpos($filename, ".")));
//$newFileName will now be abc.def
Basically this just looks for the last occurrence of . and then uses substring to retrieve all the characters up to that point.
It's similar to one of your googled examples but simpler, faster and easier than regular expressions and the other examples. Well imo anyway. Hope it helps someone.
Recommend use: pathinfo with PATHINFO_FILENAME
$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
You could use what PHP has built in to assist...
$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);
Though if you are only dealing with a filename (.somefile.jpg), you will get...
./somefile
See it on CodePad.org
Or use a regex...
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
See it on CodePad.org
If you don't have a path, but just a filename, this will work and be much terser...
$withoutExt = pathinfo($path, PATHINFO_FILENAME);
See it on CodePad.org
Of course, these both just look for the last period (.).
The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.
$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);
I found many examples on the Google but there are bad because just remove part of string with "."
Actually that is absolutely the correct thing to do. Go ahead and use that.
The file extension is everything after the last dot, and there is no requirement for a file extension to be any particular number of characters. Even talking only about Windows, it already comes with file extensions that don't fit 3-4 characters, such as eg. .manifest.
There are a few ways to do it, but i think one of the quicker ways is the following
// $filename has the file name you have under the picture
$temp = explode( '.', $filename );
$ext = array_pop( $temp );
$name = implode( '.', $temp );
Another solution is this. I havent tested it, but it looks like it should work for multiple periods in a filename
$name = substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));
Also:
$info = pathinfo( $filename );
$name = $info['filename'];
$ext = $info['extension'];
// Or in PHP 5.4, i believe this should work
$name = pathinfo( $filename )[ 'filename' ];
In all of these, $name contains the filename without the extension
$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);
Output:
this-is.file.name
As others mention, the idea of limiting extension to a certain number of characters is invalid. Going with the idea of array_pop, thinking of a delimited string as an array, this function has been useful to me...
function string_pop($string, $delimiter){
$a = explode($delimiter, $string);
array_pop($a);
return implode($delimiter, $a);
}
Usage:
$filename = "pic.of.my.house.jpeg";
$name = string_pop($filename, '.');
echo $name;
Outputs:
pic.of.my.house (note it leaves valid, non-extension "." characters alone)
In action:
http://sandbox.onlinephpfunctions.com/code/5d12a96ea548f696bd097e2986b22de7628314a0
This works when there is multiple parts to an extension and is both short and efficient:
function removeExt($path)
{
$basename = basename($path);
return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}
echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file
You can set the length of the regular expression pattern by using the {x,y} operator. {3,4} would match if the preceeding pattern occurs 3 or 4 times.
But I don't think you really need it. What will you do with a file named "This.is"?
Landed on this page for looking for the fastest way to remove the extension from a number file names from a glob() result.
So I did some very rudimentary benchmark tests and found this was the quickest method. It was less than half the time of preg_replace():
$result = substr($fileName,0,-4);
Now I know that all of the files in my glob() have a .zip extension, so I could do this.
If the file extension is unknown with an unknown length, the following method will work and is still about 20% faster that preg_replace(). That is, so long as there is an extension.
$result = substr($fileName,0,strrpos($fileName,'.'));
The basic benchmark test code and the results:
$start = microtime(true);
$loop = 10000000;
$fileName = 'a.LONG-filename_forTest.zip';
$result;
// 1.82sec preg_replace() unknown ext
//do {
// $result = preg_replace('/\\.[^.\\s]{3,4}$/','',$fileName);
//} while(--$loop);
// 1.7sec preg_replace() known ext
//do {
// $result = preg_replace('/.zip$/','',$fileName);
//} while(--$loop);
// 4.57sec! - pathinfo
//do {
// $result = pathinfo($fileName,PATHINFO_FILENAME);
//} while(--$loop);
// 2.43sec explode and implode
//do {
// $result = implode('.',explode('.',$fileName,-1));
//} while(--$loop);
// 3.74sec basename, known ext
//do {
// $result = basename($fileName,'.zip');
//} while(--$loop);
// 1.45sec strpos unknown ext
//do {
// $result = substr($fileName,0,strrpos($fileName,'.'));
//} while(--$loop);
// 0.73sec strpos - known ext length
do {
$result = substr($fileName,0,-4);
} while(--$loop);
var_dump($fileName);
var_dump($result);
echo 'Time:['.(microtime(true) - $start).']';
exit;
Use this:
strstr('filename.ext','.',true);
//result filename
Try to use this one. it will surely remove the file extension.
$filename = "image.jpg";
$e = explode(".", $filename);
foreach($e as $key=>$d)
{
if($d!=end($e)
{
$new_d[]=$d;
}
}
echo implode("-",$new_t); // result would be just the 'image'
EDIT:
The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)

Categories