How can i display all images from an ftp server in website using php?
It should also sort automatically so i could just add more images to the ftp server and it would work.
I'm trying to make a gallery type thing
I've already looked through google and found nothing that worked.
I'm still learning php and dont know too much about it.
Any help would be much appreciated. Thanks!
As already commented, scandir does the trick. The below code gets all the images and output them as <img> elements.
index.php:
// Here enter the base url of the images folder
$base_images_url = "http://example.com/images/";
$dir = dirname (__FILE__) . "/images/";
// Get the files in the folder. Sort in ascending order - this is the default
$images = scandir($dir);
// Or is you need to sort in descending order
//$images = scandir($dir,1);
// Output an img tag for every image.
foreach($images as $image){
// skip the . and .. that starts the folder listing
if($image === '.' || $image === '..'){
continue;
}
$image_url = $base_images_url . $image;
echo '<img src="' . $image_url . '">';
}
This works with the following folder setup:
-index.php
-images
-image1.png
-anotherimage.jpg
Related
I have used a function
/*
Random File Function
Written By: Qassim Hassan
Website: wp-time.com
Twitter: #QQQHZ
*/
function Qassim_Random_File($folder_path = null){
if( !empty($folder_path) ){ // if the folder path is not empty
$files_array = scandir($folder_path);
$count = count($files_array);
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = $folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
else{
return "The folder is empty!";
}
}
else{
return "Please enter folder path!";
}
}
?>
to pull a random image from a specific wordpress directory. I can successfully call up a random image file however it does not display, just displays the image filename and a broken image icon.
The code I am using from the tutorial to display the image is <?php echo Qassim_Random_File("my-folder-name"); // display random image! ?>
I am brand new to php as of this week, and a fairly novice coder in general (know some basics) so I really am stumped. I've fooled with other possible solutions from stack overflow already but this tutorial is the only thing I've been able to get close to working. Many thanks if anyone can spot the problem!
This is showing up in the HTML inspector:
<div class="elementor-widget-container">
<h5>call</h5>
<a href="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" target="_blank" title="image_2.jpg">
<img src="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" alt="image_2.jpg">
</a>
</div>
You just need to replace this line:
$file_link = $folder_path . "/" . $random_file;
...with this one:
$file_link = get_site_url(null, $folder_path . "/" . $random_file);
What was the problem?
scandir is returning the physical file path, not the url to the file - we can confirm this is we look at one of the values it returns for $random_file, e.g. wp-content/uploads/H-PH-MA-Greyscale
This is a relative URL, but we need an absolute URL so that it will work no matter where it is called. We also need to include the site URL so that the path to wp-content is correct. (Note: site URL and home URL can be different - the site URL is the one that always point to the location of the WP files).
Another problem is the trailing slash (or lack of one) on the site URL. get_site_url and get_home_url do not add the trailing slash to the URL, so you need to add it yourself if it isn't included in the file path.
So how do we solve this?
Using the get_site_url function added the correct path to the WP files, and it also lets us pass it the file path with our without a preceding slash as a parameter, and it will add the slash on the path only if it is needed.
The code looks simple, if the folder exist and it has more then 2 file (it considers the "." and ".." and files when you use scandir) then you should be able to see something. What's the generated HTML code for that function call?
Be aware that the code you are using builds the file url using the phisical path, that isn't going to work. You should fix this part:
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = get_home_url().$folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
Notice the get_home_url() to build the real URL which is needed for your <img tag src
based on the original code in this question and Tims correction over there (answer 1) I'm trying to achieve the following:
I have a folder "img" containing images as follows:
image_123.jpg
image_123_alternate.jpg
image_456.jpg
image_456_alternate.jpg
image_789.jpg
image_789_alternate.jpg
and so on...
(Note: all images have the same size of 200px/200px)
When pulling from the "img" folder the simple HTML page should display images and filenames in the following fashion:
The actual images that contain the "_alternate" part in their filename (and only these) + the image filename not containing the "_alternate" part (without the file-extension) underneath the image in a textbox. All pairs should be pulled in an alphabetical order. In the example below bold capital letters indicate the actual image to be displayed:
IMAGE_123_ALTERNATE
textbox: "image_123"
IMAGE_456_ALTERNATE
textbox: "image_456"
IMAGE_789_ALTERNATE
textbox: "image_789"
This is what I have so far but this displays all images and filenames:
<?php
$dir = opendir("img");
while (($file = readdir($dir)) !== false)
{
echo "<a href='img/".$file."' target='_blank'> <img src='img/".$file."'width='200' height='200' /></a><br />";
echo "<textarea>$file</textarea><br /><br />";
}
closedir($dir);
?>
Any help would be much appreciated!
Thanks a lot!
This code should display a list of all images in alphabetical order (using PHP's GLOB function).
It then outputs a HTML image (leading to the "_alternate" image) and the image's filename (without the path, "_alternate" or "extension").
<?php
foreach (glob("img/*_alternate.jpg") as $file) {
$filename_parts = pathinfo($file);
$filename = $filename_parts['filename'];
$filename = str_replace("_alternate", "", $filename);
echo "<div>";
echo "<img src=\"/$file\" width=\"200\" height=\"200\" />";
echo "<p>$filename</p>";
}
?>
I have broken apart the functions that find the new filename and the parts that output the HTML code to make it easier to read and understand, you could merge these into one function if you wanted to.
Just through an if statement in your while loop. Check if the file name contains alternate or or not. If it doesn't contain alternate run your same code replacing the file extension with "_alternate.ext" while keeping the text area the same. If it does contain alternalte, do nothing. That way you are only processing half the files.
$files = new \DirectoryIterator('img'); // <- this should be the full absolute path!
$images = array();
// pick up jpg images that end in 'alternate'
foreach($files as $file){
$name = $file->getBasename('.jpg');
if(strripos($name, 'alternate') === (strlen($name) - 9))
$images[] = $name;
}
// sort them
sort($images, SORT_STRING);
// and do your thing here with $images...
var_dump($images);
I hope this can be of great help to others, it took me awhile of PHP learning, but gave me a good PHP high when I pieced it together.
For those of you who are looking to put images next to your sphider results...
I use Sphider for indexing a product folder with thousands of items, here is an example of my file structure for use with this snippet:
www/
product/
item1.php
item2.php
item3.php
images/
item1.png
item2.png
item3.png
Insert this into sphider/templates/standard/search_results.html (or sphider/templates/dark/search_results.html) in line 75 just after " class="title">
<?PHP
// Edit here
$url_path = "http:// www.yoursite.com/product/"; // The url leading to your indexed pages.
$url_ext = ".php"; // The file extension of indexed pages.
$image_path = "../images/"; // Path to image folder.
$image_ext = ".png"; // The file extension of images.
// To here
$image = str_replace("$url_path", "$image_path", $url);
$image = str_replace("$url_ext", "$image_ext", $image);
if (file_exists($image)) {
// do nothing or Your Option
} else { $image = $image_path . "ICS" . $image_ext; } ?>
<img src="<?PHP print $image ?>" alt="" align="left" style="margin-right:10px; border:0;" />
Basically, if you have a page called 1234.php in your Sphider index, this will try to find picture 1234.png to go along side it of the search result. If an image is not found it will display a default image 'ICS.png' (Image Coming Soon).
Happy coding
I am building a Wordpress website. Please don't mind that I'm not working on a local or testing server, or my code. It's messy at the moment while I try to figure out this programming bit. By going to my website, you will see a row of images along the top, which is within a jcarousel.
It works, but if you hit next until you get to the "portrait" photo, there is a gap. The gap is because I have to set a width in pixels within my HTML or CSS for the carousel to work correctly. If set to auto, the carousel collapses. Makes sense to me, but it's frustrating that I cannot work around that. I want the "landscape" and "portrait" photos to have an identical height of 427, but the width I want it to self-adjust to the actual image size.
So I think I understand this bit after playing around for 3 days - I cannot tell you how many carousel codes I've used. Originally I thought that was the problem, and some were. I found out, widths of each image slide are set within the JavaScript, so if I gave it a width of 640, I would get the same result as I am getting now.
My first question is this:
I'm calling my images from a directory on my server, written specifically for Wordpress (author). Here is the code:
<?php
$uploads = wp_upload_dir();
if ($dir = opendir($uploads['basedir'].'/picture-atlantic')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
echo '<ul>';
foreach($images as $image) {
echo '<li><img src="';
echo $uploads['baseurl'].'/picture-atlantic/'.$image;
echo '" alt="" width="auto" height="auto" /></li>';
}
echo '</ul>';
?>
As you can see, it's calling from the picture-atlantic directory and displaying it within an unordered list, which is required for some reason with my jcarousel.
Finally: how can I use this same code to get my images, but also display them at their actual sizes? In the code above, if I define the width and height, it does it for all the images. However, as I mentioned before, I have portrait pictures that use different dimensions. I found this code: erikastokes.com/php/how-to-get-image-size-with-php.php, but I'm not sure how to implement it in my existing code.
Could someone please help me rewrite it?
You could set the width of the image to 100% and add a style to reposition portrait images at top: -50%;, but you will not be able to see the entire image if it is in landscape.
<?php
$uploads = wp_upload_dir();
if ($dir = opendir($uploads['basedir'].'/picture-atlantic')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
echo '<ul>';
foreach($images as $image) {
$myimage = $uploads['baseurl'].'/picture-atlantic/'.$image;
$size = getimagesize($myimage);
$top_50 = '';
if($size[1] > $size[0]) {
$top_50 = 'style="position: realative; top: -50%;"';
}
echo '<li><img src="';
echo $uploads['baseurl'].'/picture-atlantic/'.$image;
echo '" alt="" width="100%" height="auto" '.$top_50.'/></li>';
}
echo '</ul>';
?>
Welp, I read that I cannot use getimagesize if I'm already using php to dynamically display my images. I ended up settling with uploading images through Wordpress, within an unordered list, and placing my carousel markup in the post loop. It works just fine now.
Oh, I read on http://www.css-tricks.com that Wordpress adds the image attributes automatically, and that is what solved the image width problem while displaying landscape and portrait style photos at 100% across the screen.
To those who are trying to do a similar task, don't use jj nexgen gallery for inserting your images. jj nexgen gallery is a great plugin, along with the others associated with it. It just won't work for what I was trying to do because it doesn't add the attributes to the image. I would download their wordpress plugins if you aren't trying to do this, so I'm guessing the majority of you.
Thanks again for the replies.
I am trying to make a simple gallery script on my page for a photo booth. I have a tethered camera which is dropping pictures into a folder on my local site hosted with MAMP. Each folder is a different groups photos. Path to photos is ('/images/**'). First page searches the folders in my images directory and returns only the first image as a thumbnail/link to all folders containing all images for that group of people.
My structure is as follows.
1st page is:
$i = 1;
foreach (glob('images/*') as $dir) {
echo '<div id="strip' . $i . '" class="polaroid">';
// One div per directory
$p = 1;
foreach (glob($dir."/*.jpg") as $img) {
$p++;
if ($p <= 2) {
echo "<a href='$dir'><img src='$img'/></a>";
} else {
}}
echo "</div>\n";
$i++;
This part works and takes the user to the directory with jpegs in it. which also contains a index.php file with the following code:
$dir = 'images/'.basename('/'.getcwd()).'/';
foreach (glob($dir."/*.jpg") as $img)
echo $img;
{
echo "<img src='$img'/>";
}
This is where it fails. When I echo out $dir it shows the current relative path, but $dir in the foreach statement seems to be returning empty. This just returns an empty img tag. Any opinions where I am going wrong.
Thanks in advance
If you want to list the files in the current directory you have to set
$dir = '.';
You did set $dir to /images/225652/ but you are already in this directory