Displaying Images from a folder using PHP - php

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";
}

Related

Get all images in a directory except retina

I have a php script which grabs all of the images in a set directory. The script works without fault. My issue is that I want it to only get none retina images. All of the retina images are named in the format 'image1#2x.jpg' whereas all of the regular images are named in the format 'image1.jpg'. With this in mind I want my script to discount any image that contains '#2x' in it's name.
My script is:
<?php
$directory = 'images/';
$dh = opendir($directory);
while (false !== ($filename = readdir($dh)))
{
$files[] = $filename;
};
$images = preg_grep ('/(\.gif|\.GIF|\.jpg|\.jpeg|\.JPG|\.JPEG|\.png|\.PNG)$/i', $files);
foreach ($images as $image)
{
echo '<img src="'.$directory.$image.'" alt="">';
}
?>
The problem is I don't have the vocabulary to know what to search for in Google so if anyone could point me in the right direction I would appreciate it.
Thanks
I would use stripos put this conditional in your foreach loop
if(stripos($image,'#2x') === false){
echo '<img src="'.$directory.$image.'" alt="">';
}
You can make your script a little shorter by using:
$directory = 'images/';
$allImages = glob($directory.'*.{jpg,JPG,jpeg,JPEG,gif,GIF,png,PNG}', GLOB_BRACE);
$nonRetinaImages = preg_grep('/#2x/i', $allImages, PREG_GREP_INVERT);
foreach ($nonRetinaImages as $image)
{
echo '<img src="'.$image.'" alt="">';
}

Images not loading when path is correct PHP, Wordpress

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().

php function not extracting all images from directory

my code is not extracting all of the files inside the directory and i donde know why, i dont have any extension restrictions or anything, ok so this is my code what am i doing wrong? there are 24 images with jpg and png extensions and only 13 are detected when i print_r($arr)
:
<?php
function loadimages($dir) {
if(substr($dir, -1) != "/") $dir .= "/";
$rootdir = $_SERVER["DOCUMENT_ROOT"];
$fulldir = $rootdir."/".$dir;
$dir = opendir($fulldir);
$arr = array();
while(readdir($dir)) {
$arr[] = readdir($dir);
}
echo "<h1>".count($arr). "</h1><br />";
foreach($arr as $img) {
echo "<img src='/pages/course-images/{$img}' />";
}
}
loadimages("pages/course-images");
?>
I would use glob() instead.
$images = glob('*.{png,jpg}', GLOB_BRACE);
print_r($images);
http://php.net/manual/en/function.glob.php
It doesn't work because while(readdir($dir)), then you read one value and skips one step forward to the next file. The correct way would be this, and it's explaind in the manual.
while(false !== ($entry = readdir($dir))) {
$arr[] = $entry;
}
http://php.net/manual/en/function.readdir.php
But glob is better, now it only returns images.

Paginate files in a directory

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

Display contents of multiple text files

I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}

Categories