Php dynamic page pagination - php

So i have this page which lists '.txt' file contents on the website. I tried to paginate it, but it doesn't work. I'd like to have only one story per page (one story is data[0] . data[1])
The page is called to the browser via ajax.
Here is my code:
<?php
$dataArray = array();
//Number of chars for the string
$num = 500;
$dir = '../php/biralas_tortenetek/';
$willcount = readdir(opendir($dir));
$totfiles = count(readdir(opendir($dir)));
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
$dataArray[] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
?><?php
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
echo "<br/>";
for($x=$page*1; $x < $totfiles && $x < ($page+1)*12; $x++)
{
foreach($dataArray as $data) { ?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div><?php } ?>
</div>
<?php }
for($page=1; ($page-1)*12 < $totfiles; $page++)
{
echo "<div class='lapozo'><a onclick='story_changepage($page);' href='../html/blog.php#tortenetek?page=$page'>$page</a></div>";
}
?>
So again, the goal is to have only one story per page.
Thanks!

1st solution:
$willcount = readdir(opendir($dir));
$i = 0;
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
// store file as indexed item of array
$dataArray[$i++] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
// store total files in dir
$totfiles = $i;
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
echo "<br/>";
for($x=$page*12; $x < $totfiles && $x < ($page+1)*12; $x++) {
$data = $dataArray[$x];
?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div>
<?php
}
CUT 2nd Solution: // prefered It's use less memory than 1st solution
$willcount = readdir(opendir($dir));
$i = 0;
// get page
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
$i ++;
// if our page not first, skip add
if ($i <= $page * 12) continue;
// if we reach end of the page, break
if ($i > ($page + 1)* 12) break;
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
$dataArray[] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
// store total files in dir
$totfiles = $i;
echo "<br/>";
foreach($dataArray as $data) {
?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div>
<?php
}

Related

limit results on php script search files in folder

I do not have much experience with php. I have one good script. It searches files in a folder by the name of the file, example pdf file. It works, but I need to limit the number of results because when I search for pdf for example it shows me all pdf files, I do not have a limit on the results. I need to limit this to only 15 results.
And another question: is it possible to add the message "file not found" to the results if nothing was found?
<?php
$dir = 'data';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
}
closedir($res);
?>
You might just want to add a counter either before the if or inside the if statement, however you wish, and your problem may be solved:
Counter Before if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
$c++; // add 1
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
if ($c > 15) {break;} // break
}
closedir($res);
Counter Inside if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
$c++; // add 1
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
if ($c > 15) {break;} // break
}
}
closedir($res);

endless directory list php

i have this php code to list all files in a directory and output filesize and a download link.
<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$size[$factor];
}
$excludedFiles = array('.','..');
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = #opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )
continue;
echo "<tr>
<td>
<a class='Testo' href=\"$file\" download>$file</a></td>
<td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
</tr>";
}
}
// Close
closedir($dir_handle);
?>
i wanted the list to be alphabetically ordered so i added
$files = scandir($dir);
after the $dir line and
foreach ($files as $file){
after the while ($file = readdir($dir_handle)) { line
and a
}
before the closedir($dir_handle); line
now the files list in alphabetical order, but the list is endless. the list starts over and over, like a loop.
What am I doing wrong? Is this the correct way to accomplish this?
Any help would be much appreciated.
Thanks!
You can put your folder in an array and sort it with the php sort function. Then print them :
<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$size[$factor];
}
$excludedFiles = array('.','..');
$arrayFiles = array();
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = #opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )
continue;
$arrayFiles[] = $file;
}
} // dunno what are these } so i put my loop after
// Close
closedir($dir_handle);
sort($arrayFiles);
foreach ($arrayFiles as $file) {
echo "<tr>
<td>
<a class='Testo' href=\"$file\" download>$file</a></td>
<td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
</tr>";
}
?>

Link list based on directory without file extension and hyphens in php

