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
Related
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.
On my website people earn points by seeing a page. They get 1 point for each second they keep the page open (the page keeps rotating Advertisements).
Some people have started exploiting this by opening that page multiple times all together and hence are earning more points! for example if the user open the page 10 times then he is earning 10 points for each second. I don't want them to earn more than 1 point per second.
How can I prevent the users from opening that page more than once at the same time?
Thanks in advance.
note : My website is php based.
I have on easy but not reliable way in mind:
Set a Sessionvar like
$_SESSION['user_already_on_page'] = true;
Now you can check for this variable and return an error page or something like that.
if($_SESSION['user_already_on_page'])
{
//maybe the user has left unexpected. to workaround this we have to check
//for the last db entry. Examplecode:
$query = mysql_query($_db,'SELECT LastUpdated FROM Pointstable WHERE U_Id = $uid');
$row = mysql_fetch_array($query);
if((time()-$row['LastUpdated']) < 5)
{
die("You are already on this page!");
}
//$_SESSION['user_already_on_page'] is set but the last update is older than 5 sec
//it seems, that he unexpectedly lost connection or something like that.
}
To unset this variable you could fire an AJAX-Script on pageclose that unsets this variable.
So your unsetonpage.ajax.php could look like this:
<?php $_SESSION['user_already_on_page'] = false;?>
And your JS-Part (using jquery):
$(window).bind('beforeunload', function(eventObject) {
$.ajax({url:'./ajax/unsetonpage.ajax.php',type:'GET'});
});
This should work.
Add the time when the page is opened to the database. Whenever the page is opened check if the difference b/w that time and current time is less than xx seconds then redirect the user. If the difference is more than xx seconds then update that time.
//--- You make session in startup called (my_form)
if (!empty($_SESSION['my_form']))
{
if ($_SESSION['my_form']== basename($_SERVER['PHP_SELF']))
{
header("Location:index.php");
exit();
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
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);
}
...
I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>
I'm having a problem here and I think people here can help me.
I have a file that generates an image, ler.php, and the file that loads the images through a while, carregar.php.
I need to block direct access to the images generated by ler.php, tried to make a system like this session:
carregar.php:
<?
$_session['a'] = 1;
while($a != 50) { echo "<img src='ler.php?imagem=$a'>"; $a++; }
$_session['a'] = 0;
?>
ler.php:
<? if($_session['a'] == 1) { //load image } ?>
The result is the only loading the first image.
I'm trying to now use the $_SERVER ["PHP_SELF"], placing the IF of ler.php, what happens is I load it through <img src=''> she identifies as carregar.php.
Who has the best solution?
I've tried several ways with $_SESSION and it seems to not really work.
I could suggest two ways:
Easy to implement, less protective: in ler.php check that $_SERVER["HTTP_REFERER"] refers to "carregar.php".
A little bit more complicated: in carregar.php generate an unique code for each image you're going to output and store it in $_SESSION. Then pass the code to ler.php as a GET parameter. In ler.php check if the code exists in $_SESSION object, then generate an image and remove the code from $_SESSION.
I have a hard time identifying the problem, but your use of the session is going to lead to unexpected results:
You are adding 50 (I guess...) image tags to a page and right after you have added these tags, you set the session variable to 0.
The browser only loads a few files from the same server at the same time, so when the script is done and the first image is loaded, the browser is going to request the next image but that will fail as you have set the session variable to 0 already.
The only way to reliably set the session variable to 0 after all images have loaded, is an ajax request from your page that checks and triggers after all images have completely loaded.
Good! I managed to resolve one way and improvised without using AJAX:
ler.php:
<?php
if(isset($_SERVER["HTTP_REFERER"])) {
$check2 = (strpos($_SERVER["HTTP_REFERER"], 'carregar.php') > 0) ? true : false;
if(print_r($check2) != 11) {
// Blank
}
} else {
if(isset($_SERVER["HTTP_REFERER"]))
{
// Load Image
}
if(!isset($_SERVER["HTTP_REFERER"]))
{
// Blank
}
?>
So, the image only can be loaded into my page. Maybe...