refresh / clear / redraw page with content from a different location - php

I've put together some code to search through a directory and for all the jpg images it finds, display thumbnails and my required iptc and exif info.
The problem is that I have many, many directories of photos and as it is I need an index.php file for each one.
My directories are named by month and year; "1401" for January 20014, "1402" for Feb etc. and I have a set of shortcut images for each one called "1401.jpg", "1402.jpg" etc.
so I use this code for users to nagivate to other directories where $shortcut has the values of 1401, 1402 etc:
echo("<img src=\"shortcutimages/" . $shortcut . "\">");
I'd love to allow users to navigate in a similar way without needing multiple index.php files.
I would guess the best way is as follows:
On a mouseclick on a link like above, the main php (similar to below) should be re-run, replacing what's currently displayed on the screen but with new value for $dir replaced with something like $dir="../" . $shortcut;
Is this the way to do it? As a newbie I apologise if this is really simple but as it is I can't seem to work it out.
thanks in advance for your help,
Sivadas
$dir="."; // or other folder path of choice!
$jpgcount=0;
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($image = readdir($dh)) !== false)
{
if (preg_match("/.jpg/", $image)) // only use .jpg files
{
$image=$dir . "/" . $image;
$exif = exif_read_data($image, 0, true);
$exif_name = $exif['FILE']['FileName'];
if(isset($exif['EXIF']['DateTimeOriginal']))
{
$timestamp = $exif['EXIF']['DateTimeOriginal'];
}
else
{
$timestamp = "1971:01:01 01:01:01"; // puts in a datestamp if one doesnt exist
}
$datename[] = $timestamp . $exif_name; // create array of date+name to allow sorting by date then retrieval of date ordered names once datestamp is removed
$jpgcount++; // counts number of jpgs in folder
}
}
sort($datename); // sort date+name array by date
for($c=0; $c<$jpgcount; $c++)
{
$image = pythonslice("$datename[$c]","19:"); // function strips off the datestamp (1st 19 characters) to leave the filename (taken from www.php.net/manual/en/function.substr.php slow at acedsl dot com)
$image=$dir . "/" . $image;
$size = getimagesize("$image", $info);
echo("<tr><td valign=top> <IMG border=0 src=showthumb.php?image=" . str_replace(' ', '%20', $image) ."><td><td valign=top><font size=-1 face=\"Arial Narrow\">"); // get thumbnail and link to full image
show_metadata($image,$info); // function to display all required metadata
echo "</font></td></tr>";
}
closedir($dh);
}
}

Related

How would I link to thumbnails in a subdirectory, when using php to get a list of images?

