Suggest file extension from file type - php

I have an image file name without extension (lets assume it is image_file_name - NOTE IT IS MISSING THE EXTENSION) and I also know the file type (lets assume the file type is image/jpeg). Now is there a php function that returns the file extension given its type? As explained in the following pseudo code:
$extension = get_extension('image/jpeg'); // Will return 'jpg'
$file_name = 'image_file_name' . '.' . $extension; // Will result in $file_name = image_file_name.jpg
Please note that the image above was only an example, the file name could be of any file type, such as a web page file name or anything else. and the extension could be anything as well, it could be html, css ...etc.
Is it possible to do the above? And how?

$ext = substr(image_type_to_extension(exif_imagetype('dev.png')), 1); //example png
This will give you the extension correctly and is more reliable than $_FILE['image']['type'].

You can use finfo to perform mime-magic to determine the file type.
$finfo = finfo_open(FILEINFO_MIME, "/path/to/mimiemagic.file");
$res = $finfo->file($filename);
list($type, $encoding) = explode(";", $res);
$typeToExt = array(
"image/jpeg"=>"jpg",
"image/png"=>"png",
"text/html"=>"html",
"text/plain"=>"txt",
"audio/mpeg"=>"mp3",
"video/mpeg"=>"mpg"
);
$ext = $typeToExt[$type];

You can use FILEINFO_MIME directly to determine MIME type and then use a switch case to add extension. There is this mime_content_type(), but it seems deprecated.
$finfo = new FileInfo(null, 'image_file_name');
// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {
case 'image/jpg':
$extension = 'jpg'
$file_name = 'image_file_name' . '.' . $extension;
break;
case 'image/png':
$extension = 'png'
$file_name = 'image_file_name' . '.' . $extension;
break;
case 'image/gif':
$extension = 'gif'
$file_name = 'image_file_name' . '.' . $extension;
break;
}
For more extensions, keep adding cases to switch.

Related

Get Image File Extension with PHP

The file name is known but the file extension is unknown. The images in thier folders do have an extension but in the database their names do not.
Example:
$ImagePath = "../images/2015/03/06/"; (Folders are based on date)
$ImageName = "lake-sunset_3";
Does not work - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath))->getExtension();
echo $Ext;
Does not work either - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath.$ImageName))->getExtension();
echo $Ext;
Does not work either - $Ext is still empty:
$Ext = (new SplFileInfo($ImagePath,$ImageName))->getExtension();
echo $Ext;
$Ext should produce ".jpg" or ".jpeg" or ".png" etc.
So my question is simple: What am I doing wrong?
Now, this is a bit of an ugly solution but it should work. Make sure that all your files have unique names else you'll have several of the same file, which could lead to your program obtaining the wrong one.
<?php
$dir = scandir($imagePath);
$length = strlen($ImageName);
$true_filename = '';
foreach ($dir as $k => $filename) {
$path = pathinfo($filename);
if ($ImageName === $path['filename']) {
break;
}
}
$Ext = $path['extension'];
?>
Maybe this might help you (another brute and ugly solution)-
$dir = '/path/to/your/dir';
$found = array();
$filename = 'your_desired_file';
$files = scandir($dir);
if( !empty( $files ) ){
foreach( $files as $file ){
if( $file == '.' || $file == '..' || $file == '' ){
continue;
}
$info = pathinfo( $file );
if( $info['filename'] == $filename ){
$found = $info;
break;
}
}
}
// if file name is matched, $found variable will contain the path, basename, filename and the extension of the file you are looking for
EDIT
If you just want the uri of your image then you need to take care of 2 things. First directory path and directory uri are not the same thing. If you need to work with file then you must use directory path. And to serve static files such as images then you must use directory uri. That means if you need to check files exists or what then you must use /absolute/path/to/your/image and in case of image [site_uri]/path/to/your/image/filename. See the differences? The $found variable form the example above is an array-
$found = array(
'dirname' => 'path/to/your/file',
'basename' => 'yourfilename.extension',
'filename' => 'yourfilename',
'extension' => 'fileextension'
);
// to retrieve the uri from the path.. if you use a CMS then you don't need to worry about that, just get the uri of that directory.
function path2url( $file, $Protocol='http://' ) {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$image_url = path2url( $found['dirname'] . $found['basename'] ); // you should get the correct image url at this moment.
You are calling a file named lake-sunset_3. It has no extension.
SplFileInfo::getExtension() is not designed to do what you are requesting it to do.
From the php site:
Returns a string containing the file extension, or an empty string if the file has no extension.
http://php.net/manual/en/splfileinfo.getextension.php
Instead you can do something like this:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
getExtension() only returns the extension from the given path, which in your case of course doesn't have one.
In general, this is not possible. What if there is a file lake-sunset_3.jpg and a file lake-sunset_3.png?
The only thing you can do is scan the directory and look for a file with that name but any extension.
You're trying to call an incomplete path. You could try Digit's hack of looking through the directory for for a file that matches the name, or you could try looking for the file by adding the extensions to it, ie:
$basePath = $ImagePath . $ImageName;
if(file_exists($basePath . '.jpg'))
$Ext = '.jpg';
else if(file_exists($basePath . '.gif'))
$Ext = '.gif';
else if(file_exists($basePath . 'png'))
$Ext = '.png';
else
$Ext = false;
Ugly hacks aside, the question begging to be asked is why are you storing them without the extensions? It would be easier to strip off the extension if you need to than it is try and find the file without the extension

PHP+Image type detection

I have a email script that sends file trough attachment from server. The email is sent using phpmailer and the attached file is attached in code like this:
$_img = (object) ($img);
if (!empty($_img->src)) {
$ext = substr($_img->src, -3);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
break;
case "image/png":
$type = "image/png";
break;
case "image/gif":
$type = "image/gif";
break;
}
$string = file_get_contents($_img->src);
$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
}
The problem occurs when a image is not properly saved before adding it to server. If one user decides that the file 'test.jpg' shoul be 'test.png' the attached file will not be visible via email.
The $_img->src is a file saved on server.
I am trying to check for mime type but still with no success.
I want to be able to tell the script that the correct file type is the one auto detected not determined by the extension.
Could someone give me a clue about how this could be done?
$_img = (object) ($img);
if (!empty($_img->src)) {
//$ext = substr($_img->src, -3);
// better solution for get file extension (with variable length: "jpeg" or "jpeg")
$ext = pathinfo($_img->src, PATHINFO_EXTENSION);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
$ext = 'jpg';
break;
case "image/png":
$type = "image/png";
$ext = 'png';
break;
case "image/gif":
$type = "image/gif";
$ext = 'gif';
break;
// fix for others mime type
default:
$type = "application/octet-stream";
}
// for binary file use AddAttachment()
//$string = file_get_contents($_img->src);
//$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
// I hope that the variable $i is set from previous code
$mail->AddAttachment($_img->src, $i . '.' . $ext, 'base64', $type)
}
You can detect the type of the image with the IMAGETYPE_XXX constants at index 2 of the returned imginfo_array. The returned mime field you are using is much less reliable.
See documentation:
http://php.net/manual/en/function.getimagesize.php
Type contants:
http://php.net/manual/en/image.constants.php

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.

