Jump to content

Random Pictures PHP (Complete noob(

WhatComesAround

So I am really new to programming in php, but I am trying to skip ahead a LOT while I am learning. So I am trying to make a site that would display a random gif from a folder called "images". Then if the user whats to change the photo they just hit the arrow key to refresh the page and load up a new random gif. Anyone know how to do this?

 

(Edit):BTW, I would like to be able to just place photos into the folder and without having to add new lines to the code (image2.gif, image3.gif, anyway to skip this?)

Link to comment
Share on other sites

Link to post
Share on other sites

Easiest and cleanest way is to add the list of images to a database and select * order rand to return a random image. If you really don't want to for whatever reason you can get a list of all images in that folder, add them to an array. Get the number of elements in that array and mt_rand() a random one which you can send to the user

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Hazy125 said:

Easiest and cleanest way is to add the list of images to a database and select * order rand to return a random image. If you really don't want to for whatever reason you can get a list of all images in that folder, add them to an array. Get the number of elements in that array and mt_rand() a random one which you can send to the user

And could I just add the images to the database as I wish? And btw, how do I make a database, I downloaded WAMP, and I don't see any databases. Do I have to download MySQL separately?

Link to comment
Share on other sites

Link to post
Share on other sites

You don't even need a database. Just have a folder with the images and use a library to read all the filenames to an array and then select a random one.

PC: Case: Cooler Master CM690 II - PSU: Cooler Master G650M - RAM: Transcend 4x 8Gb DDR3 1333Mhz - MoBo: Gigabyte Z87x-D3H - CPU: i5 4670K @ 4.5Ghz - GPU: MSI GTX1060 ARMOR OC - Hard disks: 4x 500Gb Seagate enterprise in RAID 0 - SSD: Crucial M4 128Gb

Phone: Samsung Galaxy S6

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, WhatComesAround said:

And could I just add the images to the database as I wish? And btw, how do I make a database, I downloaded WAMP, and I don't see any databases. Do I have to download MySQL separately?

You wouldn't want to add images to the database exactly. That would take up a lot of space. Your images are stored in the images directory. You would just add a string to your database referencing that. Example, just 'img1.gif'. Then when you select that from the database just send the user the source of that image.

WAMP stands for Windows, Apache, MySQL, PHP. MySQL is already installed. I don't remember if PHPMyAdmin(Database management software is installed by default in WAMP because I use XAMPP) but even if it's not you can still create and manage databases from the command line or your PHP script.

 

EDIT: Even though I mentioned the other answer in my first response but still recommended a database approach is because the alternative does not scale at all. You have 300 images and 20 people browsing at once and your whole site is broken

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

You don't need a library you can just use scandir:

http://php.net/manual/en/function.scandir.php

PC: Case: Cooler Master CM690 II - PSU: Cooler Master G650M - RAM: Transcend 4x 8Gb DDR3 1333Mhz - MoBo: Gigabyte Z87x-D3H - CPU: i5 4670K @ 4.5Ghz - GPU: MSI GTX1060 ARMOR OC - Hard disks: 4x 500Gb Seagate enterprise in RAID 0 - SSD: Crucial M4 128Gb

Phone: Samsung Galaxy S6

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, Hazy125 said:

EDIT: Even though I mentioned the other answer in my first response but still recommended a database approach is because the alternative does not scale at all. You have 300 images and 20 people browsing at once and your whole site is broken

You have any evidence to back this up? scandir isn't that slow and for someone just starting it's easier to try out.

PC: Case: Cooler Master CM690 II - PSU: Cooler Master G650M - RAM: Transcend 4x 8Gb DDR3 1333Mhz - MoBo: Gigabyte Z87x-D3H - CPU: i5 4670K @ 4.5Ghz - GPU: MSI GTX1060 ARMOR OC - Hard disks: 4x 500Gb Seagate enterprise in RAID 0 - SSD: Crucial M4 128Gb

Phone: Samsung Galaxy S6

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, Hazy125 said:

You wouldn't want to add images to the database exactly. That would take up a lot of space. Your images are stored in the images directory. You would just add a string to your database referencing that. Example, just 'img1.gif'. Then when you select that from the database just send the user the source of that image.

WAMP stands for Windows, Apache, MySQL, PHP. MySQL is already installed. I don't remember if PHPMyAdmin(Database management software is installed by default in WAMP because I use XAMPP) but even if it's not you can still create and manage databases from the command line or your PHP script.

 

EDIT: Even though I mentioned the other answer in my first response but still recommended a database approach is because the alternative does not scale at all. You have 300 images and 20 people browsing at once and your whole site is broken

 

7 minutes ago, LUUD18 said:

You don't need a library you can just use scandir:

http://php.net/manual/en/function.scandir.php

Maybe I'll stick to youtube videos, seems like I have a bright future there sooner than with a website xD. I already got the hang of youtube and I don't think that making a website will be better if instead I could just spend more time focusing on making more content on youtube, however, I will maybe allocate a small amount of time everyday to learning php, a little will go a long way (I hope).

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, WhatComesAround said:

And as for scandir, you can have an ascending/descending order, but can I have a single random image?

You would have to use http://php.net/manual/en/function.rand.php and then get a random number between 0 and the size of the array. Then use that number to get the picture from the array.

PC: Case: Cooler Master CM690 II - PSU: Cooler Master G650M - RAM: Transcend 4x 8Gb DDR3 1333Mhz - MoBo: Gigabyte Z87x-D3H - CPU: i5 4670K @ 4.5Ghz - GPU: MSI GTX1060 ARMOR OC - Hard disks: 4x 500Gb Seagate enterprise in RAID 0 - SSD: Crucial M4 128Gb

Phone: Samsung Galaxy S6

Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, WhatComesAround said:

And as for scandir, you can have an ascending/descending order, but can I have a single random image?

Just popping back to add some numbers as I was asked for proof. Test case 870 items, 1 user. RAID 0 SSD w/ 6800k.

 

<?php 

//Scandir with mt_rand as the random operator
$start = microtime(true);
$val = scandir('D:\Downloads');
$limit = count($val);
$returnNum = mt_rand(0, $limit);
echo $val[$returnNum];
$time_elapsed_secs = microtime(true) - $start;
echo '<br>Elapsed Time: ' . $time_elapsed_secs;

echo '<br><br><br>';

$nstart = microtime(true);
$servername = "localhost";
$username = "";
$password = "";
$dbname = "test";


//MySQL with RAND() query (By the way, easily improved upon)
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("rip");
} 
$sql = "SELECT * FROM `forum` ORDER BY rand() LIMIT 1";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
    while($row = $res->fetch_assoc()) {
        echo $row['file'];
    }
}
$conn->close();
$ntime_elapsed_secs = microtime(true) - $nstart;
echo '<br>Elapsed Time: ' . $ntime_elapsed_secs;