I'm sorry if the title is a little vague ... I'm still relatively new at PHP (3 months or so) Also, my native tongue is not English, so please bear with me :) I have also searched this site and google extensively to try and find a solution, but without any luck.
I have a script set up in my images directory that scans all the subdirectories, and then outputs a list of links that, if clicked, will take you to a page, where all the images of the selected subdirectory are displayed. The path to such a page would be:
www.mysite.com/images/list_images.php?folderName=RandomFolder
The code for this:
images/index.php
<?php
$path = 'images/' ;
$results = scandir($path);
for ($i=0;$i<count($results);$i++)
{
$result=$results[$i];
if ($result === '.' or $result === '..')
continue;
if (is_dir($path . '/' . $result))
{
echo "<a href='list_images.php?folderName=$result'>$result</a><br/>";
}
}
?>
--------------------
list_images.php
<?php
if(isset($_GET['folderName']))
$folder=$_GET['folderName'];
$path = 'images/'.$folder.'/' ;
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image)
{
echo "<a href='$image'><img src='$image'/></a>";
}
?>
Now, my question:
In each of my image subdirectories I have another subdirectory called 'thumbs', that contains - yes, you guessed it - thumbnails. Each thumbnail is named exactly the same as its corresponding file in the directory above it. Now, how would I make the img src in the above code to point to the thumb?
Any help would be very welcome! Thank you in advance!
EDIT:
I looked over my code again, and I made few extra lines. It still doesn't work, but at least it now outputs thumbnails, which links to the larger image. Here's the new code:
list_images.php
if (isset($_GET['folderName'])) $folder=$_GET['folderName'];
$path = 'images/'.$folder.'/' ;
$thumb_path = ''.$path.'/thumbs/';
$thumbs = glob($thumb_path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($thumbs as $thumb){
foreach ($images as $image){
echo "<a class='fancybox' href='$image'><img src='$thumb'/></a>";
}
}
It kinda works now. The only problem is, that it outputs 13 identical thumbnails to each picture - and it does it 13 times (for a directory containing 13 image files) so there is 169 thumbnails in total.
Any ideas how to fix this?
If you are sure that the folder name is thumbs, there is no reason you can't hardcode this. Take a look at the following.
echo "<a href='$image'><img src='thumbs/$image'/></a>";
You could do a str_replace on the path.
If the path to the image is mydir\image01\pic01.jpg
str_replace('image01','image01\thumb',$image);
would point to mydir\image01\thumb\pic01.jpg

PHP help for a beginner. Scanning file structure to return folder names in an array

I am looking for some help with my code, I have looked elsewhere but am having difficulty to really understand what is going on with the code given elsewhere and I am hoping someone can help me.
I have one gallery page that uses $_POST to change the folder the gallery gets it images form based on the link clicked.
What I want now is to code a search function that looks through them all for a string (a jpg) when it finds it, it returns its img tags and displays the image.
I am having trouble making scandir work and display currently using this code
<?php
$dir = "/galleries/images/adult-cakes/images/";
$scan = scandir($dir);
echo $dir;
print_r($scan);
foreach ($scan as $output) {
echo "$output" . "<br />";
}
?>
that returns the echo dir but nothing else ( please note print was something I tried it was echo before and neither is working.
Then I need to get the output of all the gallery types, adult, anniversary etc and put them into a loop like so
search criteria = cake 1(.jpg)
put scandir info into $folderarray
search this folder until found -
galleries/images/$folderarray/images/
loop
if found then echo img tags with link to pic
if not display not found
This will get an array of all the files in directory $dir
<?php
$dir = "/galleries/images/adult-cakes/images/";
$images = glob($dir . '*');
?>
Do this to get all subdirectories of $Dir into array $DirArray:
$Dir = '/galleries/images/'; //
foreach ( $DirArray = array_filter(glob($Dir . '*'), 'is_dir') as $DirName ) {
$DirName = str_replace($Dir, '', $DirName); // Optionally, remove path from name to display
echo "Dir Name: $DirName <br />\n"; // Test
}
echo var_dump($DirArray); // Test
Modify accordingly

how to scan all usages of a custom function in all my php files?

I have created my own l($text) function in php for a multi lingual website. i use it like this in my documents :
echo '<h1>' . l('Title of the page') . '</h1';
echo '<p>' . l('Some text here...') . '</p>';
My question is, with a php script, how can i scan all my .php files to catch all this function usages and list all the arguments used into a mysql table?
the goal, of course, is to not forget any sentences in my traduction files.
I didn't find anything on google or here, so if you have any ideas, or need some more information.
Could you:
read all *.php files with glob()
then use a regex to pull the strings out (preg_match())
strings simple mysql insert?
Seems simple enough?
i just finished, your help was usefull ! :-)
here is my ugly code for those who can be interested. it's not beautifuly coded, but not made to be loaded 10000 times per day so...
<?php
// define a plain text document to see what appen on test
header('Content-Type: text/plain; charset=UTF-8');
$dossier = 'pages/'; // folder to scan
$array_exclude = array('.', '..', '.DS_Store'); // system files to exclude
$array_sentences_list = array();
if(is_dir($dossier)) // verify if is a folder
{
if($dh = opendir($dossier)) // open folder
{
while(($file = readdir($dh)) !== false) // scan all files in the folder
{
if(!in_array($file, $array_exclude)) // exclude system files previously listed in array
{
echo "\n".'######## ' . strtoupper($file) . ' ##########'."\n";
$file1 = file('pages/'.$file); // path to the current file
foreach($file1 AS $fileline)
{
// regex : not start with a to z characters or a (
// then catch sentences into l(' and ')
// and put results in a $matchs array
preg_match_all("#[^a-z\(]l\('(.+)'\)#U", $fileline, $matchs);
// fetch the associative array
foreach($matchs AS $match_this)
{
foreach($match_this AS $line)
{
// technique of "I do not want to break my head"
if(substr($line, 0, 3) != "l('" AND substr($line, 0, 4) != " l('" AND substr($line, 0, 4) != ".l('")
{
// check if the sentence is not already listed
if(!in_array($line, $array_sentences_list))
{
// if not, add it to the sentences list array and write it for fun !
$array_sentences_list[] = $line;
echo $line . "\n";
}
}
}
}
}
}
}
closedir($dh);
}
}
?>
small precision : i do have to escape various cases as :
-> CSS : background: url('image.jpg');
and
-> jQuery : $(this).html('bla bla');
so here is why the regex starts with [^a-z(] :-)
it works very well now! just have to finish later with recording entries in a mysql table and ensure that i can load the script from time to time when there are changes on the site... keep the existing translation, overwrite the existing files etc... no problem with that.
thanks a gain, this website is really helpful ! :-)

