Stop rand() code after limited page refreshes - php

I'm using a code that generate a random word from a database using ORDER BY RAND() LIMIT 1 (not many rows so it runs okay) . Is it possible, using php, to only allow the user to refresh the page a few limited times (either by clicking refresh manually or using a form['submit'] button) and then stopping the random function so it sets to the last value?
I know I can count page visits/refreshes by using sessions/cookies but I'm not sure how to stop the code running.

Barely constitutes an answer but too long for a comment - what is it exactly that you don't get?
<?php session_start();
// ...
if(!isset($_SESSION['myCounter']))
$_SESSION['myCounter'] = 0;
if($_SESSION['myCounter'] < $myLimit){
$_SESSION['myCounter']++;
// Do random DB query
$_SESSION['lastResult'] = $dbResult;
}
// Do something with result
echo $_SESSION['lastResult'];
// ...
There are even examples on the manual pages...

A IF statement would suffice
IF ( pagecount < 3 )
{
Execute code
}
ELSE
{
Don't execute code
}

Set a flag on your PHP Script using a session say, $_SESSION['runRand'] = 1;
Run the random word db code only when the above variable is set to 1.
So when the user runs this script first time...
Store the first random word which was generated from DB into a session variable say $_SESSION['firstRand']=$randNum;
So when the user clicks the refresh button or submit, the PHP script gonna load again and a new random word will be generated, now don't store that word, just compare it to the one with the session variable $_SESSION['firstRand'];
When the user keeps clicking refresh and do the same process again, at some point the random word will match with the $_SESSION['firstRand']; , at that time set the session variable $_SESSION['runRand'] = 0; . Now , eventhough the user presses the refresh button the random code from DB will not be generated.

Related

How to get dynamic home page

I have a index.html file consist of certain data with refresh button.
On pressing refresh button it will call refresh.php.
Refresh.php connects database and gets new updated data from database (Say- today's event data) And shows updated data in that refresh.php page
this is what I do.. But I want dynamic home page and want to remove refresh button. In short- whenever user loads homepage..that division should display updated data from database. So should I use .index.php and use php code in index.php itself will work?
I dont want to use asp/ajax/cookie/session. Please give me idea apart from these. Thanks :)
You could check the file's age, e.g.
<?php
$ca_file = '/path/to/foo.blah';
if (is_file($ca_file)) {
// check if file is not older then 1 hour
if (time() - filemtime($ca_file) <1 * 3600) {
$ca_news = 'y';
}
}
That would check if the file is not older then 1 hour. You'll probably want something smaller. Now all you need to do is to check the value of $ca_news and do your magic.

How to rotate two strings or functions on page refresh?

I have two values, i want to echo one of them on page refresh and rotate it.
If the two values are Hello and Hi.
Hello > Page refresh > Hi > Page refresh >Hello > Page Refresh > Hi
I tried shuffle, rand, mt_rand but sometimes it just keep the same value instead of rotating to the next.
Thanks.
<?php
session_start();
if (!isset($_SESSION["count"])) $_SESSION["count"] = 0;
$_SESSION["hits"]++;
echo ($_SESSION["hits"]%2 == 1?"Hi":"Hello");
// or with functions
if ($_SESSION["hits"]%2 ==1){
my_func_1();
} else {
my_func_2();
}
its basically a page hit counter with logic on what to print depending on if the page hits are even or odd.
To rotate the string, something random is definitively not what you are seeking.
First to have to decide the scope of the rotation.
Based on the distributed page from the server ? (odd pages hays hi) or based on the user that si visiting you (so the rotation is always visible to you, ever if other users have also the rotation)
I guess you want based on user:
So you have to link the rotation to the user that visit you,
that can be managed through a cookie or through a PHP session
set the cookie and based on the value, say hello or hi
// before sending headers
$say = isset($_COOKIE['say'])?$_COOKIE['say']:1;
setCookie('say', $say==1?2:1);
if ($say == 1)
echo "hello";
else
echo "hi";
You can do the same thing with a PHP session
That gives you an idea

PHP: In forEach, stopping execution when a condition is reached, but continuing later

Suppose I have something like this:
$count = 0;
foreach($CourseDetails as $course_line) {
print "<tr><td>{$course_line['class_code']}</td>
<td>{$course_line['class_name']}</td>
<td>{$course_line['class_unit']}</td>
<td>{$course_line['class_description']}</td>
<td>{$course_line['class_instructors']}</td>";
$count = $count + 1
if ($count = 10);
$count = 0;
// code that stops script and makes a "Continue?" button pop up on the webpage under the already outputed details
// if the client presses the "Continue?" button, allow the script to continue (jump back into the foreach loop)
}
I'm trying to find a way to stop the script and then make a button saying "Continue?". If the client presses the button, I want the script to continue where it left off. Does PHP have any functions that allow this?
Short answer: no!
This is more of a workflow design issue. I would suggest creating a list of items to execute. Then try to execute them (as they are successfully processed, mark them as complete), if an error is hit, then stop execution and let the user know. If the user wishes to continue, reload the page, and continue executing the items that have not completed from your initial list.
You can't stop the script once the page has been loaded in the browser. You can only create an interrupt condition inside the script. The two ways for "memory" between pages are either passing an URL variable, e.g. start=20, or using $_SESSION variables to remember the last point of interrupt. Better pass the variable over URL so the pages are individually accessible.
Then, in your loop, simply evaluate whether the entries have a number above the last interrupt. The following presumes your courses are in an array with a numeric index, in which case the $count is redundant. If you're pulling them from a database, take a totally different approach...
$start = !empty($_GET['start']) ? $_GET['start'] : 0;
$offset = 10;
foreach($CourseDetails as $course_num => $course_line) {
if ($course_num < $start) continue; // These were already seen.
if ($course_num >= $start + $offset) {
// Interrupt and make a button that links to ?start=$start+$offset.
break;
}
// Here display stuff.
}

My PHP Random page generator has stopped working properly after 100,000 hits

My website relies completely on a random page generator that loads a page from a text file list. The code was kindly written by "lserni" on the forum. The script has been working perfectly the last few days, and it's happily processed over 100,000 page views in 3 days!
I noticed today however that it seems to have stopped working properly. If you are a brand new visitor to the page, or you've cleared your internet cache/cookies etc - When you load the page for the first time, it doesn't randomly generate a page.. it just shows a BLANK page. If you then refresh the page, the script works perfectly. I just can't get my head round it, but it's now resulted in a large drop in traffic! Hope you can help:
<?php
session_start();
if (!isset($_SESSION['urlist'])) // Do we know the user?
$_SESSION['urlist'] = array(); // No, start with empty list
if (empty($_SESSION['urlist'])) // Is the list empty?
{
$_SESSION['urlist'] = file("linklist.txt"); // Fill it.
$safe = array_pop($_SESSION['urlist']);
shuffle($_SESSION['urlist']); // Shuffle the list
array_push($_SESSION['urlist'], $safe);
}
$url = trim(array_pop($_SESSION['urlist']));
header("Location: $url");
?>
It's actually the LAST item in the file that's used first if there is no session data.
{
$safe = array_pop($_SESSION['urlist']); // gets item at the END of the array
shuffle($_SESSION['urlist']);
array_push($_SESSION['urlist'], $safe); // puts item at the END of the array
}
$url = trim(array_pop($_SESSION['urlist']));// gets item at the END of the array
So if you introduced a newline in your textfile at the end, it may be your issue.
I would suggest, after the header call, add some HTML that explains where the user is being redirected to. All being well nobody will ever see it, but it could help diagnose why the user gets an empty page.

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

Categories