I have a function that loads all image files it finds in the wordpress uploads directory. I'd like to modify it slightly so that it skips over any image that begins with an underscore character, "_someimage.jpg" is skipped, while "someimage.jpg is not...
Here is the existing function....
$dir = 'wp-content/uploads/';
$url = get_bloginfo('url').'/wp-content/uploads/';
$imgs = array();
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file))
{
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
You can modify your current regex or add an boolean expression using strstr (which I'd recommend).
Modifying your current regex:
"/^[^_].*\.(bmp|jpeg|gif|png|jpg)$/i"
Or a simple expression to detect underscores in the string would be:
strstr($file, '_')
edit: and actually you could use substr:
substr($file, 0, 1) != '_'
if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file))
could be transformed into:
if (!is_dir($file) && preg_match("/^[^_].*\.(bmp|jpeg|gif|png|jpg|)$/i", $file))
Related
I have a folder in a server with a lot of images and I would like to rename some images. Images that contain (1 example:
112345(1.jpg to 112345.jpg. How can I do this using regex in PHP? I have to mention that my knowledge of PHP is very limited and it's the only language that can effectively do the scripting.
preg_match('/\(1/', $entry) will help you.
Also, you need to pay attention to "what if the file has a duplicate after the rename".
$directory = "/path/to/images";
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != '.' && $entry != '..') {
// Check "(1"
if (preg_match('/\(1/', $entry)) {
// Rename file
$old = $directory . '/' . $entry;
$new = str_replace('(1', '', $old);
// Check duplicate
if (file_exists($new)) {
$extension = strrpos($new, '.');
$new = substr($new, 0, $extension) . rand() . substr($new, $extension); // Basic rand()
}
rename($old, $new);
}
}
}
closedir($handle);
}
If you want only remove some substring from images names you can do this without regex. Use str_replace function to replace substring to empty string.
As example:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
You can use scandir and preg_grep to filter out the files that needs to be renamed.
$allfiles = scandir("folder"); // replace with folder with jpg files
$filesToRename = preg_grep("/\(1\.jpg/i", $allfiles);
Foreach($filesToRename as $file){
Echo $file . " " . Var_export(rename($file, str_replace("(1.", ".", $file));
}
This is untested code and in theory it should echo the filename and true/false if the rename worked or not.
Only use regex for this if you need to assert the position of the substring, e.g. if you have filenames like Copy (1)(1.23(1.jpg a simple string replacement will go wrong.
$re = '/^(.+)\(1(\.[^\\\\]+)$/';
$subst = '$1$2';
$directory = '/my/root/folder';
if ($handle = opendir($directory )) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace($re, $subst, $fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
The regular expression used searches for the part before and after the file extension, put the pieces into capturing groups, and glue them together again in the preg_replace without the (1.
I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}
So I am trying to build a script that scans a directory and returns random images to be used as backgrounds.
The php looks like this:
$dir = "views/img/bg/";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$random_key = array_rand($files, 1);
$random = $files[$random_key];
Then I am just using some simple jquery to attach the images as backgrounds:
<script>
$(document).ready(function(){
$("body").css( "background" , "url(http://'.$url_root.'/views/img/bg/'.$random.'), center center" );
});
</script>
Everything works fine but the array of all the images in the background folder seems to be returning stuff like '.' or '..' instead of image names every once in a while. Im not sure what is going on - any ideas?
Use glob() so you can filter the files.
$files = glob('views/img/bg/*.jpg');
$random = $files[array_rand($files)];
Since you're specifying *.jpg, $files contains only JPG files and you don't need to remove the . and .. items.
'.' and '..' are returned for current and parent directory. You can filter them:
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}
Why not use regex? That way it captures any amount of periods. (i.e. ".", "..", "..." etc..)
while (false !== ($filename = readdir($dh))) {
if(!preg_match('/^\.*$/',$filename)){
$files[] = $filename;
}
$dh = opendir("c:\");
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}
I have a directory with a lot of files inside:
pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...
I need to list only the pic_1_ files. Any idea how I can do?
Thanks in advance.
Use the glob() function
foreach (glob("directory/pic_1_*") as $filename) {
echo "$filename";
}
Just change directory in the glob call to the proper path.
This does it all in one shot versus grabbing the list of files and then filtering them.
The opend dir function will help you
$dir ="your path here";
$filetoread ="pic_1_";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (strpos($file,$filetoread) !== false)
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
good luck see php.net opendir
This is what glob() is for:
glob — Find pathnames matching a pattern
Example:
foreach (glob("pic_1*.jpg") as $file)
{
echo $file;
}
Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.
This is one of the samples from the manual
http://nz.php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
you can modify that code to test the filename to see if it starts with pic_1_
using something like this
if (substr($file, 0, 6) == 'pic_1_')
Manual reference for substr
http://nz.php.net/manual/en/function.substr.php
I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle