php - check whether string end with image extension [duplicate] - php

This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 9 years ago.
I need to verify string whether the string is image file name.
$aaa = 'abskwlfd.png';
if ($aaa is image file) {
echo 'it's image';
else {
echo 'not image';
}
How do i do that? It will chck 100 images, so it should be fast. I know there is a filetype verification method, but I think that's slow.. What about preg_match? Is it faster?
I'm not good at preg_match.
Thank you in advance.

Try this:
<?php
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$src_file_name = 'abskwlfd.PNG';
$ext = strtolower(pathinfo($src_file_name, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}
?>

try this code,
if (preg_match('/(\.jpg|\.png|\.bmp)$/i', $aaa)) {
echo "image";
} else{
echo "not image";
}

Maybe you are looking for this:
function isImageFile($file) {
$info = pathinfo($file);
return in_array(strtolower($info['extension']),
array("jpg", "jpeg", "gif", "png", "bmp"));
}
I am using pathinfo to retrieve detail information about file including extension.
I am using strtolower to ensure that the extension will match our list of supported image even it is in different case
Using in_array to check whether file extension is in our list of image extenion.

try this
$allowed = array(
'.jpg',
'.jpeg',
'.gif',
'.png',
'.flv'
);
if (!in_array(strtolower(strrchr($inage_name, '.')), $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
or strrchr it takes last occurence of character string..
else some other concept.
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif',
'application/x-shockwave-flash'
);
if (!in_array($image_name, $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
Here you can used STRTOLOWER function and also used in_array function

try this:
$a=pathinfo("example.exe");
var_dump($a['extension']);//returns exe

Yes, regex is the way to go. Alternatively, you could split around the "." and check the last element in the returned array against an array of image extensions. I'm not a PHP guy so I can't write the code for you, but I can write the regex:
^[a-zA-Z\.0-9_-]+\.([iI][mM][gG]|[pP][nN][gG]|etc....)$
This one is fairly simple. I know you don't have much experience with regex, but here's what this one does:
^: start of string
[a-zA-Z\.0-9_-]: describes range of characters including all letters, numbers, and ._-
\.: "." character
([iI][mM][gG]|[pP][nN][gG]|etc....): | means or. So just put all image extensions you know here. Again, the brackets for case-insensitivity
if you want to match any sequence then instead of the stuff in the brackets and the +, just use:
.*
"." matches any character and "*" means any amount of it. So this just basically says "no restrictions" (except newlines)
There are probably a lot of other things I'm missing, as you can see in the comments. Just read those, look at a regex reference, and you'll be fine.

Try this
use pathinfo():
$ext = pathinfo($file_name, PATHINFO_EXTENSION); case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}

Related

Check if the URL ends with Image Ext

I have this preg_match() here checking of the inputted value is a URL or not.
$regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?#)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS';
if (preg_match($regex, $string)) {
echo "It is an Image URL";
} else {
echo "It is not an Image URL";
}
I took it from Here Since it is clearly has the best validation results, It is too long And i'm not so expert in RegEx So i've tried to add a part where it checks if the URL ends with an image extension
So i've added the following rule .(?:jpg|gif|png) right before ?(?:/[^\s]*)?$_iuS part, But didn't work, What is the mistake i made exactly?
Why not use the proper tools for the job:
$exts = array('jpg', 'gif', 'png');
if(filter_var($string, FILTER_VALIDATE_URL) &&
in_array(strtolower(pathinfo($string, PATHINFO_EXTENSION)), $exts)) {
echo "It is an Image URL";
} else {
echo "It is NOT an Image URL";
}
filter_var has many validate filters and pathinfo can return information about the path.

Is in PHP a function which can check if string is a extension?

Is In PHP a function which can check if string is a extension of a file? For example:
$q = 'txt';
if ( is_extension($q) )
{
echo "yee, this is a extension";
}
else
{
echo "no, this isn't any extension";
}
I have a URL, for example: http://example.com/user-name/user-dir/any-file-to-download.txt(text). I would like to check if this URL contain any extension and check if this extension is correct.
Thanks!
pathinfo comes to the rescue:
echo pathinfo('http://example.com/a.txt', PATHINFO_EXTENSION);
//β‡’ txt
To check against permitted exts:
echo in_array(
pathinfo('http://example.com/a.txt', PATHINFO_EXTENSION),
array('txt','html')
);
//β‡’ 1
Though above is doing it’s job, checking MIME-type is way more error-prone and handy.
Just use pathinfo() function in php to get the extension. TO check if the extension is correct or not you will have to make a array of extensions. Use the code below
<?php
$url = ' http://example.com/user-name/user-dir/any-file-to-download.txt(text)';
$array = array("txt","doc");
$extension = pathinfo($url, PATHINFO_EXTENSION);
if($extension !=="" && in_array($extension, $array)){
echo "It has extension and that is ".$extension ;
}
else{
echo "It doesn't have extension";
}
Hope this helps you

How to check a file is video type or not in php?

I have following script:
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('upload');
My question is I want to detect a file is video(mp4 or mov)type, How i can detect $ff is a video type or not?
// Type contains video/mp4,video/avi,video/mpeg,video/mpg etc
if(preg_match('/video\/*/',$_FILES['add_image_image']['type'])):
echo "THIS IS A VIDEO FILE";
else:
echo "NOT A VIDEO FILE";
endif;
if(end(explode(".",$ff)) =="mp4")
{
echo "its an mp4 movie";
}
There you go, for case insensitive version of the extension
<?php
$ff="abc.MP4";
if(strtolower(end(explode(".",$ff))) =="mp4")
{
echo "its an mp4 movie";
}
?>
Use mime_content_typemime_content_type php.net
if (mime_content_type($dir.'/'.$ff)=='video/mp4')
echo "its mp4";
I use this code:
$mimeType = mime_content_type(public_path('uploads/' . $file));
$fileType = explode('/', $mimeType)[0]; // video|image
if ($fileType === 'video') {
// do something
}
Please use a tool like file. This answer is security aware, and a general response to uploaded file types. The second advantage to using file is it will tell you more detail about the format used. There are alot of combinations of formats that may be legitimately stored inside a '*.mpg' file. You may not be able to deal with all of them.
I did a more detailed websearch, there is a list of duplicate text articles, but no reliable solutions posted. There is a "magic bytes" detector in the form of fileinfo. This is compiled into most recent versions of PHP (its a standard extension).
NB: mime_content_type() is deprecated. Again, if you need to, try fileinfo
You can achive with preg_match
if(preg_match('/^.*\.(mp4|mov)$/i', $filename)) {
echo $filename;
}
You can append another video ext like: (mp4|mov|mpg|mpeg|wmv|mkv)
You can also try this. Should be fairly accurate and performant
<?php
function isVideo($file) {
return is_file($file) && (0 === strpos(mime_content_type($file), 'video/'));
}
?>
I recently use this to get the file type i.e. image or video:
explode('/', $request->article_thumbnail->getMimeType())[0]
Get the mime type of the uploading file and check the type like below,
$mime = $file->getMimeType;
$videoJS = array('video/mp4','video/ogg','video/webm');
if(array_search($mime, $videoJS) !== false) {
//do upload
}
$fileType = exec( 'file --mime-type '.escapeshellarg($filePath)); //e.g. output -> /tmp/somefile.mov: video/quicktime
$fileType = substr($fileType, strpos($fileType, ": ") + 2); //strip away file path -> video/quicktime
$fileType = substr($fileType, 0,strpos($fileType, "/")); //strip away whatever video type -> video
if ($fileType == 'video') $fileType = 'im a video!';
This code uses unix 'file' command with the option --mime-type to minimize the output for easier parsing. Not sure if there is a better way of parsing the output.
Also make sure you have read permission of the file you are checking.

PHP in_array and if check not working

I've got a script and simple if check to see if a value is in a array. I can't seem to find out why the if tag runs when it's in the array.
else if (!in_array($type, $avatarformats)) {
$error .= '<div class="alert error">You\'re image is not a allowed format</div>';
unlink($_FILES['file']['tmp_name']);
}
When the script reads $type and $avatarformats it's = to the following.
$avatarformats = Array ( [0] => .jpg [1] => .jpeg [2] => .png )
$type = .png
The if tag runs when it should not because .png is in the array. Or am I no understaind what am doing.
I'm not sure how you determined the type, but typically the ['type'] that comes from $_FILES is the content type (e.g. 'image/jpeg'), rather than the extension of the filename itself.
To test for file extensions, you could use this code:
// get file extension (without leading period)
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// ...
elseif (!in_array($ext, array('png', 'jpg', 'jpeg'))) {
// error
}
Note: Use exif_imagetype(), please read http://www.php.net/manual/en/function.exif-imagetype.php
function image_allowed($imgfile) {
$types = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
return in_array(exif_imagetype($imgfile), $types);
}
Then in your code.
else if (!image_allowed($_FILES['file']['tmp_name'])) {
$error .= '<div class="alert error">You\'re image is not a allowed format</div>';
unlink($_FILES['file']['tmp_name']);
}
I suspect that in_array() is returning true because the statement !in_array($type, $avatarformats) is evaluating to true due to the full stop. It is evaluating the value of $type as an integer because of the decimal place.
That being said you have 2 options:
1) Try stripping the dot i.e. ".png" to "png" from the file extension before adding it to the array in the first place and then do the test.
2) or change your conditional to the following: else if (in_array($type, $avatarformats) == false) {
in_array() is a strange beast and I try to avoid it at the best of times. isset() is your friend and much faster than in_array under most conditions anyways.

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