My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>
Related
I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:
$pdfPath = "/Documents/TEST/";
$maxSize = 102400000000;
$docid = TEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) {
if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
if ($_FILES['filepdf']['type'] != "application/pdf") {
echo '<p>The file is not in PDF</p>';
} else if ($_FILES['filepdf']['size'] > $maxSize) {
echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
} else {
$menuName = "Order_Receipt_".$docid.".pdf";
$result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
if ($result == 1) {
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';
} else {
echo '<p class="error">Error</p>';
}
}
}
I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.
Cheers
Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.
The glob function is useful for that:
http://php.net/manual/en/function.glob.php
$myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
//last element
$lastFile = end($myFiles); //returns the last file in the array
//get the number and increment it by one
$number = explode('_',$lastFile);
$newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
$pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.
$docid = TEST;
should be:
$docid = 'TEST';
Edit
Even better would be naming it in a formatted date I suppose.
$pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf
I have seen several websites where if you upload an image and an identical image already exists on there servers they will reject the submission. Using PNGs is there an easy way to check one image against a massive folder of images?
http://www.imagemagick.org/discourse-server/viewtopic.php?t=12618
I did find this with imagemagick, but I am looking for one vs many and not one to one a million
You can transform the file content into a sha1. That will give you a way to identify two pictures strictly identical.
see http://php.net/manual/fr/function.sha1-file.php
Then after you save it into a NFS, or use some kind of database to test if the hash already exists.
Details of the images are probably maintained in a database; while the images are stored in the filesystem. And that database probably has a hash column which is used to store an md5 hash of the image file itself, calculated when the image is first uploaded. When a new image is uploaded, it calculates the hash for that image, and then checks to see if any other image detail in the database has a matching hash. If not, it stores the newly uploaded image with that hash; otherwise it can respond with details of the previous upload. If the hash column is indexed in the table, then this check is pretty quick.
If I understood your question correctly. You want to find out if a specific image exists in a Directory with so many images, right? If so, take a look at the solution:
<?php
// CREATE A FUNCTION WHICH RETURNS AN ARRAY OF ALL IMAGES IN A SPECIFIC FOLDER
function getAllImagesInFolder($dir_full_path){
$returnable = array();
$files_in_dir = scandir($dir_full_path);
$reg_fx = '#(\.png|\.jpg|\.bmp|\.gif|\.jpeg)#';
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $dir_full_path . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && preg_match($reg_fx, $val) ){
$regx_dot_wateva = '/\.{2,4}$/';
$regx_dot = '/\./';
$regx_array = array($regx_dot_wateva, $regx_dot);
$replace_array = array("", "_");
$return_val = preg_replace($regx_array, $replace_array, $val);
$returnable[$return_val] = $temp_file_or_dir ;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return $returnable;
}
// CREATE ANOTHER FUNCTION TO CHECK IF THE SPECIFIED IMAGE EXISTS IN THE GIVEN DIRECTORY.
// THE FIRST PARAMETER SHOULD BE THE RESULT OF CALLING THE PREVIOUS FUNCTION: getAllImagesInFolder(...)
// THE SECOND PARAMETER IS THE IMAGE YOU WANT TO SEARCH WHETHER IT EXISTS IN THE SAID FOLDER OR NOT
function imageExistsInFolder($arrImagesInFolder, $searchedImage){
if(!is_array($arrImagesInFolder) && count($arrImagesInFolder) < 1){
return false;
}
foreach($arrImagesInFolder as $strKey=>$imgPath){
if(stristr($imgPath, $searchedImage)){
return true;
}
}
return false;
}
// NOW GET ALL THE IMAGES IN A SPECIFIED FOLDER AND ASSIGN THE RESULTING ARRAY TO A VARIABLE: $imgFiles
$imgFolder = "/path/to/directory/where/there/are/images";
$arrImgFiles = getAllImagesInFolder($imgFolder);
$searchedImage = "sandwich.jpg"; //<== OR EVEN WITHOUT THE EXTENSION, JUST "sandwich"
// ASSUMING THE SPECIFIC IMAGE YOU WANT TO MATCH IS CALLED sandwich.jpg
// YOU CAN USE THE imageExistsInFolder(...) FUNCTION TO RETURN A BOOLEAN FLAG OF true OR false
// DEPENDING ON IF IT DOES OR NOT.
var_dump($arrImgFiles);
var_dump( imageExistsInFolder($arrImgFiles, $searchedImage) );
I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:
$pdfPath = "/Documents/TEST/";
$maxSize = 102400000000;
$docid = TEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) {
if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
if ($_FILES['filepdf']['type'] != "application/pdf") {
echo '<p>The file is not in PDF</p>';
} else if ($_FILES['filepdf']['size'] > $maxSize) {
echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
} else {
$menuName = "Order_Receipt_".$docid.".pdf";
$result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
if ($result == 1) {
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';
} else {
echo '<p class="error">Error</p>';
}
}
}
I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.
Cheers
Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.
The glob function is useful for that:
http://php.net/manual/en/function.glob.php
$myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
//last element
$lastFile = end($myFiles); //returns the last file in the array
//get the number and increment it by one
$number = explode('_',$lastFile);
$newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
$pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.
$docid = TEST;
should be:
$docid = 'TEST';
Edit
Even better would be naming it in a formatted date I suppose.
$pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf
I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.
Appreciate your help
Thank you.
I don't know whats about the $img_id but you could consider to use shuffle().
shuffle($file_array);
But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:
$file_array = array(
array("images/bag200.bmp", 1),
array("images/bag178.bmp", 1),
array("images/bag004.bmp", 0,
...
);
In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)
You can loop over images this way (they are in random order now):
<?php foreach($file_array as $image): ?>
<img src="<?php echo $image ?>" />
<?php endforeach; ?>
If you only want to display a subset of the images, randomly chosen, you can do this:
$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly
shuffle($rand); //shuffle keys
foreach($rand as $r) {
echo '<img src="' . $file_array[$r] . '" />';
}
Some comments on your code:
$ran = array_rand($file_array);
$ran contains a key randomly chosen from the images.
for ($i=0;$i<200;$i++) {
//while (in_array($tst,$rand_array)){
$tst = $file_array[$ran];
$id = $img_id[$ran];//}
$rand_array[] = $tst;
$rand_id[] = $id;
}
You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.
If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html