Currently I have a script running to grab all the images in a directory based on ending with "154x154.jpg". Basically what I'm doing is going through a gallery directory and looking for all the thumbnails of images, which I will then output in a sliding gallery on the main page of a website.
<?php
// loop through the images
$count = 0;
$images = array();
foreach (glob("../../uploads/2012/05/*154x154.jpg") as $filename) {
$images[$count] = $filename;
$count++;
}
for ($i = 0; $i < 7; $i++) {
$random = mt_rand(1, $count - 1);
echo '<li><a class="gal_img" href="#">';
echo '<span class="roll"></span>';
echo '<img class="image" src="'.$images[$random].'" height="154" width="154" alt="" />';
echo '</a></li>';
}
?>
This works perfectly fine as it is, but what I need to do is be able to grab the files from within a directory above the current one. To be more specific:
image folder: http://root/wp-content/uploads/2012/05/
theme folder: http://root/wp-content/themes/theme_folder/
** EDIT **
Everything works now with the above code it executes fine, when I go directly to the file. However using it within the theme generates everything except for the filepaths in the code. Using wordpress 3.3.2
Try:
foreach (glob("../images/*154x154.jpg") as $filename) {
Update:
Of course, this is a relative path and only works if the file you need to include is one level up from your script's current working directory. Solution: use an absolute path, ie. one that begins with /. Also, keep in mind that the absolute path is a path on the disk, not the root folder of your website.
Related
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
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
Alright, this will need a long explanation. Sorry if it's too long:
/////////////// INTRODUCTION ///////////////
There doesn't seem to be much information around about using opendir() within Wordpress and the way it should be implemented. However, after a couple hours of research, trial and error, I got it working on a custom page template.
I need it to fetch game thumbnail images from folders and output them as a grid, divided by categories (each folder is a category).
/////////////// MY APPROACH ///////////////
I created a function in functions.php that opens and reads a folder using the following relative path:
"wp-content/games/".$category."/"
Where $category is the argument of the function (defined by the user).
This is how my function looks like now:
function fetch_game_images($category){
//$category = 'featured';
$imageFiles = array();
$extensions = array('.JPG','.PNG');
$directory = "wp-content/games/".$category."/";
$openDir = opendir($directory);
while ($imgFile = readdir($openDir))
{
if ($imgFile <> '.' and $imgFile <> '..')
{
$extension = strtoupper(substr($imgFile, strrpos($imgFile, '.')));
if (in_array($extension, $extensions))
{
$imageFiles[] = $imgFile;
}
}
}
closedir($openDir);
foreach ($imageFiles as $k => $v)
{
$withoutExt = preg_replace("/\\.[^.\\s]{3,4}$/", "", $v);
$hyphenlessName = str_replace("-"," ",$withoutExt);
$formattedName = strlen($hyphenlessName) > 24 ? substr($hyphenlessName,0,24)."..." : $hyphenlessName;
if ($category == 'featured'){
if (strpos($formattedName,'netent') !== false) {$finalName = trim($formattedName, 'netent');}
else if (strpos($formattedName,'mg') !== false) {$finalName = trim($formattedName, 'mg');}
else { $finalName = $formattedName;}
}
else { $finalName = $formattedName;}
echo '<div class="games-list-item"><div class="game-container">';
echo '<a href=""><img src="'.get_bloginfo('url').'/'.$directory.'/'.$v.'" alt=""/>';
echo '<h3>'.$finalName.'</h3></a>';
echo '<div class="game-hover">';
echo '<img src="'.get_bloginfo('url').'/'.$directory.'/'.$v.'" alt=""/>';
echo '<div class="game-buttons-holder"><a class="play_now_btns" href="">Play Now</a><a class="free_play_btns" href="">Free Play</a></div></div><!--.game-hover-->';
echo '</div><!--.game-container--></div><!--.games-list-item-->';
}
}
/////////////// MY APPROACH RESULTS ///////////////
When I load the Wordpress Page using the Page Template that calls this function, it loads the images flawlessly.
But then, I have to change the games category dynamically using jQuery, I take the category/folder name, save it in a JavaScript variable and send it to a php that grabs it and passes it to the fetch_game_images(); function.
My jQuery GET looks like this:
$('#sidebar-list-menu li a').live('click', function(){
event.preventDefault();
var category = $(this).data('category');
//alert(cat);
//$('div.games-grid').html('<span class="loadingNotification">LOADING</span>');
$.get("<?php bloginfo('template_directory'); ?>/games-list-loader.php?category="+category,
function(data){
//alert(data);
//$('span.loadingNotification').remove();
$('div.games-grid').html(data);
});
});
And the PHP File (located in the same theme directory) looks like this:
<?php $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$cat = $_REQUEST['category'];
fetch_game_images($cat);
?>
<div class="clear"></div>
/////////////// THE ISSUE ///////////////
The issue is that when I click on the sidebar link that triggers the GET call and tries to fetch the data from the PHP, it outputs the following error:
Warning: opendir(wp-content/games/featured/) [function.opendir]: failed to open dir: No such file or directory in [...]
Which shouldn't happen at all, since both my Page Template and my custom PHP file are in the same directory and load Wordpress core to use functions.php.
/////////////// THE QUESTION ///////////////
Does anybody know what could be the reason behind this behaviour? I read most of the google results I could find about this opendir() error, but most of them seem to point at a wrong path, but mine seem to be correct.
Others say that it might be a permissions issue. But I got my folders set to 755 and the files to 644.
So, any help would be great!
Thank you.
<======== /////////// EDIT ///////// =========>
Thanks to the help by #CBroe, I figured it out:
Instead of using a loose path like
"wp-content/games/".$category."/"
I changed it to a server-relative one
ABSPATH . "/wp-content/games/".$category."/"
And then I just changed the output to match the changes:
echo '<img src="'.get_bloginfo('url').'/wp-content/games/'.$category.'/'.$v.'" alt=""/>';
This works from both locations and solved the GET issue.
Most likely your relative path is not the correct one – usually happens when scripts are run from two different physical locations.
Making a debug output of getcwd() directly before calling opendir will show you what directory the scripts are actually running in in both cases – and that location is the one used to “complete” the relative path, so if those don’t match it’s only natural one of them will fail.
Relative paths are always tricky that way. It’s usually preferable to use a path relative to the server root (starting with a /) to avoid such issues.
in php i want to ask how to get images one by one from folder directory and display in the jquery slider i have tried this php code by it's not working as i want?
<ul class="jcarousel-list">
<li class="jcarousel-item">
<?php
$directory = "data/uploads/topslider/";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
else
{
}
$files_index = glob("data/uploads/"."top"."slider/*.*");
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
?>
<img src="<?php echo $num2;?>" width="50" height="50" alt="" /> <?
}?></li>
</ul>
i want display like this:
Image1 Imag2 Image3......and So On from single folder or directory
There are four main things to check:
Is your $directory path correct relative to your current working directory in PHP? You can determine your current working directory by doing a temporary echo getcwd();. It needs to return the parent directory of your "data" folder for your code to work.
Is the data folder accessible from the current page on the web? e.g. if you manually remove the page from the URL (say, index.php) and add data/uploads/topslider/someimage.png where someimage.png is an image you know exists in your topslider folder, does the image load properly in the browser? If not, you'll need to update the way you build the src attribute in your img tag(s).
You're only adding one jcarousel-item for all your images, which doesn't seem right to me. I'm guessing you're expected to add a list item for each image.
You don't need to call glob twice just to ascertain how many files you have to work with. Just do a foreach statement once:
echo '<ul class="jcarousel-list">';
foreach(glob($directory . '*') as $filename) {
echo '<li class="jcarousel-item"><img src="'.$filename.'" width="50" height="50" alt="" /></li>';
}
echo '</ul>';
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