How to generate table of contents using dompdf? - php

I am using the dompdf library of php to generate PDF report from an HTML template. In that html template there is a section table of contents. When genrating PDF i need to update the page number of table of contents. Does anyone know how I can achieve this in dompdf library of php?
Thanks in advance.

I have achieved this in Drupal and guess it works on other php opensource and frameworks as well.
I have kept this code inside script tag
$GLOBALS['entity_page'][] = $pdf->get_page_number();
in template that stores the page number. Template is with extension tpl.php
Now in the module
after other codes for export I have added......
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "normal");
$canvas->page_text(520, 805, "Page {PAGE_NUM}", $font, 9, array(0.4, 0.4, 0.4));
foreach ($GLOBALS['entity_page'] as $key => $val) {
$GLOBALS["entity_val"] = 0;
$GLOBALS["entity_y"] = 110;
$canvas->page_script('if($PAGE_NUM == 3 && $PAGE_NUM < 4){
$font = Font_Metrics::get_font("helvetica", "normal");
$x = 380;
$y = $GLOBALS["entity_y"];
$pdf->text($x, $y, "-------------------------".$GLOBALS["entity_page"][$GLOBALS["entity_val"]]."", $font, 12, array(0, 0, 0, 0.8));
$GLOBALS["entity_y"] = $GLOBALS["entity_y"] + 33;
$GLOBALS["entity_val"] = $GLOBALS["entity_val"] + 1;
}');
}
$pdf->text this part adds the page numbers with constant increment in y axis position. Other global variables entity_y and entity_val are used to store the values.

Generating a Table of Contents from HTML (with h1,h2,h3), I did the following:
First give every header an unique ID (because we are using PrinceXML) and is a good pratice.
Then create an OL/LI structure of it, although that piece of code can contain bugs.
$matches = null;
$smatches = null;
$had_headers = array();
preg_match_all('/<h[0-9].*?>.*?<\/h[0-9]>/i', $content, $matches);
if (!empty($matches[0]) && count($matches[0]) > 0)
foreach ($matches[0] as $headertag) {
preg_match('/>(.*?)<\/(h[0-9])>/i', $headertag, $smatches);
if (!empty($smatches[1]) && count($smatches[1]) > 0) {
$headerid = strip_tags($headertag);
$headerid = trim(strtolower(preg_replace('/[^a-z0-9]/i', '', $headerid)));
$smatches[2] = strtolower($smatches[2]);
$header_depth = intval(trim(str_ireplace('h', '', $smatches[2])));
while (in_array($headerid, $had_headers)) {
$headerid .= '1';
}
$had_headers[] = $headerid;
$content = str_replace($headertag, '<'. $smatches[2] . ' id="' . htmlentities($headerid) . '">' . $smatches[1] . '</' . $smatches[2] . '>', $content);
}
}
$matches = null;
$smatches = null;
$toc_html = '<ol id="toc">' . "\n";
$old_depth = 0;
$hadfirst = false;
preg_match_all('/<h[0-9].*?>.*?<\/h[0-9]>/i', $content, $matches);
if (!empty($matches[0]) && count($matches[0]) > 0)
for ($i=0; $i < count($matches[0]); $i++) {
$headertag = $matches[0][$i];
preg_match('/<h[0-9][^>]*?id="(.*?)".*?>(.*?)<\/(h[0-9])>/i', $headertag, $smatches);
if (!empty($smatches[1]) && count($smatches[1]) > 0) {
$headerid = trim($smatches[1]);
$header_depth = intval(trim(str_ireplace('h', '', $smatches[3]))) - 1;
// don't take heigher than h3 in TOC
if ($header_depth > 2)
continue;
if ($header_depth < $old_depth) {
$diff = $old_depth - $header_depth; //if going multiple levels up
$toc_html .= '</li>'.str_repeat('</ol></li>', $diff);
} elseif ($header_depth > $old_depth) {
$toc_html .= '<ol>';
} else {
$toc_html .= ($hadfirst) ? '</li>' : null;
}
$toc_html .= '<li>' . htmlentities(trim(strip_tags($smatches[2]))) . '';
$old_depth = $header_depth;
$hadfirst = true;
}
}
$toc_html .= str_repeat('</li></ol>', ($old_depth + 1));

You may have solved this already? I've not used dompdf, but i did a similar thing in Zend_Pdf: I made a blank page for the table of contents and then went on creating all the other later pages, keeping an array of page_number => title. At the end I went back and updated the contents page using the reference saved earlier...

