Get list of all image files in a directory - php

I am trying to generate some HTML code to list some images for a slide show.
I arrived at the following idea:
function galGetTopPhotos()
{
//path to directory to scan
$directory = SITE_ROOT_PATH."/gallery/best/";
//get all files
$images = glob($directory . "*.*");
//print each file name
$ret = "";
$ret .= '<div id="myslides">';
foreach($images as $image)
{
$ret .= '<img src="'.$image.'" />';
}
$ret .= '</div>';
return $ret;
}
The problem is that it only works when I use root path for $directory...if I use URL it will not work. And it causes the images to not load. Here is what this code generates:
<div id="myslides">
<img src="D:/xampp/htdocs/mrasti/gallery/best/1.jpg" />
<img src="D:/xampp/htdocs/mrasti/gallery/best/10.jpg" />
</div>
So the question is, how to get the list of files so it generates img sources in http://127.0.0.1/.... format?
What I mean if I use the code like this it returns no file!
$directory ="http://127.0.0.1/mrasti/gallery/best/";

This looks like a job for PHP function basename. This takes a file path and returns only the final element of the path - in this case the actual name of the jpeg image.
You could amend your code so that it looks something like this:
$urlPath = "http://127.0.0.1/mrasti/gallery/best/";
...
...
foreach($images as $image)
{
$relative_path = $urlPath.basename($image);
$ret .= '<img src="'.$relative_path.'" />';
}
The above takes the path and appends the filename "example.jpg" to your image directory url

glob does only work for local files and not on remote files. Have a look here:
http://php.net/manual/en/function.glob.php
For remote files have a look here:
http://www.php.net/manual/en/features.remote-files.php
But i do not think that you need remote files. It seems like you want to go through a local directory and display this images.
Try something like this
...
$ret .= '<img src="http://127.0.0.1/my/path/'.basename($image).'" />';
...

You need to have some functionality to translate the file path on disk to the correct URI so that your browser can understand it.
In your specific case as outlined and with the exact data given in your question, the following could work:
foreach($images as $image)
{
$src = '/mrasti/gallery/best/'.substr($image, strlen($directory));
$ret .= '<img src="'.$src.'" />';
}

Related

Get image from PHP displaying using an img src

The code I have should output a jpg from a list of files in a directory however it is not. I have trawled this site and tried different methods but not helped. I am a relative beginner at php so looking for any help at all.
I have tried using img src in the php code but I am trying to get the image to display within a Wordpress post so I cannot echo the img src within the script. I have tried file_get_contents and read file as well but it may be my lack of knowledge holding me back.
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);
define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );
If(LOCALHOST){
define('PATH_IMAGES', 'this_path');
}else{
define('PATH_IMAGES', '../../../Images/');
}
$arrnum = $GLOBALS[imagenum] - 1;
$dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
$images = scandir($dirname);
rsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
header('Content-type: image/jpeg');
file_get_contents('$dirname$images[$arrnum]');
}
}
?>
Have you tried readfile(...); should read and output the file. In your example you are not outputting the image data
http://php.net/manual/en/function.readfile.php

PHP loop with dyamic images from a folder list

I have a folder called loop-images which has a set of images. I also have the php loop below:
foreach ($feed as $feed_id => $feed_title){
echo '<img src="/loop-images/01.jpg" border="0"><br>';
echo ''.$feed_title.'';
}
In the loop I have a fixed image, However I am looking to use the image dynamically from the loop-images folder. So basically, on the first loop it should use the first image and so on. If it runs out of images in the loop then it starts from the first image again.
Any ideas how I can achieve this?
Thanks
Here is something which you can try
$directory = "/loop-images"; // path to loop images folder
$images = glob($directory . "*.jpg");
$imagescounter = 0; foreach ($feed as $feed_id => $feed_title){
if($imagescounter>count($images)){
$imagescounter = 0;
}
echo '<img src="/loop-images/'.$images[$imagescounter].'.jpg" border="0"><br>';
echo ''.$feed_title.'';
$imagescounter++;
}
Maybe what you're trying to accomplish is something like that.
Using the scandir function and a regex to match all images using preg_match php function
foreach(scandir('/path/to/loop-images/') as $key => $file) {
if (preg_match('/[\s\S]+\.(png|jpg|jpeg|tiff|gif|bmp)/iu', $file)) {
echo '<img src="loop-images/' . $file . '" border="0"><br>';
}
}

