Randomly Rotate PHP files in sidebar on page refresh - php

I have 4 php files which all have a small PHP and jQuery game inside.
The files are as follows:
/game1.php
/game2.php
/game3.php
/game4.php
Every time the page is refreshed I want one of the games to show in the sidebar. When the page is refreshed again, a different game and so.
Is there a way to include files in the sidebar at random via some kind of query on page refresh, if so, could someone please help me with the code. Thanks!

$games = array('game1.php','game2.php','game3.php','game4.php');
session_start();
$used = array();
if (isset($_SESSION['used'])){
$used = $_SESSION['used'];
}
$usable = array_diff($games,$used);
if (sizeof($usable)==0){
$usable = $games;
$_SESSION['used'] = array();
}
$inUse = $usable[array_rand($usable)];
$_SESSION['used'][] = $inUse;
include($inUse);

Try:
include '/game' . rand(1, 4) . '.php';

$FileNames = array ('File1.php','File2.php','File3.php','File4.php'); // Can later be autodetected if file structure gets too big
$FileNames = array_rand($FileNames);
foreach ($FileNames AS $Links){
echo $Links;
}
If you wish to make these clickable:
foreach ($FileNames AS $Links){
echo "".$Links."";
}

$file_array= array('game1.php','game2.php','game3.php','game4.php');
$rand = rand (0, count ($file_array));
include ($file_array[$rand]);

I think you'll find your answer in sessions since you don't want the last viewed game to show up on a next page refresh:
//Fill in array
$games = array('game1' => 'PONG', 'game2' => 'Donkey Kong', 'game3' => 'Patience', 'game4' => 'LoL');
//Delete the current game from the array
unset($games[$_SESSION['currentGame']]);
//Shuffle the array and pick the last one
$game = end(shuffle($games));
include($game.'.php');
//Update session for next page refresh
$_SESSION['currentGame'] = $game;

Related

Getting all from json api array using php

I wanna improve on how to fetch data from an API. In this case I want to fetch every app-id from the Steam API, and list them one per line in a .txt file. Do I need an infinite (or a very high-number) loop (with ++ after every iteration) to fetch everyone? I mean, counting up from id 0 with for example a foreach-loop? I'm thinking it will take ages and sounds very much like bad practice.
How do I get every appid {"appid:" n} from the response of http://api.steampowered.com/ISteamApps/GetAppList/v0001?
<?php
//API-URL
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
//Fetch content and decode
$game_json = json_decode(curl_get_contents($url), true);
//Define file
$file = 'steam.txt';
//This is where I'm lost. One massive array {"app": []} with lots of {"appid": n}.
//I know how to get one specific targeted line, but how do I get them all?
$line = $game_json['applist']['apps']['app']['appid'][every single line, one at a time]
//Write to file, one id per line.
//Like:
//5
//7
//8
//and so on
file_put_contents($file, $line, FILE_APPEND);
?>
Any pointing just in the right direction will be MUCH appreciated. Thanks!
You don't need to worry about counters with foreach loops, they are designed to go through and work with each item in the object.
$file = "steam.txt";
$game_list = "";
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
$game_json = file_get_contents($url);
$games = json_decode($game_json);
foreach($games->applist->apps->app as $game) {
// now $game is a single entry, e.g. {"appid":5,"name":"Dedicated server"}
$game_list .= "$game->appid\n";
}
file_put_contents($file, $game_list);
Now you have a text file with 28000 numbers in it. Congratulations?

Random image from directory with no repeats?

