PHP move_uploaded_file dynamic file name - files have no extension - php

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.

Related

rename file while uploading with php

I have a php script which uploads files:
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
// File path
$path = '../pdf/'.$filename;
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
This works fine!
But I would like to modify the filename while uploading:
For example:
I uploading a "upload.pdf" file.
But I would like to get the name "upload_2021.pdf"
How can I realize it?
I found a solution !!
$path = '../pdf/'.$filename;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$name = pathinfo($path, PATHINFO_FILENAME);
From what I can see, the only thing you need to do is change the $path variable.
Bare in mind, that what you are showing here is not a safe and secure upload script. You are not doing any file and mime-type validation what so ever. There is nothing preventing your users from uploading harmful files. Together with not checking for duplicate files and some other edge cases, think twice before putting this into production.
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
$parts = explode(".", $filename);
$year = date("Y");
// File path
$path = '../pdf/'.$parts[0] . '_' $year . '.' . $parts[count($parts)-1];
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
}
a short example:
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

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

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.

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

PHP strip unknown file extension

I understand that using PHP's basename() function you can strip a known file extension from a path like so,
basename('path/to/file.php','.php')
but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?
Thanks in advance!
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.
$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);
The value of $filename will be file.
You can extract the extension using pathinfo and cut it off.
// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");
Note the . before $ext
$filename = preg_replace('#\.([^\.]+)$#', '', $filename);
You can try with this:
$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));
Try this:-
$path = 'path/to/file.php';
$pathParts = pathinfo( $path );
$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];

Categories