PHP glob() regex pattern - php

I have a folder that contains logos for sponsors. In my website, a user can belong to a sponsor and the sponsor_id is set in session when the user logs in.
Here is my code:
function sponsor_logos($sponsor_id) {
$logos = glob("resources/content/sites/{$sponsor_id}*");
foreach($logos as $logo) {
if(file_exists("{$logo}"))
echo "<img src='/{$logo}' />";
}
}
The above works, but a sponsor can have multiple logos. So the multiple logos are saved like so: sponsor_id.jpg, sponsor_id_2.jpg, sponsor_id_3.jpg
I am not the strongest at regex, so any help is greatly appreciated! thanks!

You better open directory and check all files in it (if there are not so much files). You could do it like that:
function sponsor_logos($sponsor_id) {
if ($dh = opendir('resources/content/sites/')) {
while (($file = readdir($dh)) !== false) {
if(strpos($file, $sponsor_id . '.') === 0) {
$sponsor_files[] = $file;
}
else if(strpos($file, $sponsor_id . '_') === 0) {
$sponsor_files[] = $file;
}
}
closedir($dh);
}
foreach($sponsor_files as $logo) {
echo "<img src='resources/content/sites/" . $logo . "' />";
}
}
But best solution is to have normal naming scheme.

use this regex sponsor_id(_\d+)?\.jpg

Related

PHP Is there a way to display my list from the foreach separately?

I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}

How to retrieve files on a directory in list using PHP

How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}

How to avoid Parent Directory Link when listing the files of a Directory?

I used the following code to display the contents of a Folder say images (Both Directories as well as Files in that folder)
<?php
$dir="images/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
$newvar1="$dir$filename";// For Hyperlink Path
?>
<p><a href="<?php echo $newvar1; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
But the PHP file shows an output with two additional Links
A link to the folder 'images' and
A Link to the 'Homepage'.
I tried to filter those two links with "filesize" function but getting some error.
How can I resolve this?
Skip current dir and parent dir with a check.
while(...) {
if($filename == ".." || $filename == ".") continue;
...
}
Modify your code to something like this:
while(($filename = readdir($dir_list)) !== false)
{
if($filename != '.' || $filename != '..') // This part to check and ignore
$newvar1="$dir$filename";// For Hyperlink Path
else
continue; //while loop will no further be processed!
//...
}
This is a more in-depth answer and I'm so fed up with such things... This is absolutely an horrible piece of code, even though Php does permit such horrible things.
Something like this is easier to read, easier to maintain, and easier to debug:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
if($filename != ".." && $filename != ".")
{
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink)
{
echo '<p>'.$filename.'</p>';
}
?>
More compact but a bit less easy to read:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if($filename != ".." && $filename != ".") {
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink) {
echo '<p>'.$filename.'</p>';
}
?>
And some people (including my old teachers) tell that "if there's one line of code, don't use {}" (which I strongly disagree because it may lead to errors later on) but here's the "optimized" version:
<?php
$tab = array();
$dir="images/";
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false)
if($filename != ".." && $filename != ".")
$tab[$filename] = $dir.$filename; // Hyperlink Path
closedir($dir_list);
}
foreach ($tab as $filename => $hyperlink)
echo '<p>'.$filename.'</p>';
?>

How to get innermost directory name

