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.
Related
I have a foreach loop that is processing image uploads. When I add multiple images they are given a filename that consists of a unique id and a time stamp using $filebase = uniqid() . '_' . time();
When the images are processed they have the same image name, and I don't understand why the foreach loop isn't giving unique file names?
I have the $temp variable assigned to the index of the foreach loop with the following line: $temp = $_FILES['standard-upload-files']['tmp_name'][$index]; so I don't understand why it doesn't increment a new value?
The images are being moved correctly to the destination folder (albeit with the same name) so I know it isn't an issue with my HTML form, or the initial foreach loop.
if(isset($_POST['submit-images'])) {
foreach($_FILES['standard-upload-files']['name'] as $index => $filename ) {
if($_FILES['standard-upload-files']['error'][$index] === 0 ) {
$temp = $_FILES['standard-upload-files']['tmp_name'][$index];
$filebase = uniqid() . '_' . time();
move_uploaded_file($temp, "images-download/{$filebase}");
}
} // main foreach
} // isset($_POST)
I see, my first guess is using uniqid. Uniqid is generated based on the current time in microseconds which could result in the same values. As the documentation mentions, this function does not guarantee the uniqueness of the return value.
Since most systems adjust the system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return a unique ID for the process/thread. Use more_entropy to increase the likelihood of uniqueness.
A [not so reliable] solution would be setting the more_entropy to true:
uniqid('', true)
but again, remember this approach is not reliable.
So use another method for generating your unique IDs (UUID for example as explained in the comments here.)
I am trying to make a PHP application which searches through the files of your current directory and looks for a file in every subdirectory called email.txt, then it gets the contents of the file and compares the contents from email.txt with the given query and echoes all the matching directories with the given query. But it does not work and it looks like the problem is in the if-else part of the script at the end because it doesn't give any output.
<?php
// pulling query from link
$query = $_GET["q"];
echo($query);
echo("<br>");
// listing all files in doc directory
$files = scandir(".");
// searching trough array for unwanted files
$downloader = array_search("downloader.php", $files);
$viewer = array_search("viewer.php", $files);
$search = array_search("search.php", $files);
$editor = array_search("editor.php", $files);
$index = array_search("index.php", $files);
$error_log = array_search("error_log", $files);
$images = array_search("images", $files);
$parsedown = array_search("Parsedown.php", $files);
// deleting unwanted files from array
unset($files[$downloader]);
unset($files[$viewer]);
unset($files[$search]);
unset($files[$editor]);
unset($files[$index]);
unset($files[$error_log]);
unset($files[$images]);
unset($files[$parsedown]);
// counting folders
$folderamount = count($files);
// defining loop variables
$loopnum = 0;
// loop
while ($loopnum <= $folderamount + 10) {
$loopnum = $loopnum + 1;
// gets the emails from every folder
$dirname = $files[$loopnum];
$email = file_get_contents("$dirname/email.txt");
//checks if the email matches
if ($stremail == $query) {
echo($dirname);
}
}
//print_r($files);
//echo("<br><br>");
?>
Can someone explain / fix this for me? I literally have no clue what it is and I debugged soo much already. It would be heavily gracious and appreciated.
Kind regards,
Bluppie05
There's a few problems with this code that would be preventing you from getting the correct output.
The main reason you don't get any output from the if test is the condition is (presumably) using the wrong variable name.
// variable with the file data is called $email
$email = file_get_contents("$dirname/email.txt");
// test is checking $stremail which is never given a value
if ($stremail == $query) {
echo($dirname);
}
There is also an issue with your scandir() and unset() combination. As you've discovered scandir() basically gives you everything that a dir or ls would on the command line. Using unset() to remove specific files is problematic because you have to maintain a hardcoded list of files. However, unset() also leaves holes in your array, the count changes but the original indices do not. This may be why you are using $folderamount + 10 in your loop. Take a look at this Stack Overflow question for more discussion of the problem.
Rebase array keys after unsetting elements
I recommend you read the PHP manual page on the glob() function as it will greatly simplify getting the contents of a directory. In particular take a look at the GLOB_ONLYDIR flag.
https://www.php.net/manual/en/function.glob.php
Lastly, don't increment your loop counter at the beginning of the loop when using the counter to read elements from an array. Take a look at the PHP manual page for foreach loops for a neater way to iterate over an array.
https://www.php.net/manual/en/control-structures.foreach.php
I searched all day on this forum but couldn't find any answer.
I use following php code to display the next line from myfile.txt on each pageload (looping when gone through entire file):
<?php
session_start();
$item = file("myfile.txt");
$itemCount = count($item);
if ($_SESSION['sess_row'] === NULL) {
$_SESSION['sess_row'] = 0;
} else {
$_SESSION['sess_row'] = ($_SESSION['sess_row'] + 1) % $itemCount;
}
echo $item[$_SESSION['sess_row']];
?>
Now I want to shuffle the lines in myfile.txt before each session.
For example, if myfile.txt contains 5 lines, it now displays lines in same order every session: 123451234512345...
With shuffle it should display one session: 325413254132541..., another session: 413254132541325..., another session: 142351423514235..., and so on.
How can above code be changed to shuffle myfile.txt before each session?
Use shuffle to shuffle your array each time.
$item = file("myfile.txt");
shuffle($item);
If you need to have different number for each user, you should have a database or something (it could be just a single file containing one number) to keep track of how many of your items are already assigned to users. Each time, read that number (call it cursor), assign the number associated with that cursor, increment the cursor by one and write it back to the file (or database ...)
If you need unique data, you can use array_unique:
$item = file("myfile.txt");
$item = array_unique($items);
shuffle($item);
in "file.txt" i have some numbers like 1234,123456,12345678 etc.
so i was wondering how i can get dynamically just one element, for example echo just 12345,then echo 123456, but one by one ???when user comes i want to show him one element,and then next time i want to show another element on the page, it would be good also if i could erase elements that i have echo...When i manually enter position it works... Please help...
I have a following code:
function test($n){
$file=file_get_contents("file.txt");
$array = explode(",", $file);
return print_r($array[$n]);
};
The solution will need deleting the number on your filesystem or marking it as already showed either on the filesystem or on the database, after the number gets echoed.
Shuffling the numbers or generating a random index will never quite be full proof since the same number could be shown again.
First of all, this is usually a terrible way of doing this.
It's much better to use a database, for example.
But you could do the following:
<?php
function getRandomNumber() {
// retrieve and parse the numbers
$numbers = file_get_contents('file.txt');
$numbers = explode(',' $numbers);
// select a random index
$randomIndex = array_rand($numbers);
// get the chosen number
$randomNumber = $numbers[$randomIndex];
// remove it from array
unset($numbers[$randomIndex]);
// save updated file
file_put_contents('file.txt', implode(',', $numbers));
return $randomNumber;
}
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] );
?>