Solved! "../pictures/uploads/profile" I changed to "./pictures/uploads/profile". My mistake, sorry! And I used answer from #Kunal Raut
I want to get extension of file in PHP from path. I have this code:
$fileName = "../pictures/uploads/profile".$id.".*";
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$sourceImg = "../pictures/uploads/profile".$id.".".$ext."?".mt_rand();
I have folder with pictures. They can be in png or jpg or jpeg. And php file is in another folder. So how do that?
$fileName = "../pictures/uploads/profile".$id.".*"; // <---- this is not a file,put a file name
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
Try this:
$files = scandir("../pictures/uploads/");
foreach ($files as $fileName) {
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
}
Just use the DirectoryIterator class.
foreach (new DirectoryIterator('../pictures/uploads') as $fileInfo) {
if ($fileInfo->isDot()) continue;
if (stripos($fileInfo->getFilename(), 'profile' . $id) !== false) {
var_dump($fileInfo->getExtension());
}
}
The DirectoryIterator class is available since PHP 5.3.6.
A more detailed example could be a DirectoryIterator instance used by a FilterIterator instance to just output the desired files. Th given example requires a minimum of PHP 7.4. If you 're using a PHP version smaller than 7.4 remove the type hints for the class properties.
class MyFileFilter extends FilterIterator
{
protected string $filename;
public function __construct(Iterator $iterator, $filename)
{
$this->filename = $filename;
parent::__construct($iterator);
}
public function accept(): bool
{
$info = $this->getInnerIterator();
return stripos($info->getFilename(), $this->filename) !== false;
}
}
The FilterIterator class is available since PHP 5.1. The above shown extension takes an Iterator and searches for a given filename and returns the SplFileInfo object, if the filename matches.
How to use it:
$directory = new DirectoryIterator('../pictures/uploads');
$filename = 'picture' . $id;
$filter = new MyFileFilter($directory, $filename);
foreach ($filter as $file) {
var_dump($file->getExtension());
}
The foreach loop is basically the filter, that only returns files, that match the given filename. Every returned file is a SplFileInfo instance. With this you can use the SplFileInfo::getExtension() method to get the file extension.
Last but not least comes the GlobIterator class which is available since PHP 5.3. It 's the easiest way to iteratate over a given path with placeholders.
$filesystem = new GlobIterator('../pictures/uploads/profile' . $id . '.*');
foreach ($filesystem as $file) {
var_dump($file->getExtension());
}
You can get all the extensions in the directory by using the function scandir() as
$fileName = scandir("../pictures/uploads/");
$ext = "";
foreach($fileName as $files) {
if($files !== '.' && $files !== '..') {
$ext = pathinfo($files, PATHINFO_EXTENSION);
}
}
echo $ext .'<br>';
Usually scandir() returns the first two values in the array as . and .. and by if condition mentioned in the answer you can delete these unwanted values and get the answer in the pure form.
Note : scandir() returns the values in the form of array.
i got it working see below
Related
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
Need to remove user requested string from file name. This below is my function.
$directory = $_SERVER['DOCUMENT_ROOT'].'/path/to/files/';
$strString = $objArray['frmName']; // Name to remove which comes from an array.
function doActionOnRemoveStringFromFileName($strString, $directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!strstr($file,$strString)) {
continue;
}
$newfilename = str_replace($strString,"",$file);
rename($directory . $file,$directory . $newfilename);
}
}
closedir($handle);
}
}
It works partially good. But the mistake what in this routine is, renaming action also takes on file's extensions. What i need is, Only to rename the file and it should not to be affect its file extensions. Any suggestions please. Thanks in advance :).
I have libraries written by myself that have some of those functions. Look:
//Returns the filename but ignores its extension
function getFileNameWithOutExtension($filename) {
$exploded = explode(".", $filename);
array_pop($exploded);
//Included a DOT as parameter in implode so, in case the
//filename contains DOT
return implode(".", $exploded);
}
//Returns the extension
function getFileExtension($file) {
$exploded = explode(".", $file);
$ext = end($exploded);
return $ext;
}
So you use
$replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
$newfilename = $replacedname.".".getFileExtension($file);
Check it working here:
http://codepad.org/CAKdCAA0
I need to list all files for example mp4 or avi in my folder /Files and relative subdirectories and after that insert into <a href={$filename}><\a> tag so I need a array i suppose.
I tried with find command but I receive a string and not a Array so I've to split the string and this isn't practical.
Any suggestion?
or use class RecursiveDirectoryIterator - For example :
$dir_iterator = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($dir_iterator);
foreach ($iterator as $filename)
{
if (dirname($filename) != dirname(__FILE__))
{
if(is_file($filename)) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == 'mp4' )
{
print ''.basename($filename)."<br />";
}
}
}
}
<?php
$dir ="/Files";
$files = scandir($dir);
foreach($files as $file) {
$fullname = "/Files/" . $file;
echo '<a href='.$fullname.'>File</a>;
}
This should work for you.
I'm using PHP to batch rename some local photos. The script is in the same directory as the photos.
The photos are named like 872376237_Photo_1_001.jpg. The first set of numbers (before the first underscore) is different for each file, and that's what I want to remove.
The format for the new file name should be Photo_1_001.jpg. In the PHP I get the new file name by using $newfilename = substr($filename, strpos($filename, '_') + 1);. Echo'ing out $newfilename shows the correct new file name.
The problem is when I call rename($filename, $newfilename) the files are getting renamed to 1_001.jpg. The $newfilename variable definitely contains the correct new file name. If I use copy() instead of rename() it works as expected. I can't figure this out.
Here's the code:
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$filename = $fileinfo->getFilename();
if ($filename != basename(__FILE__)) { // skip this script
$newfilename = substr($filename, strpos($filename, '_') + 1);
rename($filename, $newfilename);
}
}
}
EDIT: DevZer0 explained why this is happening in the comments. I thought DirectoryIterator compiled a list of all the files before iterating, but it does not. It will continuously iterate as long as new files are created (or renamed).
There's probably a better way to do this, but this works:
$dir = new DirectoryIterator(dirname(__FILE__));
$filenames = [];
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$filename = $fileinfo->getFilename();
if ($filename != basename(__FILE__)) {
$newfilename = substr($filename, strpos($filename, '_') + 1);
array_push($filenames, [$filename, $newfilename]);
}
}
}
foreach ($filenames as $file) {
rename($file[0], $file[1]);
}
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);