I am trying to unlink files in a Directory which have no extensions.
I did following, but did not work:
$fileInfo = pathinfo($this->outputPath);
if($fileInfo['extension'] == NULL)
{
unlink($fileInfo['dirname'].$fileInfo['basename']);
}
according to the pathinfo manual :
Note:
If the path does not have an extension, no extension element
will be returned (see second example below).
so you need to check if the returned value has the extension element using isset , note that using empty will pass the dot directories in unix systems, for example if you are iterating some directory empty will consider the . and .. directories as an empty extension elements
// check if not isset
if(isset($fileInfo['extension']) === false) {
// perform some action
}
or if in the future you want to perform some complex search [eg: recursive search for files that does not have extensions] you may use FilesystemIterator
foreach (new FilesystemIterator($dir) as $fileInfo) {
// check if some file extension is null
if ($fileInfo->getExtension() == null) {
// perform some action
}
}
As #CBroe noticed in comments:
Your comparison with NULL is just wrong here.
Check for empty'ness instead:
$fileInfo = pathinfo($this->outputPath);
if(empty($fileInfo['extension']))
{
unlink($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $fileInfo['basename']);
}
Also, you missed a DIRECTORY_SEPARATOR between the dirname and the basename.
Update: As #hassan pointed out, empty is not the proper way to check for this either. That's because of directories . and .. on unix-like systems will pass this test, which is not desired.
So, the proper way to check for files without extension would be:
if(isset($fileInfo['extension']) === false)
{
unlink($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $fileInfo['basename']);
}
Related
I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.
I'd like to be able to search a directory for a file that starts with a specific string, for example:
- foo
- 1_foo.jpg
- 2_bar.png
How would I check directory foo for files that begin with "1_"?
I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.
Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
<?php
foreach (glob('1_*.*') as $filename) {
echo "$filename\n";
}
?>
The above example will output something similar to:
1_foo.png
1_bar.png
1_something.png
Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.
I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).
You can use the glob() function
<?php
$list = glob('1_*.*');
var_dump($list);
I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):
if ($handle = opendir('path/to/folder/'))
{
while ( false !== ($entry = readdir($handle)) ) {
if ( $entry != "." && $entry != ".." ) {
// echo "$entry<br>";
if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
{
// $found_it = TRUE;
}
}
}
closedir($handle);
}
I've been trying to make a simple website that lets you specify a directory, and embeds a player for each mp3 in whatever directory the user specifies. The problem is that no matter how I enter the directory name, glob() does not return any files. I've tried this with local folders, server directories, and the same folder as the php file.
'directoryPath' is the name of the text box where the user enters, you guessed it, the directory path. The 'echo $files' statement displays nothing onscreen. The 'echo "test"' statement DOES run, but the 'echo "hello"' statement in the loop does not execute.
Any help is appreciated!
if (!empty($_POST['directoryPath']))
{
$path = ($_POST['directoryPath']);
$files = glob("$path/{*.mp3}", GLOB_BRACE);
echo $files[0];
echo "test";
foreach($files as $i)
{
echo "hello";
echo $files[$i];
?>
<embed src=<?php $files[$i]; ?> width=256 height=32 autostart=false repeat=false loop=false></embed><?php echo $files[$i] ?></p>
<?php;
}
unset($i);
}
Validate the input first:
$path = realpath($_POST['directoryPath']);
if (!is_dir($path)) {
throw new Exception('Invalid path.');
}
...
Additionally check the return value glob returns false on error. Check for that condition (and ensure you are not using one of those systems that even return false when there are no files found).
I hope this is helpful. And yes, check your error log and enable error logging. This is how you can see what is going wrong.
Also see the following related function for a usage-example and syntax of GLOB_BRACE:
Running glob() from an included script returns empty array
One one tool I find very useful in helping debug variables in PHP is var_dump(). It's a function that provides you with information about a variable's type, it's contents, and any useful metadata it can attain from that variable. This would be a very useful tool for you here, because you'll quickly realize what you have in the variable $i is not at all what you expect.
$files = glob("$path/{*.mp3}", GLOB_BRACE);
foreach ($files as $i) {
var_dump($i);
}
/* Here's a hint, $i is not an index to the $files array.
So $files[$i] makes no sense. $i is actually the value not the key.*/
foreach ($files as $key => $value) { // very different from
// $key is the key to the current element of $files we're iterating over
// $value is the value of the current element we're iterating over
}
So in your code $i is the value not the key. See http://php.net/foreach for more information on how the construct works.
Also, what should be noted here is that you are using a relative path, whereas glob will return an absolute path. By relative this means your searching relative to the CWD (Current Working Directory) of your PHP script. To see wha that is you can use the following code.
var_dump(real_path('.'));
// similarly ...
var_dump(getcwd());
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}
In the script below, I'm trying to copy the folders that exist in the $base directory over to the $target directory. However, in my initial echo test, its returning the . and .. directories even though I'm trying to handle that exception in the conditional.
What am I missing?
$base = dirname(__FILE__).'/themes/';
$target = dirname( STYLESHEETPATH );
$directory_folders = new DirectoryIterator($base);
foreach ($directory_folders as $folder)
{
if ($folder->getPath() !== '.' && $folder->getPath() !=='..' )
{
echo '<br>getPathname: '. $folder->getPathname();
//copy($folder->getPathname(), $target);
}
}die;
However, and this makes no sense to me, if I change the conditional to...
if (!is_dir($folder) && $folder->getPath() !== '.' && $folder->getPath() !=='..' )
It returns the correct folders inside of $base. What?
DirectoryIterator::getPath() returns the full path to the directory -- and not only the last part of it.
If you only want the last portion of that path, you should probably use SplFileInfo::getBasename() in your condition.
Or, for your specific test, you might want to take a look at the DirectoryIterator::isDot() method (quoting) :
Determine if current
DirectoryIterator item is '.' or
'..'
You can use DirectoryIterator::isDot instead:
if (!$folder->isDot())