echo '<br><br><br>';

//Scandir with other users suggest random operator of rand()
$n2start = microtime(true);
$val = scandir('D:\Downloads');
$limit = count($val);
$returnNum = rand(0, $limit);
echo $val[$returnNum];
$n2time_elapsed_secs = microtime(true) - $n2start;
echo '<br>Elapsed Time: ' . $n2time_elapsed_secs;
?>

 

The script I used to test numbers.

 

Results:
c3275e651d.png

 

As you can see, database is faster than both rand and mt_rand. Not a huge difference but hey, 1 user.

In my first response I immediately suggest mt_rand() over rand() as it is common knowledge that it's just quicker and more random by default

   -source https://en.code-bude.net/2013/01/06/php-rand-vs-mt_rand-what-is-more-accurate-what-is-faster/

                http://stackoverflow.com/questions/28760650/difference-between-mt-rand-and-rand

and in fact in the last version of PHP they just got rid of the old rand() function and made it behave the same way as mt_rand()

 

In reality the difference isn't huge, but whatever option you go for, using rand() over mt_rand is pointless

 

 

 

 

I am good at computer

Spoiler

Motherboard: Gigabyte G1 sniper 3 | CPU: Intel 3770k @5.1Ghz | RAM: 32Gb G.Skill Ripjaws X @1600Mhz | Graphics card: EVGA 980 Ti SC | HDD: Seagate barracuda 3298534883327.74B + Samsung OEM 5400rpm drive + Seatgate barracude 2TB | PSU: Cougar CMX 1200w | CPU cooler: Custom loop

Link to comment
Share on other sites

Link to post
Share on other sites

First, you have to define your problem.

You say when user presses LEFT or RIGHT on the keyboard when your page is loaded, the page should reload and show another image. So basically, either LEFT or RIGHT key, the consequence is the same, a random image is loaded from a folder.

 

The easiest solution to handle pressing keys and reloading page would be to add some javascript code in the page served to the user. The code would monitor the keyboard for key presses and when it detects the left or right key, it tells the browser to reload the page.

It's javascript code because javascript runs in the browser on the users' computer after page is loaded completely.

PHP is a programming language meant to run on the remote server in order to create a page which is then served to the user.

 

Anyway.. so let's say the problem of pressing keys is solved, and browser loads or reloads the page.

Now, every time the browser requests the page, the web server (apache) starts php and  tells php to parse your php file and execute the code in that page, and the output of your php code will be sent to the user.

So every time your code is executed, your code will basically have to build a list of images it has available (either by using php functions to search within one or multiple folders, or by retrieving a list of file names from a database)  and then your code must pick a number between 1 and the maximum number of images you can work with and then in the code sent to the user, you print the command which tells the web browser to load an image.

 

Here's a very basic example where the source code has a list of images pre-stored in an array

 

<?php 

$imagelist[0] = 'file1.jpg';
$imagelist[1] = 'anotherfile.png';
$imagelist[2] = 'animatedpicture.gif';

$imagecount = 2; // the maximum number random function should pick.

$imagechoice = mt_rand(0,$imagecount); // min , max

// now we start creating the HTML page which is sent to the user.

echo '
<html>
 <head>	
	<title>Random Image</title>
 </head>
<body>';

//Now tell the browser to load the random image 

echo '<img src="http://mydomain.org/images/' . $imagelist[$imagechoice] . '" alt="This is a random image" />

// here you would send a Javascript function inside the page that the browser would load after the page is fully downloaded from the server 
// the function would monitor the key presses and reload the page..
// Im too lazy to make one up, so Im just going to put an empty form with a button, when button is pushed by user, page reloads

echo '
<form name="name" method="post" action="">
	<input name="button" type="submit" value="Reload page" />
</form>';

echo '
</body>
</html>';

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

What @bogdanastan said. Basic idea is:

 

<?php

$pathToPictures = 'wherever/they/are/*.gif';

$pictures = [];
foreach(glob($pathToPictures) as $picture) {
	$pictures[$picture] = null; // array_rand returns key, so that's all we care about
}
$randomPicture = array_rand[$pictures];

Now, depending on how large your folder becomes, it might get a bit processing intensive to rebuild that array every request. Or what if you decide to move your pictures to s3 or someplace else? That's where a library like Flysystem comes in: abstract the file getting and cache the results for a moderate amount of time so you don't have to rebuild the array from disk. 

 

Or build a caching solution yourself, could be a fun project with Redis...

 

Edited by Brammm
cleaned up the code

BTW - God tier beard.

- @Slick in a PM once

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×