I am successfully able to get random images from my 'uploads' directory with my code but the issue is that it has multiple images repeat. I will reload the page and the same image will show 2 - 15 times without changing. I thought about setting a cookie for the previous image but the execution of how to do this is frying my brain. I'll post what I have here, any help would be great.
$files = glob($dir . '/*.*');
$file = array_rand($files);
$filename = $files[$file];
$search = array_search($_COOKIE['prev'], $files);
if ($_COOKIE['prev'] == $filename) {
unset($files[$search]);
$filename = $files[$file];
setcookie('prev', $filename);
}
Similar to slicks answer, but a little more simple on the session front:
Instead of using array_rand to randomise the array, you can use a custom process that reorders based on just a rand:
$files = array_values(glob($dir . '/*.*'));
$randomFiles = array();
while(count($files) > 0) {
$randomIndex = rand(0, count($files) - 1);
$randomFiles[] = $files[$randomIndex];
unset($files[$randomIndex]);
$files = array_values($files);
}
This is useful because you can seed the rand function, meaning it will always generate the same random numbers. Just add (before you randomise the array):
if($_COOKIE['key']) {
$microtime = $_COOKIE['key'];
else {
$microtime = microtime();
setcookie('key', $microtime);
}
srand($microtime);
This does means that someone can manipulate the order of the images by manipulating the cookie, but if you're okay with that this this should work.
So you want to have no repeats per request? Use session. Best way to avoid repetitions is to have two arrays (buckets). First one will contains all available elements that your will pick from. The second array will be empty for now.
Then start picking items from first array and move them from 1st array to the second. (Remove and array_push to the second). Do this in a loop. On the next iteration first array won't have the element you picked already so you will avoid duplicates.
In general. Move items from a bucket to a bucket and you're done. Additionally you can store your results in session instead of cookies? Server side storage is better for that kind of things.

Pagination without using database in PHP

I am trying to create a webpage which shows 10 files stored in a directory each time. I don't want to use database for it though. This is what I have up to this point.
<?php
$exclude = array("index.php");
$cssfiles = array_diff(glob("*.php"), $exclude);
foreach ($cssfiles as $cssfile) {
$filename = "http://example.com/lessons/css/".$cssfile;
outputtags($filename,true,true);
}
?>
This prints out all results, I can't figure out how to show just first ten results and after that when user clicks next 10 more results without using database. I think using a database just for this purpose doesn't make sense.
EDIT The reason I want to do it this way is because I am getting max_user_connection error.
You could do that by storing your files into an array and sort it as you wish, like following :
$exclude = array("index.php");
$cssfiles = array_diff(glob("*.php"), $exclude);
$files = array();
foreach ($cssfiles as $cssfile) {
$filename = "http://example.com/lessons/css/".$cssfile;
$files[] = $filename;
}
asort($files);
// Pagination start from here
$page = 1; // You will get this parameter from the url using $_GET['page'] for instance
$limit = 10; // Number of files to display.
$offset = (($page-1) * $limit);
$max = ($page * $limit);
$max = $max > count($files) ? count($files) : $max;
for ($i=$offset; $i<$max; $i++) {
echo $files[$i] . PHP_EOL;
}
echo 'Total Pages : ', count($files). PHP_EOL;
echo 'Page number : ' , $page;
Maybe you could use ajax and extract the pagination page to avoid fetching all the files each time.
It depends on how you want to select those ten pages. One could use a for loop that lists the files 0-9 as and may count from 10-19,..., depening on the page range the user requests.
However, when a file is added, the system would get out of order. In that case, loading / saving some sorting Information to sessions / cookies could solve the problem.
EDIT : Using a database is, however, the standard for tasks like this. Even if you don't like them, you will most likely need them for more complex Tasks that require sorting, searching or joining multiple datasets, that are just too complicated to achieve with the filesystem functions.

php include random file with no repeat on pageload

I am currently using mt_rand to display a random file from the specified folder each time the page is loaded.
After doing lots of searching i think i need to create an array and then shuffle the array, but not sure how to go about this.
Most of the examples i have found use an array and then echo the results where as i'm trying to include the result.
<?php
$fict = glob("spelling/*.php");
$fictional = $fict[mt_rand(0, count($fict) -1)];
include ($fictional);
?>
You can use session cookies to hold a random, non-repeating list of files. Actually, for security, the session cookie should only store a list of indices into an array of files.
For example, suppose we have the following file list in an array:
index file
----------------------------
0 spelling/file1.txt
1 spelling/file2.txt
2 spelling/file3.txt
3 spelling/file4.txt
We can create an array of the indices, e.g. array(0,1,2,3), shuffle them to get something like array(3,2,0,1), and store that list in the cookie. Then, as we progress through this random list of indices, we get the sequence:
spelling/file4.txt
spelling/file3.txt
spelling/file1.txt
spelling/file2.txt
The cookie also stores the current position in this list of indices and when it reaches the end, we reshuffle and start over.
I realize all this may sound a bit confusing so maybe this gorgeous diagram will help:
… or maybe some code:
<?php
$fictional = glob("spelling/*.php"); // list of files
$max_index = count($fictional) - 1;
$indices = range( 0, $max_index ); // list of indices into list of files
session_start();
if (!isset($_SESSION['indices']) || !isset($_SESSION['current'])) {
shuffle($indices);
$_SESSION['indices'] = serialize($indices);
$_SESSION['current'] = 0; // keep track of which index we're on
} else {
$_SESSION['current']++; // increment through the list of indices
// on each reload of the page
}
// Get the list of indices from the session cookie
$indices = unserialize($_SESSION['indices']);
// When we reach the end of the list of indices,
// reshuffle and start over.
if ($_SESSION['current'] > $max_index) {
shuffle($indices);
$_SESSION['indices'] = serialize($indices);
$_SESSION['current'] = 0;
}
// Get the current position in the list of indices
$current = $_SESSION['current'];
// Get the index into the list of files
$index = $indices[$current];
// include the pseudo-random, non-repeating file
include( $fictional[$index] );
?>

How to show a random picture in a web page?

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 . "'" );
}
}
}
?>

Categories