Dynamically including multiple files within php for image descriptions - php

Working on implementing image descriptions to a php run gallery and can't seem to figure out how to call each text file for each individual image. I would need to place a div in the code for the image and then call the include.
//total number of images
$total = 77;
//max number of thumbnails per page
$max = 9;
//what image do we want to start from?
$startcount = $_GET["start"];
//if there is not a defined starting image, we start with the first
if(empty($startcount))
{
$startcount = 0;
}
//start off the loop at 1
$loop = 1;
//start the loop
while($loop <= $max)
{
//for the picture labels
$num = $startcount + $loop;
if($num > $total)
{
$num = $num - 1;
break;
}
// Add class="last" to every third list item
if(is_int($num / 3))
{
$last = ' class="last"';
}
else
{
$last = "";
}
//the code for the image
echo '
<li'.$last.'><img src="images/portfolio/thumbs/pic-'.$num.'-thumb.jpg" width="256" height="138" alt="Thumbnail of image '.$num.'" /><div>'.$num.'</div></li>';
I see that I can call the text files by number using '.$num.' (I have 77 individual text files with a phrase in each) but how do I tell it to call the files?

Assuming the description files are named something like "description_$num.txt", you can simply use readfile.
echo "<li${last}><a href='images/portfolio/pic-${num}.jpg' rel='milkbox[gall1]'>
<img src='images/portfolio/thumbs/pic-${num}-thumb.jpg' width='256'
height='138' alt='Thumbnail of image ${num}'/>
</a><div>";
readfile("description_${num}.txt");
echo '</div></li>';
Note that you don't "call" files in PHP, you either include them (which interprets them as scripts) or read them (which dumps them to the output).

For each file you need to do something like that:
<?php
$f=fopen($file,'r');
$data='';
while(!feof($f))
$data.=fread($f,$size);
fclose($f);
// do whatever you want with the file content.
?>

I made use of file_get_contents, and split the output a bit so you can more easily modify it:
<?php
$total = 77;
$max = 9;
$startcount = $_GET["start"];
$loop = 1;
if(empty($startcount)) $startcount = 0;
while($loop <= $max)
{
$num = $startcount + $loop;
if($num > $total)
{
$num--;
break;
}
$last = ($num % 3 == 0 ? ' class="last"' : '');
$output = "<li $last>";
$output .= "<a href=\"images/portfolio/pic-$num.jpg\" rel=\"milkbox[gall1]\">";
$output .= "<img src=\"images/portfolio/thumbs/pic-$num-thumb.jpg\" width=\"256\" height=\"138\" alt=\"Thumbnail of image $num\">";
$output .= "</a>";
$output .= "<div>";
$output .= file_get_contents("textfile-" . $num . ".txt"); // assuming this is where you want the phrase
$output .= "</div>";
$output .= "</li>";
echo $output;
}
?>

Related

PHP selecting images with specific width and building a grid

I'm having trouble with building a dynamic grid with PHP like this:
I have an array containing images in various sizes, but always either 900 or 1800 in width.
Looks like this:
$images = array('img_1_900.jpg', 'img_2_900.jpg', 'img_3_1800.jpg', 'and so on');
Is there any smart way to do this? I'm kind of new to the PHP-thing, so any hints could be nice. Here's what i got so far:
$img_count = count($images);
$i = 1;
while($i <= $img_count){
list($width) = getimagesize($images[$i]);
if($width = 1800){
}
$i++;
}
I know this does nothing, but i simply don't know where to go from here. Hope some kind soul could help me a little along. I can't just float them, because they need to stay on line even after a resize, so some kind of table/table-div has to do it. I guess.
Thanks in advance!
if your image array is allway build in the same way... and not getting sorted...
$i = 0;
$html = "<table cellpadding='0' cellspacing='10' border=1>"
foreach($image as $img){
if($i == 0)
$html .= "<tr>";
if($i < 2){
$html .= "<td><img src='{$img}' /></td>";
$i++;
}
if($i == 2){
$html .= "</tr><tr>";
$html .= "<td colspan=2><img src='{$img}' /></td>";
$i = 0;
}
}
echo $html;
I can't write full functional code for you but I'll write pseudo code
H_MARGIN = // horizontal margin between elements
V_MARGIN = // vertical margin
I_HEIGHT = // Image height
$ImgWidth = 1800 + H_MARGIN
$I1800 = // Number of 1800 images
$I900 = // Number of 900 images
$NRows = $I1800 + ceil($I900 /2);
$ImgHeight = $NRows * I_HEIGHT + V_MARGIN * ($NRows - 1);
- Create $ImgWidth*$ImgHeight image
*- Blit 900 image then v_margin
- If still a 900 blit next to the first
- Else blit a 1800 then h_margin
- While images left loop back to *

how to show random articles

I am working on project which shows articles and this was done by article manager (a ready to use php script) but I have a problem, I want to show only four article titles and summaries from old list of article randomly which contains 10 article. Any idea how to achieve this process?
I have auto generated summary of article
<div class="a1">
<h3><a href={article_url}>{subject}</h3>
<p>{summary}<p></a>
</div>
When a new article is added the above code will generated and add into summary page. I want to add it to side of the main article page, where user can see only four article out of ten or more randomly.
<?php
$lines = file_get_contents('article_summary.html');
$input = array($lines);
$rand_keys = array_rand($input, 4);
echo $input[$rand_keys[0]] . "<br/>";
echo $input[$rand_keys[1]] . "<br/>";
echo $input[$rand_keys[2]] . "<br/>";
echo $input[$rand_keys[3]] . "<br/>";
?>
Thanks for your kindness.
Assuming I understood you correctly - a simple solution.
<?php
// Settings.
$articleSummariesLines = file('article_summary.html', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$showSummaries = 4;
// Check if given file is valid.
$validFile = ((count($articleSummariesLines) % 4 == 0) ? true : false);
if(!$validFile) {
die('Invalid file...');
}
// Count articles and check wether all those articles exist.
$countArticleSummaries = count($articleSummariesLines) / 4;
if($showSummaries > $countArticleSummaries) {
die('Can not display '. $showSummaries .' summaries. Only '. $countArticleSummaries .' available.');
}
// Generate random article indices.
$articleIndices = array();
while(true) {
if(count($articleIndices) < $showSummaries) {
$random = mt_rand(0, $countArticleSummaries - 1);
if(!in_array($random, $articleIndices)) {
$articleIndices[] = $random;
}
} else {
break;
}
}
// Display items.
for($i = 0; $i < $showSummaries; ++$i) {
$currentArticleId = $articleIndices[$i];
$content = '';
for($j = 0; $j < 4; ++$j) {
$content .= $articleSummariesLines[$currentArticleId * 4 + $j];
}
echo($content);
}

Adding filename to glob script

I am using the following script to display all my images on a page. I am looking to have about 12000 images in this folder, hence the need for pagination. The files names are numbers in ascending order 1 - 12000 and must be displayed in order.
<?php
$dir = "../image/thumb/";
//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg";
//Set the number of images you want to display per page
$imagesPerPage = 20;
//Set the $page variable
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);
//Count the number of images
$totalImages = count($images);
//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);
//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
//Set the currnet page to the total pages.
$page = $totalPages;
}
//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;
//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
//We need to make sure that its within the range of totalImages.
if($i < $totalImages){
//Now we can display the image!
echo "<img src='{$images[$i]}' alt='{$images[$i]}' />";
}
}
//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
if($p == $page){
$tmp_pages[] = "<strong>{$p}</strong>";
}else{
$tmp_pages[] = "<a href='?page={$p}'>{$p}</a>";
}
}
//Now display pages, seperated by a hyphon.
echo "<br />" . implode(" - ", $tmp_pages);
?>
I need to have the filenames echo below each image how can I achieve this?
Many thanks in advance.
===== EDIT =====
This script now works with thanks to SuperScript The complete code is:
<?php
//The directory to your images folder, with trailing slash
$dir = "../image/thumb/";
//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg";
//Set the number of images you want to display per page
$imagesPerPage = 20;
//Set the $page variable
if(!isset($_GET['page'])){
$page = 1;
}else{
$page = $_GET['page'];
}
//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);
usort($images,function($a,$b){
$a=(int)preg_replace('~\D~','',$a);
$b=(int)preg_replace('~\D~','',$b);
return $a<$b?-1:1;
});
//Count the number of images
$totalImages = count($images);
//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);
//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
//Set the currnet page to the total pages.
$page = $totalPages;
}
//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;
//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
//We need to make sure that its within the range of totalImages.
if($i < $totalImages){
//Now we can display the image!
// echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><a class=\"filename\">" . basename($images[i]) . "</a>";
echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><p>" . basename($images[$i]) . " </p>";
}
}
//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
if($p == $page){
$tmp_pages[] = "<strong>{$p}</strong>";
}else{
$tmp_pages[] = "<a href='?page={$p}'>{$p}</a>";
}
}
//Now display pages, seperated by a hyphon.
echo "<br />" . implode(" - ", $tmp_pages);
?>
Try changing your echo line (//Now we can display the image!):
echo "<img src='{$images[$i]}' alt='{$images[$i]}' /><p>" . basename($images[$i]) . "</p>";
The basename() function returns just the filename of a file.
And to sort correctly, add this line after you get $images:
usort($images,function($a,$b){
$a=(int)preg_replace('~\D~','',$a);
$b=(int)preg_replace('~\D~','',$b);
return $a<$b?-1:1;
});

How can I stop certain part of my php script from executing? (to make my page load faster)

<?php
$rows_per_page = 2;
$cols_per_page = 2;
$image_href = '<a href=/';
$image_links = array('file1/page1>', 'file2/page2>', 'file3/page3>',
'file4/page4>', 'file5/page5>', 'file6/page6>', 'file6/page6>',
'file/page7>', 'file/page8>', 'subfile/page9>');
$img_srcs = '<img src="https://s3.amazonaws.com/imagetitle/';
$images = array();
for($i = 1; $i < 10; $i++)
{
$images[$i] = $i;
}
$image_ending = '.png" height="200" width="200" /></a>';
$image_descriptions = array('<br />something', '<br />description',
'<br />arbitrary', 'random', '<br />you', '<br />get', '<br />the',
'<br />idea', '<br />itsdescriptions');
$total_images = count($images);
$images_per_page = $rows_per_page * $cols_per_page;
$total_images = count($images);
$total_pages = ceil($total_images / $images_per_page);
$current_page = (int) $_GET['page'];
if($current_page<1 || $current_page>$total_pages)
{
$current_page = 1;
}
//Get records for the current page
$page_image_links = array_splice($image_links, ($current_page-1)*$images_per_page, $images_per_page);
$page_images = array_splice($images, ($current_page-1)*$images_per_page, $images_per_page);
$page_image_descriptions = array_splice($image_descriptions, ($current_page-1)*$images_per_page, $images_per_page);
$slots = "<table border=\"1\">";
for($row=0; $row<$rows_per_page; $row++)
{
$slots .= "<tr>";
for($col=0; $col<$cols_per_page; $col++)
{
$imgIdx = ($row * $rows_per_page) + $col;
$img = (isset($page_images[$imgIdx])) ? "{$image_href}{$page_image_links[$imgIdx]}{$img_srcs}{$page_images[$imgIdx]}{$image_ending}{$page_image_descriptions[$imgIdx]}" : ' ';
$slots .= "<td>$img</td>";
}
$slots .= "</tr>";
}
$slots .= "</table>";
//Create pagination links
$first = "First";
$prev = "Prev";
$next = "Next";
$last = "Last";
if($current_page>1)
{
$prevPage = $current_page - 1;
$first = "First";
$prev = "Prev";
}
if($current_page<$total_pages)
{
$nextPage = $current_page + 1;
$next = "Next";
$last = "Last";
}
?>
<html>
<title></title>
<body>
<h2>Here are the records for page <?php echo $current_page; ?></h2>
<ul>
<?php echo $slots; ?>
</ul>
Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
<br />
<?php echo "{$first} | {$prev} | {$next} | {$last}"; ?>
</body>
</html>
So basically this code above makes it easy to put up images and their links. For now, I don't have that many images, so the page runs super fast. However, I'm thinking in the long run. If I have say, 10,000 images, it's gonna take a long time to process each paginated page, as I would have $image_links of file1/page1 up to file10000/page10000, and 10000 descriptions! Is there a way to stop the web browser from reading, or skip, certain parts of the script (the $image_links and $image_descriptions in my case)? That way, it won't need to read through all 10000 $image_links and $image_descriptions.
Thanks!
I'm going to suggest another approach. Using arrays for this is not ideal; it really feels like it should be a database driven app.
If you decide to go for that approach, pagination becomes much easier. You can just ask your database engine for the corresponding records. For example, in MySQL, you'd ask for the data something like this:
select * from tableA order by id limit 10 offset 20;
This would return id's 21 thru 30.
... and, would scale much better. Of course, if you've never done any work with databases, there is quite a learning curve.
If you want to end execution at a certain place, just call exit;
Try using the onload function on your < body >'s html, so it will load the page at once

Adding description tag to PHP image gallery

I am trying add a descriptive tag under each image but most of the code is in PHP and i am not to familiar with how to program it without screwing up the whole structure. Here is the website: http://suncoastdeck.com/index.php?page=portfolio&start=0
Here is the code for the portfolio page:
<div class="content-box">
<?
//total number of images
$total = 77;
//max number of thumbnails per page
$max = 9;
//what image do we want to start from?
$startcount = $_GET["start"];
//if there is not a defined starting image, we start with the first
if(empty($startcount))
{
$startcount = 0;
}
//start off the loop at 1
$loop = 1;
//start the loop
while($loop <= $max)
{
//for the picture labels
$num = $startcount + $loop;
if($num > $total)
{
$num = $num - 1;
break;
}
// Add class="last" to every third list item
if(is_int($num / 3))
{
$last = ' class="last"';
}
else
{
$last = "";
}
//the code for the image
echo '
<li'.$last.'><img src="images/portfolio/thumbs/pic-'.$num.'-thumb.jpg" width="256" height="138" alt="Thumbnail of image '.$num.'" /><div>'.$num.'</div></li>';
//add 1 to the loop
$loop++;
}
echo '</ul>';
//Calculate the number of pages
$total_pages = $total / $max;
//clean it up
if(!is_int($total_pages))
{
$total_pages = floor($total_pages) + 1;
}
//start the page count at 1
$ploop = 1;
echo '<hr /><div id="portfolio-wrap"><div id="pages">Page: ';
while($ploop <= $total_pages)
{
$offset = ($ploop * $max) - $max;
if($startcount == $offset)
{
echo '<span>'.$ploop.'</span>';
}
else
{
echo ''.$ploop.'';
}
$ploop++;
}
echo '</div>';
echo '<div id="portfolio-foot-left"><p>Displaying Images <strong>'.($startcount + 1).' - '.$num.'</strong> of <strong>'.$total.'</strong></p></div></div>';
?>
Pretty much what i want is to make section drop down a bit more where i can add in additional info about the pic. Any suggestions?
You need a database or else you can store your descriptions in a text file next to the image. What have you tried so far?
Basically you need to create a form that accepts the image name and caption, take the caption and write it to a file or database. Then when displaying the caption, you just add a <div> that reads from file with file_get_contents(). Why don't you copy the script to another directory and start experimenting? People probably won't write the whole thing for you ;)

Categories