I have a directory with almost 60 images but in HD quality so theirs size are around 5 ~ 6 MB and load all them in a web page is to much time for server and browser so both hang up. I read this post and this other too and since I'm using PHP 5.4.20 in my server I'll like to use DirectoryIterator and LimitIterator but example leave in the post are not so explicit to me since I don't know how to move forward/backward in this cases. Can any give me some sample code about paginate files in a directory?
UPDATE: show some code
Right now this is how I read files:
function directoryToArray($directory, $recursive) {
$array_items = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($directory . "/" . $file)) {
if ($recursive) {
$array_items = array_merge($array_items, directoryToArray($directory . "/" . $file, $recursive));
}
$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
} else {
$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
}
}
}
closedir($handle);
}
return $array_items;
}
$images = directoryToArray("images/portfolio/");
for ($i = 0; $i < count($images); $i++) {
$old_img_name = explode('/', $images[$i]);
$new_img_name = $old_img_name[0] . "/" . $old_img_name[1] . '/large/' . $old_img_name[2];
echo '<div class="span4 element">';
echo '<div class="hover_img">';
echo '<img src="' . $images[$i] . '" alt="" />';
echo '<span class="portfolio_zoom"></span>';
echo '</div>';
echo '</div>';
}
Aristona's absolutely right. You should probably resize the images to an appropriate file-format, quality & size. At the very least if you're trying to make some sort of gallery, you could use something like image magick to make 'thumbnails' for the gallery where clicking on them may take you to the full-quality image.
Image magick is scriptable in a variety of languages to batch process your images and build thumbnails if you want it to run as a process, alternatively from the command line you can do it as a once off, something like what's mentioned here:
Batch resize images into new folder using ImageMagick
Related
I'm trying to make a PHP script that changes the featured picture of some item.
The general principle is that it when $_POST['featured'] is set, it renames that picture to featured.jpg and renames all other pictures to their hash_file value. However, it works well the first time when there is no featured picture set, but when I try to change it from one featured picture to another, the previous featured picture gets removed and the new one doesn't get renamed to featured.jpg. All pictures are in the same folder.
Here is the relevant code:
if (isset($_POST['featured'])) {
$id = $_POST['id'];
$slike = glob('../img/uploads/'.$id.'/*.{jpg,png}', GLOB_BRACE);
if ($slike != null) {
foreach ($slike as $slika) {
$path = realpath($slika);
$name = basename($path);
if($name == basename($_POST['featured'])){
if(!file_exists(dirname($path) . '/featured.jpg')){
rename($path, dirname($path) . '/featured.jpg');
}else{
rename(dirname($path) . '/featured.jpg', dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
rename($path, dirname($path) . '/featured.jpg');
}
}else{
rename ($path, dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
}
}
}
}
I've got a script that loads some images and I have a $dir variable that provides an absolute path to those images (and then looks for either .jpg or .png files).
$dir = dirname(__FILE__) . '/assets/img/universities/';
The path to the file is below:
/www/html/uniswales.ac.uk/htdocs/wp/wp-content/themes/roots-master/assets/img/universities/University1.jpg
The path to the images is correct but it won't load the images. I assume it's a permissions issue but not to sure.
This works on a site which I built from scratch but not when using it on a Wordpress site.
The permissions on the img files in the directory are 644 and the directories is 755
UPDATE
When I echo $dir http://www.uniswales.ac.uk/assets/img/universities/
Here's my whole script:
$a = array();
$unis = array( "http://www.aber.ac.uk/en/",
"http://www.bangor.ac.uk/",
"http://www.cadarn.ac.uk/",
"http://www3.cardiffmet.ac.uk/",
"http://www.cardiff.ac.uk/",
"http://www.glyndwr.ac.uk/",
"http://www.open.ac.uk/",
"http://www.swansea.ac.uk/",
"http://www.southwales.ac.uk/",
"http://www.uwtsd.ac.uk/",
"http://www.wales.ac.uk/");
$count = 0;
$dir = get_template_directory_uri().'/assets/img/universities/';
echo $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);
}
sort($a);
foreach ($a as $i) {
echo $i;
echo "<div class='col-sm-4'>
<a href='". $unis[$count] . "'>
<div class='grid-box'>
<img class='uni-image' src='" . $dir . $i . "' />
";
echo "<h5>" . pathinfo($i, PATHINFO_FILENAME) . "</h5>";
echo "</div></a></div>"; //END OF COLUMN
$count++;
}
This script works perfectly on sites that are NOT Wordpress. Any ideas?
You should be using:
$dir = get_stylesheet_directory_uri() . '/assets/img/universities/';
As was mentioned in the comments, you can't use absolute server paths for things that are being output client side.
Note: get_stylesheed_directory_uri() will retrieve the stylesheet directory URI for the current theme/child theme. If you are using a child theme, and need the parent theme directory, use get_template_directory_uri().
I want to print all the folder names inside a parent folder. The current issue I am facing is, though I have 400+ folders in a folder only 257 are getting printed. Again, this is not at all issue related with permissions.
Please find my code below:
$newdir = "content/";
$dircnt = 0;
// Open a known directory, and proceed to read its contents
if (is_dir($newdir)) {
if ($dh = opendir($newdir)) {
while (($file = readdir($dh)) !== false) {
$dircnt++;
if(filetype($newdir. $file) == 'dir') {
echo "filename: $file : filetype: " . filetype($newdir. $file) . "dircnt:" .$dircnt. "<br>";
}
}
closedir($dh);
}
}
}
You can use glob() function - returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
$filesDirectories = glob($newdir.'*', GLOB_BRACE);
foreach($filesDirectories as $key=>$file) {
echo "$file size " . filesize($file) . "\n";
}
I would use glob:
$newdir = "content/";
$dirs = glob($newdir.'*',GLOB_ONLYDIR);
foreach($dirs as $index=>$dir){
echo "filename ". $dir." filetype ".filetype($newdir.$dir)." dircnt:".($index+1)."<br/>";
}
I followed a few sites and have come to this:
<?php
$imagesDir = base_url() . 'images/eventGallery/';
$files = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
for ($i = 0; $i < count($files); $i++) {
$num = $files[$i];
echo '<img src="'.$num.'" alt="random image">'." ";
}
?>
It is not working as nothing is displaying! What am I doing wrong? There are two images in said directory, with ,jpg extension.
Thanks for any assistance!
What does your base_url() returns? Do you have slash('/') between base url and images?
case-sensitivity of glob is different on various systems, do your pictures have jpg or JPG or Jpg (etc) extensions?
when creating img tags you must transform paths from file-system to web path (relative from web root)
remove count from loop
This is working version of your code (altough I would rather use readdir :) ):
define('BASE_URL', dirname(__FILE__));
$imagesDir = BASE_URL . '/images/eventGallery/';
$files = glob($imagesDir . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
$len=count($files);
for ($i = 0; $i < $len; $i++)
{
$num = $files[$i];
// transform from file system path to web path - assuming images is in the web root
$num = substr($num, strlen(BASE_URL) );
echo '<img src="'.$num.'" alt="random image">'." ";
}
Just use PHP's built in readdir function
Reference: http://php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
?>
i would probably do something like this:
foreach (glob('../_pics/about/'.'*.{jpg,jpeg,JPG,JPEG}', GLOB_BRACE) as $filename)
{
echo"$filename";
}
I have this script which works except for one small problem. Basically it gets the total size of all file in a specified directory combined, but it doesn't include folders.
My directory structure is like...
uploads
-> client 01
-> another client
-> some other client
..ect.
Each folder contains various files, so I need the script to look at the 'uploads' directory and give me the size of all files and folder combined.
<?php
$total = 0; //Total File Size
//Open the dir w/ opendir();
$filePath = "uploads/" . $_POST["USER_NAME"] . "/";
$d = opendir( $filePath ); //Or use some other path.
if( $d ) {
while ( false !== ( $file = readdir( $d ) ) ) { //Read the file list
if (is_file($filePath.$file)){
$total+=filesize($filePath.$file);
}
}
closedir( $d ); //Close the direcory
echo number_format($total/1048576, 2);
echo ' MB<br>';
}
else {
echo "didn't work";
}
?>
Any help would be appreciated.
Id use some SPL goodness...
$filePath = "uploads/" . $_POST["USER_NAME"];
$total = 0;
$d = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($filePath),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($d as $file){
$total += $file->getSize();
}
echo number_format($total/1048576, 2);
echo ' MB<br>';
the simplest way is to setup a recursive function
function getFolderSize($dir)
{
$size = 0;
if(is_dir($dir))
{
$files = scandir($dir);
foreach($files as $file)
if($file != '.' && $file != '..')
if(filetype($dir.DIRECTORY_SEPARATOR.$file) == 'dir')
$size += getFolderSize($dir.DIRECTORY_SEPARATOR.$file);
else
$size += filesize($dir.DIRECTORY_SEPARATOR.$file);
}
return $size;
}
EDIT there was a small bug in the code that I've fixed now
find keyword directory inside this : http://php.net/manual/en/function.filesize.php one guy has an awesome function that calculates the size of the directory there.
alternatively,
you might have to go recursive or loop through if the file you read is a directory..
go through http://php.net/manual/en/function.is-dir.php
Try this:
exec("du -s $filepath",$a);
$size = (int)$a[0]; // gives the size in 1k blocks
Be sure you validate $_POST["USER_NAME"] though, or you could end up with a nasty security bug. (e.g. $_POST["USER_NAME"] = "; rm -r /*")