I am trying to output a class based on the name of innermost directory name, but can't get it right. Any help would be very much appreciated. It's a php_file_tree, please see section numbered #39 below:
function php_file_tree_dir($directory, $return_link, $extensions = array(), $first_call = TRUE) {
// Get and sort directories/files
if (function_exists("scandir")) {
$file = scandir($directory);
}
else {
$file = php4_scandir($directory);
}
natcasesort($file);
// Make directories first
$files = $dirs = array();
foreach ($file as $this_file) {
if (is_dir("$directory/$this_file")) {
$dirs[] = $this_file;
}
else $files[] = $this_file;
}
$file = array_merge($dirs, $files);
// Filter unwanted extensions
if (!empty($extensions)) {
foreach (array_keys($file) as $key) {
if (!is_dir("$directory/$file[$key]")) {
$ext = substr($file[$key], strrpos($file[$key], ".") + 1);
if (!in_array($ext, $extensions))unset($file[$key]);
}
}
}
// Use 2 instead of 0 to account for . and .. "directories"
if (count($file) > 2) {
$php_file_tree = "<ul";
if ($first_call) {
$php_file_tree .= " class=\"php-file-tree clearfix\"";
$first_call = FALSE;
}
// #39, Here needs to output a class based on innermost directory name
/*
else {
$php_file_tree .= " class=\"innertree ". htmlspecialchars(basename(rtrim($directory, '/'))) ." clearfix\"";
}
*/
$php_file_tree .= ">";
foreach ($file as $this_file) {
if ($this_file != "." && $this_file != "..") {
if (is_dir("$directory/$this_file")) {
// Directory
$php_file_tree .= "<li class=\"pft-directory\"><a class=\"folder \" href=\"#\">". htmlspecialchars($this_file) ."</a>";
$php_file_tree .= php_file_tree_dir("$directory/$this_file", $return_link, $extensions, FALSE);
$php_file_tree .= "</li>";
}
else {
//$ext = "ext-". substr($this_file, strrpos($this_file, ".") + 1); // need to compare speed with native
$ext = "ext-". pathinfo($this_file, PATHINFO_EXTENSION);
$link = str_replace("[link]", base_path() ."$directory/". urlencode($this_file), $return_link);
$php_file_tree .= "<li class=\"pft-file ". strtolower($ext) ."\"><a class=\"screenshot\" title=". htmlspecialchars($this_file) ." href=\"$link\">". htmlspecialchars($this_file) ."</a></li>";
}
}
}
$php_file_tree .= "</ul>";
}
return $php_file_tree;
}
The topmost directory will always have a class "php-file-tree", while the subsequent/ following directories underneath will have their classes based on their own folder names.
Geez, actually it was okay already. Seems the problem was cache or something as I placed it inside modal dialog with AJAX call. I have tried several possibilities before, including "$first_call = FALSE;" to no avail. But when I revisited the directory again, added "$first_call = FALSE;", and clear everything, it now output the folder name correctly.
Sorry to bother, anyone. Thanks

Need to bulletproof this image parser function

I've got a function below which reads the contents of wp-content/uploads and writes out all images that it finds there.
The problem is that it's reading off the blog title to determine the image path and when the blog title has a dot in it, there's trouble
Blog title is abc123.com
site url is abc123.com
test image filename is abc123-1.jpg
img tag SHOULD become:
<img src='http://abc123.com/wp-content/uploads/abc123-1.jpg' />
actual image tag written from the function below is:
<img src='http://abc123.com/wp-content/uploads/abc123.com-1.jpg' />
My question is, how did the ".com" get inserted into the filename???
Function follows...
function get_images()
{
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); }
}
if($cb_custom_images !== "")
{
echo $cb_custom_images;
}
else
{
$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);
}
foreach ($imgs as $idx=>$img)
{
$class = ($idx == count($imgs) - 1 ? ' class="xlast"' : '');
echo '<img src="' . $url . $img . '" alt="' .$img . '"' . $class . ' />';
}
}
}
Are you sure your test file is named abc123-1.jpg? I just copied your code into a file and added dummy scaffolding, including a wp-content/uploads/abc123-1.jpg file.
I got the correct result when I ran the script:
% php img.php
<img src="http://abc123.com/wp-content/uploads/abc123-1.jpg" alt="abc123-1.jpg" class="xlast" />
`
I think it is preg_match issue try to remove character after jpg
Is there a abc123.com-1.jpg file in that directory?
That could be the problem.
Sorry about this one guys, nothing wrong with the function. I had a legacy file that this file relied on that was incompatible. After updating that file, all is well.
Now I just have to figure this one out (assuming I've got any cred left after this one :-) Do we get mulligans around here?

Categories