better way to see if file has certain extention - php

I'm doing this right now in my code to see if a file name has the extension .txt, but I think it basically checks if it contains .txt and not necessarily ends with .txt. Does php have a better way to do extension checking instead of using strpos?
strpos($filename,'.txt') !== false

You can use the pathinfo() function to get the extension of the file:
$info = pathinfo($pathToFile);
$ext = $info['extension'];
and then check if the extension is one of the allowed:
$validExtensions = array("txt", "doc");
if (in_array($ext, $validExtensions) {
//more code
}

Use the following code, it couldn't get any better:
$ext = pathinfo('test.txt', PATHINFO_EXTENSION);

$ext = pathinfo($filename, PATHINFO_EXTENSION);

strpos is okay, you have to just keep in mind that you need not first but last dot.
and use strrpos(), note the double "r".

You can allow multiple extensions by adding to the array.
$allowed = array('txt');
if (in_array(pathinfo($filename, PATHINFO_EXTENSION), $allowed)){
// Has the correct file extension
}
or a simpler version which allows only txt extensions could be:
if (pathinfo($filename, PATHINFO_EXTENSION) == 'txt'){
// Has the correct file extension
}

Related

How to dynamically determine unknown file extension from file in web folder [duplicate]

I want get uploaded image extension.
As I know, best way is getimagesize() function.
but this function's mime, returns image/jpeg when image has .jpg or also .JPEG extension.
How can get exactly extension?
$ext = pathinfo($filename, PATHINFO_EXTENSION);
you can use image_type_to_extension function with image type returned by getimagesize:
$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);
You can also use strrpos and substr functions to get extension of any file
$filePath="images/ajax-loader.gif";
$type=substr($filePath,strrpos($filePath,'.')+1);
echo "file type=".$type;
output: gif
if you want extension like .gif
$type=substr($filePath,strrpos($filePath,'.')+0);
output: .gif
$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);
One more way to do it:
$ext = strrchr($filename, "."); // .jpg
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);
You can also explode the file name with dots and take the end of the array as follows:
$ext = end(explode('.', 'image.name.gif'));
According to: Two different ways to find file extension in PHP
And a new way for you lol:
$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];
For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetype function. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

PHP move_uploaded_file dynamic file name - files have no extension

I want to upload some GPX (XML technically) files to the server and rename them with dynamic file names (such as 0.gpx, 1.gpx ... ). I can not figure out how to do this with the move_uploaded_file function as it only creates the files extensionless. I get a 'name' file instead of a 'name.gpx' file.
Shouldn't it use the PATHINFO_EXTENSION of the uploadef file automatically to create the file with the right extension?
I have tried to call the function like this:
$filename = 0;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$filename++;
Even if I try to create a string with the extension it does not work:
$tmp = 0;
$ext = pathinfo($name, PATHINFO_EXTENSION);
$filename = $tmp + "." + $ext;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Help please?
File name should have the extension. This works fine for me to find the extension:
$temp = explode(".", $_FILES["uploadfiles"]["name"]);
$extension = end($temp);
echo $extension; // Display the extension
$tmp = 0;
$filename = $tmp.".".$extension;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Hope this helps.
I don't think temporary files have an extension.
You could manually add "gpx" to the name :
$tmp = 0;
$filename = $tmp . ".gpx";
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Or maybe check the mimetype and craft the appropriate extension out of it.
Or take the extension in $_FILES['uploadfiled']['name'], match it in a whitelist, and append it to your final filename.

Get image extension

I want get uploaded image extension.
As I know, best way is getimagesize() function.
but this function's mime, returns image/jpeg when image has .jpg or also .JPEG extension.
How can get exactly extension?
$ext = pathinfo($filename, PATHINFO_EXTENSION);
you can use image_type_to_extension function with image type returned by getimagesize:
$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);
You can also use strrpos and substr functions to get extension of any file
$filePath="images/ajax-loader.gif";
$type=substr($filePath,strrpos($filePath,'.')+1);
echo "file type=".$type;
output: gif
if you want extension like .gif
$type=substr($filePath,strrpos($filePath,'.')+0);
output: .gif
$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);
One more way to do it:
$ext = strrchr($filename, "."); // .jpg
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);
You can also explode the file name with dots and take the end of the array as follows:
$ext = end(explode('.', 'image.name.gif'));
According to: Two different ways to find file extension in PHP
And a new way for you lol:
$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];
For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetype function. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
?>
$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

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

How to get only images using scandir in PHP?

Is there any way to get only images with extensions jpeg, png, gif etc while using
$dir = '/tmp';
$files1 = scandir($dir);
You can use glob
$images = glob('/tmp/*.{jpeg,gif,png}', GLOB_BRACE);
If you need this to be case-insensitive, you could use a DirectoryIterator in combination with a RegexIterator or pass the result of scandir to array_map and use a callback that filters any unwanted extensions. Whether you use strpos, fnmatch or pathinfo to get the extension is up to you.
The actual question was using scandir and the answers end up in glob. There is a huge difference in both where blob considerably heavy. The same filtering can be done with scandir using the following code:
$images = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
I hope this would help somebody.
Here is a simple way to get only images. Works with PHP >= 5.2 version. The collection of extensions are in lowercase, so making the file extension in loop to lowercase make it case insensitive.
// image extensions
$extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
// init result
$result = array();
// directory to scan
$directory = new DirectoryIterator('/dir/to/scan/');
// iterate
foreach ($directory as $fileinfo) {
// must be a file
if ($fileinfo->isFile()) {
// file extension
$extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
// check if extension match
if (in_array($extension, $extensions)) {
// add to result
$result[] = $fileinfo->getFilename();
}
}
}
// print result
print_r($result);
I hope this is useful if you want case insensitive and image only extensions.
I would loop through the files and look at their extensions:
$dir = '/tmp';
$dh = opendir($dir);
while (false !== ($fileName = readdir($dh))) {
$ext = substr($fileName, strrpos($fileName, '.') + 1);
if(in_array($ext, array("jpg","jpeg","png","gif")))
$files1[] = $fileName;
}
closedir($dh);
You can search the resulting array afterward and discard files not matching your criteria.
scandir does not have the functionality you seek.
If you would like to scan a directory and return filenames only you can use this:
$fileNames = array_map(
function($filePath) {
return basename($filePath);
},
glob('./includes/*.{php}', GLOB_BRACE)
);
scandir() will return . and .. as well as the files, so the above code is cleaner if you just need filenames or you would like to do other things with the actual filepaths
I wrote code reusing and putting together parts of the solutions above, in order to make it easier to understand and use:
<?php
//put the absolute or relative path to your target directory
$images = scandir("./images");
$output = array();
$filer = '/(.jpg|.png|.jpeg|.gif|.bmp))/';
foreach($images as $image){
if(preg_match($filter, strtolower($image))){
$output[] = $image;
}
}
var_dump($output);

Categories