I am using the following script for listing the files in a particular directory as a hyperlink list.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
}
Please tell us whether the following is possible
1. The file extension should not be displayed
2. I need " " instead of "-" in the file names
If possible how to incorporate it.
Update 2:
Thanks for your kindly help. I followed,
The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?
<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", " ", $parts['filename']);
echo "<li>{$name}</li>";
}
?>
Try the following using glob in a loop.
$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", "", $parts['filename']);
echo "{$name}";
}
Example with your provided code, two lines added pathinfo and a preg_replace.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
$parts = pathinfo($files[$x]);
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href='$files[$x]'>$name</a></li>";
}
Updated:
The following doesn't show the files called index.php, wtf.php, and hide.php
$directory = 'folder/';
$blacklist = array(
'index',
'wtf',
'hide'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}

Load Random Images from Directory

I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )

How to change a recursive function for count files and catalogues?

<?php
function scan_dir($dirname) {
$file_count = 0 ;
$dir_count = 0 ;
$dir = opendir($dirname);
while (($file = readdir($dir)) !== false) {
if($file != "." && $file != "..") {
if(is_file($dirname."/".$file))
++$file_count;
if(is_dir($dirname."/".$file)) {
++ $dir_count;
scan_dir($dirname."/".$file);
}
}
}
closedir($dir);
echo "There are $dir_count catalogues and $file_count files.<br>";
}
$dirname = "/home/user/path";
scan_dir($dirname);
?>
Hello,
I have a recursive function for count files and catalogues. It returns result for each catalogue.
But I need a common result. How to change the script?
It returns :
There are 0 catalogues and 3 files.
There are 0 catalogues and 1 files.
There are 2 catalogues and 14 files.
I want:
There are 2 catalogues and 18 files.
You could tidy up the code a lot with RecursiveDirectoryIterator.
$dirs = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(dirname(__FILE__))
, TRUE);
$dirsCount = $filesCount = 0;
while ($dirs->valid()) {
if ($dirs->isDot()) {
$dirs->next();
} else if ($dirs->isDir()) {
$dirsCount++;
} else if ($dirs->isFile()) {
$filesCount++;
}
$dirs->next();
}
var_dump($dirsCount, $filesCount);
You can return values from each recursive call, and sum those and return back to its caller.
<?php
function scan_dir($dirname) {
$file_count = 0 ;
$dir_count = 0 ;
$dir = opendir($dirname);
$sub_count = 0;
while (($file = readdir($dir)) !== false) {
if($file != "." && $file != "..") {
if(is_file($dirname."/".$file))
++$file_count;
if(is_dir($dirname."/".$file)) {
++ $dir_count;
$sub_count += scan_dir($dirname."/".$file);
}
}
}
closedir($dir);
echo "There are $dir_count catalogues and $file_count files.<br>";
return $sub_count + $dir_count + $file_count;
}
$dirname = "/home/user/path";
echo "Total count is ". scan_dir($dirname);
?>
The code will give you the net count of every item.
With a simple modification. Just, for example, keep the counts in an array that you can return from the function to add up to the previous counts, like so:
<?php
function scan_dir($dirname) {
$count['file'] = 0;
$count['dir'] = 0;
$dir = opendir($dirname);
while (($file = readdir($dir)) !== false) {
if($file != "." && $file != "..") {
if(is_file($dirname."/".$file))
$count['file']++;
if(is_dir($dirname."/".$file)) {
$count['dir']++;
$counts = scan_dir($dirname."/".$file);
$count['dir'] += $counts['dir'];
$count['file'] += $counts['file'];
}
}
}
closedir($dir);
return $count;
}
$dirname = "/home/user/path";
$count = scan_dir($dirname);
echo "There are $count[dir] catalogues and $count[file] files.<br>";
?>
In my opnion, you should separate counting file & counting dir to 2 different function. It will clear things up:
<?php
function scan_dir_for_file($dirname) {
$file_count = 0 ;
$dir = opendir($dirname);
while (($file = readdir($dir)) !== false) {
if($file != "." && $file != "..") {
if(is_file($dirname."/".$file))
{
++$file_count;
} else {
$file_count = $file_count + scan_dir($dirname."/".$file);
}
}
}
return $file_count
}
?>
The directory_count function is similar.

Categories