PHP readir results - trying to sort by date created and also get rid of "." and ".."

I have a double question. Part one: I've pulled a nice list of pdf files from a directory and have appended a file called download.php to the "href" link so the pdf files don't try to open as a web page (they do save/save as instead). Trouble is I need to order the pdf files/links by date created. I've tried lots of variations but nothing seems to work! Script below. I'd also like to get rid of the "." and ".." directory dots! Any ideas on how to achieve all of that. Individually, these problems have been solved before, but not with my appended download.php scenario :)
<?php
$dir="../uploads2"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
?>
<p><a href="http://www.duncton.org/download.php?file=login/uploads2/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
While you can filter them out*, the . and .. handles always come first. So you could just cut them away. In particular if you use the simpler scandir() method:
foreach (array_slice(scandir($dir), 2) as $filename) {
One could also use glob("dir/*") which skips dotfiles implicitly. As it returns the full path sorting by ctime then becomes easier as well:
$files = glob("dir/*");
// make filename->ctime mapping
$files = array_combine($files, array_map("filectime", $files));
// sorts filename list
arsort($files);
$files = array_keys($files);

Multiple Random Includes from Directory with Sub-Directories

I have a directory containing sub directories which each contain a series of files. I'm looking for a script that will look inside the sub directories and randomly return a specified number of files.
There are a few scripts that can search a single directories (not sub folders), and other scripts that can search sub folders but only return one file.
To put a little context on the situation, the returned files will be included as li's in an rotating banner.
Thanks in advance for any help, hopefully this is possible.
I think I've got there, not exactly what I set out to achieve but works good enough, arguably better for the purpose, I'm using the following function:
<?php function RandomFile($folder='', $extensions='.*'){
// fix path:
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
// check folder:
if (!is_dir($folder)){ die('invalid folder given!'); }
// create files array
$files = array();
// open directory
if ($dir = #opendir($folder)){
// go trough all files:
while($file = readdir($dir)){
if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){
// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}
if (count($files) == 0){
die('No files where found :-(');
}
// seed random function:
mt_srand((double)microtime()*1000000);
// get an random index:
$rand = mt_rand(0, count($files)-1);
// check again:
if (!isset($files[$rand])){
die('Array index was not found! very strange!');
}
// return the random file:
return $folder . "/" . $files[$rand];
}
$random1 = RandomFile('project-banners/website-design');
while (!$random2 || $random2 == $random1) {
$random2 = RandomFile('project-banners/logo-design');
}
while (!$random3 || $random3 == $random1 || $random3 == $random2) {
$random3 = RandomFile('project-banners/design-for-print');
}
?>
And echoing the results into the container (in this case the ul):
<?php include($random1) ;?>
<?php include($random2) ;?>
<?php include($random3) ;?>
Thanks to quickshiftin for his help, however it was a little above my skill level.
For info the original script which I changed an be found at:
http://randaclay.com/tips-tools/multiple-random-image-php-script/
Scrubbing the filesystem every single time to randomly select a file to display will be really slow. You should index the directory structure ahead of time. You can do this many ways, try a simple find command or if you really want to use PHP my favorite choice would be RecursiveDirectoryIterator plus RecursiveIteratorIterator.
Put all the results into one file and just read from there when you select a file to display. You can use the line numbers as an index, and the rand function to pick a line and thus a file to display. You might want to consider something more evenly distributed than rand though, you know to keep the advertisers happy :)
EDIT:
Adding a simple real-world example:
// define the location of the portfolio directory
define('PORTFOLIO_ROOT', '/Users/quickshiftin/junk-php');
// and a place where we'll store the index
define('FILE_INDEX', '/tmp/porfolio-map.txt');
// if the index doesn't exist, build it
// (this doesn't take into account changes to the portfolio files)
if(!file_exists(FILE_INDEX))
shell_exec('find ' . PORTFOLIO_ROOT . ' > ' . FILE_INDEX);
// read the index into memory (very slow but easy way to do this)
$aIndex = file(FILE_INDEX);
// randomly select an index
$iIndex = rand(0, count($aIndex) - 1);
// spit out the filename
var_dump(trim($aIndex[$iIndex]));

Categories