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.
Related
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
I could of course check mime types through the exif_imagetype or getimagesize and check mime types one by one... But I just want ANY image - I dont care what type... So I was wondering - can I do something like this: ?
// PHP manual says: Determine the type of an image
// and that Imagetype Constants are 1-17 so :
$tmp_imagetype = exif_imagetype('image.gif');
if ( ($tmp_imagetype>=1) && ($tmp_imagetype<=17) ) {
echo "It is an image!";
} else{
echo "It isn't an image.";
}
Can I rely on that?
What happens when the file is not an image? Will it just return non-image constant value or will it throw a warning or error
Thanks
You really don't need all that you just need the following as exif_imagetype returns false if its not an image
if($imagetype = exif_imagetype('image.gif')){
// its an image
} else {
// its not an image
}
You could check if the function returns (exactly) FALSE:
$file="SOMEFILE";
if(exif_imagetype($file)===FALSE){
print("NOT IMAGE");
}else{
print("IMAGE");
}
Why don't you just put all types of images in an array and then check it with this code:
if(in_array($value, $array)) {
//it's an image! Hooray!
}else {
//it's not.
}
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';
}
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.
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.