How to download the file uploaded to a BLOB field using PhpMyAdmin?

I'm running a localhost mysql server with PhpMyAdmin version 4.2. I created a table with a MEDIUMBLOB column to store file. I can upload *.doc files correctly, but when I click the file link, it downloads it as a "tablename-columnname.bin" bin file.
Then I tried to manually rename this "tablename-columnname.bin" to "original_file.doc" and the doc can be opened correctly.
Question: Why phpmyadmin does not download the file as is? What can I do to fix it? I know a bit of php
Thanks!
Use the 'header' before echo the file
header('Content-type: application/msword');
for dynamic way to find the 'Content type' use to store the 'file name' with 'extension' in database.
To make it a bit dynamic (based on MIME) I did the following change:
In tbl_get_field.php file, last few lines:
$mime = PMA_detectMIME($result);
switch($mime){
case 'image/jpeg':
$extension = 'jpg';
case 'image/gif':
$extension = 'gif';
case 'image/png':
$extension = 'png';
case 'application/pdf':
$extension = 'pdf';
default:
$extension = 'bin';
}
PMA_downloadHeader(
$table . '-' . $_GET['transform_key'] . '.' . $extension,
$mime,
strlen($result)
);
echo $result;
Code above should output the file with correct extension instead of always ".bin".
In mime.lib.php file, we need to detect more MIME cases:
function PMA_detectMIME(&$test)
{
$len = strlen($test);
if ($len >= 2 && $test[0] == chr(0xff) && $test[1] == chr(0xd8)) {
return 'image/jpeg';
}
if ($len >= 3 && substr($test, 0, 3) == 'GIF') {
return 'image/gif';
}
if ($len >= 4 && substr($test, 0, 4) == "\x89PNG") {
return 'image/png';
}
return 'application/octet-stream';
}
I want to add pdf and word doc in this, but I dont know how to determine their MIME type base on the stream characters

How to find the file name or extension from base name

I want to grab the file name from a known base name in PHP.
I've searched and found pathinfo(), but then you already give the file name with base name and extension in the argument.
Also in the pathinfo() docs:
$path_parts = pathinfo('/path/basename');
var_dump($path_parts['extension']);
That's more or less what I need, but the result is :
string '' (length=0)
I want the extension, not an empty string. I know the base name, but I don't know the extension, how do I grab that?
To list file names, knowing only the base, you can use glob. It returns an array because there may be several files with the same base but different extensions, or none at all:
$files = glob($base.'.*');
if (!empty($files))
echo $files[0];
If file has an extension you can get it like this
$file_name = 'test.jpg';
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
echo $ext; // output:jpg
Example: To scan all files in images directory and show if ext is allowed or not
$image_path = __DIR__ . '/images/';
$files = scandir($image_path);
$allowed_images = array('jpg', 'jpeg', 'gif', 'png');
foreach ($files as $file_name) {
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if (in_array($ext, $allowed_images)) {
echo $ext . ' allowed<br>';
} else {
echo $ext . ' not allowed<br>';
}
}
You could use:
$ext = end(explode('.',$filename));
Note: it's not secure to rely on this extension to determine the file type.

Categories