As an extension to vicky shrestha's answer here is what I have for a table of contents that expands more than a single page.
36 is just an arbitrary number of items that fit in the design.
foreach ($GLOBALS['entity_page'] as $key => $val) {
$GLOBALS["entity_y"] = 88;
$GLOBALS["entity_val"] = 0;
$GLOBALS["entity_per_page"] = 36;
if($val) {
$canvas->page_script('
if(isset($GLOBALS["entity_page"][$GLOBALS["entity_val"]])) {
if($PAGE_NUM == $GLOBALS["entity_page_number"]){
$x = 505;
$y = $GLOBALS["entity_y"];
$font = $fontMetrics->get_font("Open Sans", "Helvetica Neue", "Helvetica, Arial, sans-serif");
$pdf->text($x, $y, $GLOBALS["entity_page"][$GLOBALS["entity_val"]]."", $font, 7, array(0, 0, 0, 1));
$GLOBALS["entity_y"] = $GLOBALS["entity_y"] + 19;
$GLOBALS["entity_val"] = $GLOBALS["entity_val"] + 1;
if (($GLOBALS["entity_val"] + 1) % $GLOBALS["entity_per_page"] == 0 ) {
$GLOBALS["entity_page_number"] = $GLOBALS["entity_page_number"] + 1;
$GLOBALS["entity_y"] = 31;
}
}
}');
}
}
the isset is important as for some reason the foreach will loop an additional time and you will get an out of bounds exception thrown at the end.

My idea to create TOC in pdf is following:
generate pdf where title of page would contain random token instead of name
parse generated pdf (using Smalot\PdfParser) and find page number which contains the token
generate the pdf where replace tokens with real name and found page number.
Example:
$html = "<html>
<div class='toc'>
<a>Article1 ..... {article_1_num}</a>
</div>
...
<div class='article'>
<div>{article_1_title}</div>
<div>Article content</div>
</div>
</html>";
//prepare variables to replace in template with random token
$vars = ["{article_1_title}"=>'676TGZGHVGFTRR655R66TTFTF', "{article_1_num}"=>0];
//genetate pdf
$options = new Options();
$options->set('defaultFont', 'Courier');
$options->set('isRemoteEnabled', TRUE);
$options->set('debugKeepTemp', TRUE);
$options->set('isPhpEnabled', TRUE);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
//load html with variables replaced
$dompdf->loadHtml(strtr($html, $vars));
$dompdf->setPaper('A4');
#$dompdf->render();
//create tamporary file
$temp = tempnam(sys_get_temp_dir(), 'prefix');
$output = $dompdf->output();
//save to temporary file
file_put_contents($temp, $output);
// parse pdf
$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile($temp);
$pages = $pdf->getPages();
$pageNum = 0;
//loop the pages and find the one with the token
foreach ($pages as $k=>$page) {
if(strpos($page,'676TGZGHVGFTRR655R66TTFTF') !== false){
$pageNum = $k+1;
break;
}
}
// remove temp file
unlink($temp);
//prepare variables with real values to replace in template
$vars = ["{article_1_title}"=>'Article no. 1', "{article_1_num}"=>$pageNum];
// generate pdf and stream it to user
$options = new Options();
$options->set('defaultFont', 'Courier');
$options->set('isRemoteEnabled', TRUE);
$options->set('debugKeepTemp', TRUE);
$options->set('isPhpEnabled', TRUE);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
//load html with variables replaced
$dompdf->loadHtml(strtr($html, $vars));
$dompdf->setPaper('A4');
#$dompdf->render();
$dompdf->stream("pdf.pdf", array('Attachment' => 0));

Related

PHP file unable to extract and split image from database after made changes to the file

I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.

Generating pdf from XML response taking so much time

I have xml in my database and wanted to generate pdf from xml, but if xml is too big then it through timeout error. I don't want to change my server timeout instead of how to improve the timing of pdf generate.
I am using <pre> tag for good formatting.
Below code for pdf generate
public function generateCreditReport($form, $path=false, $htmlPath=false){
$this->load->library('fpdf/fpdf');
$this->load->library('fpdi/fpdi');
if(!empty($path) && !file_exists($path)){
$data['form'] = $form;
$data['date'] = $data['xml'] = null;
if($data['form']->credit_report != ''){
try{
$data['xml'] = new SimpleXMLElement($data['form']->credit_report);
}catch(Exception $e){
}
$timeStatus = $this->admin->get_timestamp($data['form']->id, 'credit_pulled');
if(!empty($timeStatus)) {
$data['date'] = $timeStatus->date;
}
}
$pdf = new TCPDF();
$pdf->SetFont('Helvetica');
$pdf->SetFontSize(10);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetProtection(array('print','modify'),"$form->loan_id","sefinance",0);
$pdf->AddPage();
$html = $this->load->view('admin/credit_report_pdf', $data,true);
$generatedReport = file_put_contents($htmlPath, $html , FILE_APPEND | LOCK_EX);
$pdf->WriteHTML($html);
if($path){
$pdf->Output($path, "F");
}else{
$pdf->Output();
}
}
}
View file credit_report_pdf is as below
<h4>Report Results</h4>
<br>
<?php if(!empty($xml)){ ?>
<?php echo print_credit($xml->EfxReport->USPrintImage); ?>
<?php } ?>
I am formatting using <pre> to look good.
function print_credit($report) {
$split = " <div style='page-break-before: always;'></div>" . repeater(' ', 43);
$report = preg_replace('/\* \* \*[\s\S]+?USER REF./', $split, $report);
$output = "";
$output = '<pre>';
$length = strlen($report);
$count = $length / 81;
$position = 1;
for ($i = 0; $i < $count; $i++) {
if (strpos(substr($report, $position, 80), 'THIS FORM PRODUCED BY EQUIFAX') === FALSE) {
$output .= substr($report, $position, 80) . '<br>';
}
if ($i == 32) {
$output .= '</pre><pre>';
}
$position += 81;
}
$output .= '</pre>';
return $output;
}
Here is screenshot how pdf looks like.
Please help me to improve the timing of pdf, currently taking more than 10min for 10-page pdf.

Stuck with file_get_contents

guys. Please help me to find out the problem. I have one script on my ftvgirlsbay.com site:
<?php
define('C', 16); // NUMBER OF ROWS
define('D', 6); // NUMBER OF CELLS
$file = #file_get_contents('http://ftvgirlsbay.com/design/tables/gals.txt');
if($file === FALSE) {
echo "<h2>Make file gals.txt with data!</h2>";
return FALSE;
}
$file = explode("\r\n", $file);
$thumbs = array();
while(list(,$el) = each($file)) {
$el = explode('|', $el);
if(isset($el[0]) && isset($el[1]))
$thumbs[] = array($el[0], $el[1]);
}
//print_r($thumbs);
$size = sizeof($thumbs);
if($size < C*D) {
echo "<h2>More data needed. You have $size, you need ".C*D."!</h2>";
return FALSE;
}
$range = range(0, $size - 1);
shuffle($range);
//print_r($range);
?>
<table align=center>
<?php
$num = 0;
for($i = 0; $i < C; $i++) {
echo '<tr align=center>'."\r\n";
for($k = 0; $k < D; $k++) {
echo '<td>FTV '.$thumbs[$range[$num]][0].' Gallery </td>'."\r\n";
$num++;
}
echo '</tr>'."\r\n";
}
?>
</table>
Result of this script:
"More data needed. You have 1, you need 96!"
( http://ftvgirlsbay.com/random_scripts/test.php )
If this part
$file = #file_get_contents('http://ftvgirlsbay.com/design/tables/gals.txt');
change to
$file = #file_get_contents('http://sexsticker.info/ftvgirlsbay.com/pictable/gals.txt');
it works just fine
( http://ftvgirlsbay.com/random_scripts/test2.php )
So if I links to the .txt file on my server's side script reads only 1 line.
If I links to the .txt on the remote server - script works wilh all lines
I figured out your problem and was able to replicate the issue.
The issue is with the \r in
$file = explode("\r\n", $file);
Remove the \r
$file = explode("\n", $file);
Both servers might be different. One may be on a Linux, while the other on a Windows server.

Read contents of directory, output results randomly with HTML tag title php (working but not title)

So far my script is working fine, basically it gets all htm files, out puts results, however im using DOM to get the HTML title tag from each file, that's where im not get to get it in the random array.. (image basenames and htm basename files are the same (firstresult.htm has picture firstresult.jpg)
I hope the code I provide and answer will be useful
<?php
// loop through the images
$count = 0;
$filenamenoext = array();
foreach (glob("/mydirectory/*.htm") as $filename) {
$filenamenoext[$count] = basename($filename, ".htm");
$count++;
}
for ($i = 0; $i < 10; $i++) {
$random = mt_rand(1, $count - 1);
$cachefile = "$filename";
$contents = file($cachefile);
$string = implode($contents);
$doc = new DOMDocument();
#$doc->loadHTML($string);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
echo '<img class="image" src="'.$filenamenoext[$random].'.jpg" " />"'.$title.'"<BR><BR>';
}
?>
It looks like the $filename variable you use on the line $cachefile = "$filename"; hasn't been set. It's only defined in the foreach loop's scope.
You should change it to
$cachefile = $filenamenoext[$random] . '.htm';
Also, it's a better practice to use array_push() and count() functions, instead of using a counter and manually filling the array. At least the code is better looking and more readable.
<?php
// loop through the images
$count = 0;
$filenamenoext = array();
foreach (glob("/mydirectory/*.htm") as $filename) {
array_push($filenamenoext, basename($filename, ".htm"));
}
for ($i = 0; $i < 10; $i++) {
$random = mt_rand(1, count($filenamenoext) - 1);
$cachefile = $filenamenoext[$random] . '.htm';
$contents = file($cachefile);
$string = implode($contents);
$doc = new DOMDocument();
#$doc->loadHTML($string);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
echo '<img class="image" src="' . $filenamenoext[$random] . '.jpg" " />"' . $title . '"<BR><BR>';
}
?>

php script to show 4 random photos from a folder is showing the same photo 4 times

i'm trying to build a little module for a site that pulls 4 random photos from a folder on the server and presents them in a div. what's happening is the same 4 photos are being called. how do i get it to call 4 different photos?
heres the random.php file:
<?php
$folder = '.';
$extList = array();
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$img = null;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = #imagecreate (100, 100)
or die ("Can't initialize image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
here's how random.php is being called:
<?php
/* DATA */
$data = array(
array('COUNT', '88', 'Here are a few of them', '1, 2, 3, 4'),
);
?>
<div>
<table class="reop" border='0' width='100%' cellpadding='0' cellspacing='10'>
<?php
$count = 0;
foreach($data as $row) {
$class = ($count % 2 == 1 ? " class='alt'" : '');
echo "<tr$class>";
for($j = 0; $j < count($row); $j++) {
if ($j!=3) {
echo "<td class='cell_$j'>$row[$j]</td>";
} else {
// $avatar = '';
$array = preg_split('/,/', $row[$j], -1, PREG_SPLIT_NO_EMPTY);
foreach ($array as $val) {
$avatar .= '<img src="/staffpics/random.php"> ';
}
echo "<td class='cell_$j'>$avatar</td>";
}
}
echo '</tr>';
// $count++;
}
?>
</table>
when your page is displayed, most browsers will immediately request the four pictures.. nearly all at the same time. your code for "random" picking a picture is based on time() which returns a count of seconds since the begin of unixtime. executed 4 times within the same second it will also yield the same result 4 times.
your code:
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
should be rewritten as:
// filelist starts with "0", count with "1" .. so we are off-by-one and first picture would never show without -1
$imageNumber = rand() % (count($fileList) - 1);
$img = $folder.$fileList[$imageNumber];
that way you will get "random" pictures.
Also, what Mister Lister commented is totally valid - your browser may also cache the picture and thus only request a picutre once and just display that one again and again using its cache.
to avoid this, replace any <img src="random.php"> with <img src="random.php?rand=<?= rand(); ?>">
But note:
your server may eventually return the same random number multiple times so eventually (rarely) you will end up with the same picture twice on the same page.
to fix that, you must completely rewrite your code.
the script rendering the page should decide which pictures to choose and ensure that no picture is displayed twice instead of just including a "give random picture" script, which is independent of the page rendered.
much easier, you could try this:
// find all images - case SenSItivE
$all_images = glob("/path/to/images/*.{jpeg|jpg|png|gif}", GLOB_BRACE);
// bring array in random order
shuffle($all_images);
// pick four random images - you may also use a for or foreach loop to iterate the array
list ($img1, $img2, $img3, $img4) = $all_images;
// write code to display four images here
Here is another way of fetching 4 random photos:
//randomize order
shuffle($fileList);
//get first 4 values of array
$randomPhotos = array_slice($fileList, 0, 4);
Please note, shuffle would change value order in your original array.
Call srand to seed your random number generator.

Categories