I haven't seen this asked yet, so if it is, can someone re-direct me?
I'm having an issue creating a full screen background for my WordPress theme that uses random images from the image library. I want to write a PHP function that can be used on multiple sites, so I can't simply use the direct path in the code. It also needs to work on MultiSite in such a way that it only pulls images that are uploaded to that site. Here's the code I'm working with:
HTML for my Background Div
<div id="background" class="background" style="background-image:url(<?php displayBackground();?>);">
</div>
PHP to randomize my image folder
<? php
function displayBackground()
{
$uploads = wp_upload_dir();
$img_dir = ( $uploads['baseurl'] . $uploads['subdir'] );
$cnt = 0;
$bgArray= array();
/*if we can load the directory*/
if ($handle = opendir($img_dir)) {
/* Loop through the directory here */
while (false !== ($entry = readdir($handle))) {
$pathToFile = $img_dir.$entry;
if(is_file($pathToFile)) //if the files exists
{
//make sure the file is an image...there might be a better way to do this
if(getimagesize($pathToFile)!=FALSE)
{
//add it to the array
$bgArray[$cnt]= $pathToFile;
$cnt = $cnt+1;
}
}
}
//create a random number, then use the image whos key matches the number
$myRand = rand(0,($cnt-1));
$val = $bgArray[$myRand];
}
closedir($handle);
echo('"'.$val.'"');
}
I know that my CSS markup is correct because if I give the DIV a fixed image location, I get a fullscreen image. Can anyone tell me what to do to fix it?
Related
This question already has answers here:
How to prevent Browser cache for php site
(7 answers)
Closed 3 years ago.
I am trying to give my wordpress site a randomly pulled "About the Author" image in my footer.
My first solution was to create an array, name them each aboutAuthor[x].jpg and generate a random number for x.
That works just fine, but I was looking for a solution that didn't involve me having to rename files and adding a line of code every time I decide to add a new image to the folder.
I found a solution on this site: http://photomatt.net/scripts/randomimage
He provides some php code
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array();
$i = -1;
if ('' == $folder)
$folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach ($exts as $ext) {
if (preg_match('/\.' . $ext . '$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double) microtime() * 1000000);
$rand = mt_rand(0, $i);
header('Location: ' . $folder . $files[$rand]);
?>
Then I simply place that php file in the directory in question and call it in place of an image
<img src="/imgDirectory/rotate.php">
The only problem with this is that my browser is caching the resulting random image.
With a normal reload or clicking a link to a new page, I get the same image.
With a hard reload, I get a new one, like I want.
Oddly, in the sample on his website, it works as expected with a normal reload.
So what is the best way to achieve what I'm looking for?
Here is the solution
1) Create new div:
<div class="randomAuthor" id="randomAuthor"> </div>
2) Move image source
<img src="/imgDirectory/rotate.php">
to a separate PHP or html file, example author.php:
3) Load author.php into div "randomAuthor" using
ajax code:
$(document).ready(function(){
$('#randomAuthor').load("author.php");
});
This way on each refresh the $(document).ready(function(){..... will get triggerd which in turn will trigger rotate.php file thus you will get new image each time you open your page or refresh it.
I am developing an application using php for personal use. What I want to achieve is :
I have a large number of images in a directory. I want to write some description for every image. I have prepared a DB table with 3 columns : id, image_name(unique constraint) and description.
And to make it work, I have developed a webpage, where I would open each image in the browser, write a description about it, save to the database and then open the next image by clicking next and so on.
However, I couldn't figure out how to achieve it. If I do something like :
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
Then I would end up opening n-1 images always , before I reach the nth image.
I would first import the files into the database. Not the actual files , but just a reference to the file in the folder.
(this is not the complete code, but you'll get the point)
$files = array_diff( scandir("/path/to/directory"), array(".", "..") );
foreach($files as $file) {
//insert a reference into the database
$query = "insert into table_name (image_name) values $file;";
mysql_query($query);
}
Once they are in place you can easily query them by the Id.
A webpage would look something like this:
<?php
$imageId= (int)$_GET['id'];
$row = mysql_fetch_array("select * from table_name where id=$imageId");
?>
<html><body>
Next image
<img src="<? echo $row['image_name']; ?> ">
your form here...
and go to your page using for example http://127.0.0.1/images/index.php?id=1
Using browser you cannot do it because between web requests PHP does not keep its state.
What you can do is:
Keep the last image number in a cookie - on next request you will read it and skip to the desired number (you still have to skip).
Send the whole list of files from PHP to your browser and navigate through it within one page using Javascript and AJAX requests.
Keep the list and/or the current number in your database in some temporary table. So each time you send the request to PHP script, it will first check if saved data exists.
What I would do is to find an image that doesn't exist in the database already and request a description for it, this would make the php to be like:
if (!empty($_POST['image'])) {
// Save the image / description in the db
}
$existing = array(); // Fill this array with the image names that exist in the db.
$dir = "/images/";
// Open a directory, and read its contents
$file = null;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if (!in_array($file, $existing)) {
break;
}
}
closedir($dh);
}
}
if ($file === null) {
die('something is wrong, I can not get any files');
}
// set the $file to your view
And in the html I would have something like this:
<form action="">
Image: <input name="image" type="text" value="<?php echo $file; ?>"/>
Description: <input name="description" type="text" value="<?php echo $file; ?>"/>
</form>
FIXED!
Feel free to use my code, no need to cite my work. There was no problem, just that the image size was too small and some weren't showing up. duh.
I will change the size from 100px to 500px for anyone who wants to use this code.
Have fun
I'm trying to use some open code that's available on the internet to make a random flash generator.
The orignal code:
<?php
$imglist='';
//$img_folder is the variable that holds the path to the swf files.
// see that you dont forget about the "/" at the end
$img_folder = "images/";
mt_srand((double)microtime()*1000);
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, ad them to a list
while ($file = $imgs->read()) {
if (eregi("swf", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//display random swf
echo '<embed src="'.$img_folder.$image.'" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash" width="100"
height="100"></embed>';
?>
My modified code:
<?php
$imglist='';
//$img_folder is the variable that holds the path to the swf files.
// see that you dont forget about the "/" at the end
$img_folder = "../files/flash/";
mt_srand((double)microtime()*1000);
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, ad them to a list
while ($file = $imgs->read()) {
if (preg_match("/(swf)/i", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//display random swf
echo '<embed src="'.$img_folder.$image.'" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash" width="500"
height="500"></embed>';
?>
I was at first having problems with ergi on line 11, I was told to replace it with preg and I went through and figured that out.
I loaded up my random page, (http://www.nsgaming.us/random/) and it flashed for a fraction of a second a random flash object I had in the folder but now it just shows nothing.
help please?
my index shows as follows:
<html>
<head>
<title>test</title>
<?php
include("../menu.php");
include_once('random2.php');
?>
</head>
<body>
<p>This is the random page.</p>
<p>I am planning on having random flash objects load here but still working on it.</p>
</body>
</html>
Keep in mind I am new to moderate at web design, HTML and PHP.
If you could try and not yell at me for doing something stupid which is probably what happened.
instead of
if (preg_match("/(swf)/i", $file))
try
if (preg_match("/\.swf$/i", $file))
Also the following line is going to break your code if any filename has space in your filename.
$imglist = explode(" ", $imglist);
Instead of
while ($file = $imgs->read()) {
if (preg_match("/(swf)/i", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
The following code will help you serve the filenames with spaces also. This will also exclude the two dot directories.
$imglist=array();
while (false !== ($file = $imgs->read())) {
if (($file==".")||($file=="..")) continue;
if (preg_match("/\.swf$/i", $file))
$imglist[]= $file;
} $imgs->close();
The flash objects are returning 404.
One of them actually works.
http://www.nsgaming.us/files/flash/anon_partyhard007.swf
Based on this, I think you might be looking at the wrong files folder. I'm assuming you have a public files folder, and then a files folder one level below root?
Perhaps this might work better.
$img_folder = "./files/flash/";
I have a script that scans a directory of thumbnails and echoes them to the page. It works nicely, but the thumbnails are not clickable, and i would really like this to be the case. echo "<img src='$thumbnail' class='resizesmall'>"; is the line where the thumbnails are echoed. I'm not sure how to write the path to the larger image inside the php without breaking it. Maybe this should be done inside the foreach statement? thanks for your help?
$dir = "../mysite/thumbnails/";
$dh = opendir($dir);
// echo "$dh";
$gallery = array();
while($filename = readdir($dh))
{
$filepath = $dir.$filename;
//pregmatch used to be ereg
if (is_file($filepath) and preg_match("/\.png/",$filename))
{
$gallery[] = $filepath;
}
}
sort($gallery);
foreach($gallery as $thumbnail)
{
echo "<img src='$thumbnail' class='resizesmall'>";
}
?>
</div>
<??>
The easiest way would be to setup a situation where your thumbs and your full size images were named the same. So you may have thumbs/image1.png and full/image1.png. Then instead of using $thumbnail use a variable $image, or something similar just so the code reads better. You'll also want to leave the $filepath out of the mix so that $image ends up as just the file name.
foreach($gallery as $image)
{
echo "<a href='full/$image'><img src='thumb/$image' class='resizesmall'></a>";
}
You may want to throw in some checks to make sure there is a matching image just to prevent errors or bad UX. However, the code above should work.
Yesterday I got a question about a slideshow with lightbox fixed on stackoverflow but now I came to another problem.. I create an Javascript array trough php and in JS I make the slideshow work + lightbox work. Now when I add a new image to the images folder it does include it in the src"" attribute but does not show the image and instead shows the error picture when an image doesn't work (couldn't include an image because I don't have enough rep if you would like the image of the problem, I can send it)
This is the php code part:
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname ="/Applications/MAMP/htdocs/slidepluslight/slideshows/minpunten/images/") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
print_r ('galleryarray['.$curimage.']="'.$file .'";');
$curimage++;
}
}
closedir($handle);
}
return($files);
}
print 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And this is the Javascript code that makes the slideshow + lightbox work.
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 500);
}
window.onload = function(){
setInterval("rotateimages()", 2500);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('lightbox').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
It all runs fine but when I add a new image to the images folder it doesn't show it..
Regards Koen.
UPDATE, everything worked but we tried to do it dynamically but now the src"" gives me undefined.. Does somebody see where I code it wrong?
The php part:
function returnimages($relPath = "/slidepluslight/slideshows/minpunten/images/") {
$dirname = $_SERVER['DOCUMENT_ROOT'] + $relPath;
$files = array();
$curimage = 0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if (preg_match('/\.(jpg|jpeg|gif|png)$/', $file)){ //if this file is a valid image
//Output it as a JavaScript array element
print_r ('galleryarray['.$curimage.']="'. $relPath + $file .'";');
$curimage++;
}
}
closedir($handle);
}
return($files);
}
print 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
And the Javascript part:
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
Kinds regards,
Koen.
The reason you were having trouble is you weren't properly refering to the location of the images. I'll find some links to have you look it in a min.
If you change
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
to
document.getElementById("slideshow").setAttribute("src", "/slidepluslight/slideshows/minpunten/images/"+galleryarray[curimg]);
the browser will know to look in the /slidepluslight/slideshows/minpunten/images directory for the images.
The remander of this answer applies to the dynamic URL issue so this solution could be used in other applications.
As far as making the links to the images dynamic it seems to me like it needs to be addressed in the returnimages function.
Use $_SERVER['DOCUMENT_ROOT'] to get the root directory of website. Here that is /Applications/MAMP/htdocs and then have the rest specified as a parameter to returnimages.
function returnimages($relPath = "/slidepluslight/slideshows/minpunten/images/") {
$dirName = $_SERVER['DOCUMENT_ROOT'] . $relPath;
...
/* Where you are outputting the JS array */
print_r ('galleryarray['.$curimage.']="'. $relPath + $file .'";');
....
}