I'm adding images to a website but the amount I want to add would take a long time, is there a quicker way of adding these images and for it to automatically find new images if the file name was appended +1 such as image1.jpg, image2.jpg etc.
I am using PHP. Also thought maybe this could be done using a javascript or jquery loop, for loop maybe, im just unsure how.
<img src="images/other/pic2.png"></a>
<img src="images/other/pic3.png"></a>
<img src="images/other/pic4.png"></a>
<img src="images/other/pic5.png"></a>
<img src="images/other/pic6.png"></a>
<img src="images/other/pic7.png"></a>
<img src="images/other/pic8.png"></a>
Its not a good idea to blindly loop a curtain amount of iterations hoping that the file is there and is a valid file, a better way would to loop the directory of files, check that the file is first a valid image and contains the expected filename prefix. This way you can add as may images to the dir knowing that there be added without changing code.
<?php
$img_path = './images/other/';
$prefix = 'img';
if ($fh = opendir($img_path)) {
while (false !== ($file = readdir($fh))) {
if ($file != "." && $file != "..") {
//Validate its an image and get size, also check that the image filename starts with the $prefix
$attr = getimagesize($img_path.$file);
if(isset($attr[3]) && substr($file,0,strlen($prefix)) == $prefix){
echo '<img src="'.$img_path.$file.'" '.$attr[3].' alt="'.$file.'"/>';
}
}
}
closedir($fh);
}
?>
Well judging by your description, doing something like this would probably be suitable:
$initialImageNumber = 2;
$endingImageNumber = 9;
for ($i = $initialImageNumber; $i <= $endingImageNumber; $i++)
echo '<img src="images/other/pic' . $i . '.png">';
Related
I have my folder /images (with ~ 95.000 files), and i check every file if is in the database.
Table : images
Row : hash
The folder containt all my image with sha1 name.
I use shuffle($images); to make sure the verification is random, otherwise it only verifies the first 35,000 images.
If I go over 35,000 checks, the script puts a timeout and the page blocks it.
Example name of an image : d0a0bb3149bea2335e8784812fef706ad0a13156.jpg
My Script :
I select the images in the database
I'm putting it in a array
I make the array random (to avoid always checking the first 35,000
images)
I create a array of images file in the folder /images
I check for missing database files using the array created by the
opendir(); function
I display the answer
<?php
set_time_limit(0);
$images = [];
$q = $mysqli->query('SELECT hash FROM images');
while($r = $q->fetch_assoc())
{
$images[] = $r['hash'].'.jpg';
}
shuffle($images);
$i_hors_bdd = 0;
$images_existent_hors_bdd = [];
if($dh = opendir($_SERVER['DOCUMENT_ROOT'].'/images'))
{
while(($file = readdir($dh)) !== false)
{
if(!in_array($file, $fichiers_a_exclures))
{
if(!is_sha1($file) OR !in_array($file, $images))
$images_existent_hors_bdd[] = '<p>Name of File: '.$file.'</p>';
}
if($i_hors_bdd > 35000)
{
break;
}
$i_hors_bdd++;
}
}
closedir($dh);
if(count($images_existent_hors_bdd) > 0)
{
echo '<p>Image exist, but not in the databse.</p>';
sort($images_existent_hors_bdd);
foreach($images_existent_hors_bdd as $image_existe_hors_bdd)
echo $image_existe_hors_bdd;
}
else
echo '<p>All images are in datase.</p>';
echo '<p>'.$i_hors_bdd.' images checked.</p>';
So my question is: How can I optimize this script to improve the speed of the script to allow checking more images without blocking the script? Knowing that my VPS is not very powerful and I don't have SSD.
Here are some things to consider or try:
Concatenate '.jpg' to hash in the sql, then use fetch_all into a numeric array.
use scandir to build an array of files in the directory
use array_diff to remove $fichiers_a_exclures and $images
iterate over this smallest array to do the sha1 test
Using a WordPress plugin, I have an image carousel that displays all files within a specified folder.
I only want to display the last 24 images from that folder. One way I thought I could do this without editing the original plugin is have all files from the previous day move to a new folder when the first photo from the next day arrives. The file names contain a time stamp, because of this, I can't specify actual file names, just the type of file.
Unfortunately, I am completely new to PHP and Server Side Scripting and would appreciate any advice on how to solve this issue.
I believe you don't have to move the files, just read them and sort by date.
here's a conceptual how to, untested.
$files =[];
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort in reverse order
krsort($files);
for($i =0; $i < 24; $i++) {
$file = $files[$i]
echo "<img src='".$file."' />";
}
}
good luck
Ok, You want to display only last 24 images from that folder.
You can get name of last 24 images by their modification time.
$filelist = glob("/path/to/your_dir/*.{jpg,JPG,PNG,png,jpeg,JPEG}", GLOB_BRACE);
In php run a foreach loop for all the files in that directory, ,
$i = 0;
foreach($filelist as $key => $file){
$temp_arr[$i]['mtime'] = filemtime($file);
$temp[$i]['filename'] = $file;
$i++;
}
Then you can sort $temp_arr to retrive 24 latest images based on mtime.
I am creating a word to image converter and for multy image words, I need to write a bit more complex if statements.
My first if statement works well for 2 image word(word = image + image):
$words = array("car", "bike",...)
foreach ($words as $x => $word) {
$jpg = "Pictures/".$words[$x] . ".jpg";
$jpg1 = "Pictures/".$word."/".$word. "1.jpg";
$jpg2 = "Pictures/".$word."/".$word. "2.jpg";
$jpg3 = "Pictures/".$word."/".$word. "3.jpg";
if (file_exists($jpg1) && file_exists($jpg2)) {
print '<div class="result1"><div id="result1" style="background-image:url('.$jpg1.')"></div>
<div id="result2" style="background-image:url('.$jpg2.')"></div>
<a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
This if spatement says that if the file in directory jpg1 and jpg2 exists, print this...So if it locates just the two files in those directories it will work.
However, when I try adding a 3rd file_exists function to an else if statement like this:
else if (file_exists($jpg1) && file_exists($jpg2) && file_exists($jpg3)) {
print '<div class="result2"><div id="result3" style="background-image:url('.$jpg1.')"></div>
<div id="result4" style="background-image:url('.$jpg2.')"></div>
<div id="result5" style="background-image:url('.$jpg3.')"></div>
<a id="word'. $x .'">'. $words[$x] .'</a></div>';
}
The first if statement overrides the second one, even though the second one is correct. and the first one isn't.
I wanted to ask if everything is correct with my syntax? Or if I can even use multiple file_exists functions like this.
Or any other reason why this might not work.
I'm trying to think of a way to make this happen.
I'm using a jQuery slideshow to display images, and a simple php script to pull the images from a folder based on which gallery the user selects:
$handle = opendir(dirname(realpath(__FILE__)).'/../images/gallery/'.$gallery);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
$pictures .= '<img src="images/gallery/'.$gallery.'/'.$file.'" alt="" />';
}
}
I'm doing it this way since there are 6 different galleries, and the amount of photos in each gallery varies, from about 25 - 40 pictures. If I did the site staticly, or had a database running it'd be no problem, but I can't think of a PHP way of doing this.
Basically here is an example of what I'm hoping to do: I hard coded all the images and text
But on this page I can't think of a good way of doing it
You can add to each folder file like info.txt with descriptions. Check file_exists() on load and get data from the file.
If you want to set desc for each photo you can do smth like:
For files:
flower.jpg
cloud.jpg
girl.jpg
info.txt:
flower.jpg::This is flower
cloud.jpg::This is cloud
girl.jpg::This is girl
So you read info.txt, explode by rows and explode rows at last. At the result you're getting array with descriptions and filenames.
Probably not the best way to do it, but heres my work-around way I accomplished it:`
I renamed the images:
01-A Bird, 02-A Cat
$handle = opendir(dirname(realpath(__FILE__)).'/../images/gallery/'.$gallery);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
$alt = substr($file, 3, -4); //Removes the "##-" and the ".jpg"
$id = substr($file, 0, 2); // Removes EVERYTHING after the "##"
// The image
$pictures .= '<img src="images/gallery/'.$gallery.'/'.$file.'" alt="'.$alt.'" data-caption="#cap'.$id.'" />';
// The text
$span .= '<span class="caption" id="cap'.$id.'">'.$alt.'</span>';
}
}`
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);