Pull all images from a URL folder and display in Boostrap HTML

I need to pull all images from a URL directory (they are not displayed...just sitting in a folder on a server that I do not have access to) and display them within a Bootstrap Image gallery.
http://www.electrictoolbox.com/extract-images-web-page-php/
<?php
require_once('./simple_html_dom.php');
require_once('./url_to_absolute.php');
$url = 'http://www.bbc.co.uk';
$html = file_get_html($url);
foreach($html->find('img') as $element) {
echo url_to_absolute($url, $element->src), "\n";
}
?>
The URL for the folder where all the images are stored is:
http://masterplan.imgix.net/Slimming_Book/
Is it possible for php to scan this URL directory and pull the images to another website that is being hosted on another server?
Bit late but I figured I'd answer this. The below PHP code loads all ".png" images from the directory and then echos the image tag. You would replace the plain html tag for the equivalent bootstrap one.
dirname = "media/images/cats/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}

PHP Extract only the Filename from UNC Path

I'm trying to create an Intranet page that looks up all pdf documents in a UNC path and the returns them in a list as hyperlinks that opens in a new window. I'm nearly there however the following code displays the FULL UNC path - My question how can I display only the Filename (preferably without the .pdf extension too). I've experimented with the basename function but can't seem to get the right result.
//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>$file</a><br>";
}
The links work fine it just the display text shows //myserver/adirectory/personnel/document.pdf rather than just document. Note the above code was taken from another example I found whilst researching. If there's a whole new better way then I'm open to suggestions.
echo basename($file);
http://php.net/basename
Modify your code like this:
<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>";
}
?>
You may try this, if basename() does not work for some reason:
$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
$filename = $file_a[count($file_a)-2];
else
$filename = end($file_a);

printing a UL from an array of images

I am trying to print a UL list of images ending with _th.jpg returned from a specific folder. All i get back is array()
<?php
require '../../config.php';
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);
$id = (int)$_GET['id'];
$q = $conn->query("SELECT * FROM cms_page WHERE id=$id");
$project = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
$imagesDir = 'public/images/portfolio/'.$project['slug'].'/';
$images = glob($imagesDir . '*_th.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo $imagesDir ;
print_r($images);
?>
<h1><?=htmlspecialchars($project['title'])?></h1>
<?php
if ($images < 1) {
echo '<div id="slider">';
echo '<ul>';
foreach($images as $key => $value) {
echo '<li><img src="public/images/portfolio/'.$project['title'].'/'.$value.'.jpg" width="160" height="96" /></li>';
}
echo '</ul>';
echo '</div>';
} else {
echo 'There are currently no images to display for tihis project.';
}
?>
Anyone got any ideas?
First of all : are you sure you are reading from the right directory ?
What I mean, is : does 'public/images/portfolio/'.$project['slug'].'/' really exist, and is accessible from your script, using this relative path, in this PHP script ?
(You can test that with is_dir, for instance)
As a precaution, when working with files and directories, I like using absolute paths, so I always know to which directory exactly I'm accessing.
For instance, something like this :
$imagesDir = '/var/www/public/images/portfolio/'.$project['slug'].'/';
If you do not know the absolute path to your directories, you can use dirname(__FILE__), to get the absolute path to the current PHP file -- and then, starting from that file, use a relative path ; for instance :
$imagesDir = dirname(__FILE__) . '/public/images/portfolio/'.$project['slug'].'/';
This way, you don't have to care about the current working directory : your path will always be the same, as it's not relative.
If that doesn't work, then first of all, make sure you are accessing the right directory.
<h1><?=htmlspecialchars($project['title'])?></h1>
Is <? a valid PHP opening tag?
Since your last block of PHP code isn't apparently executed (since it would either print an empty ul or the text from the else block) I suspect the PHP doesn't get parsed correctly.

Categories