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>
Related
Purely hypothetical at this point, no code yet. Trying to figure out the best way to do this. We are company "A" and we have two partners, company "B" and company "C". On a sign up form, we collect data and then pass it on to either partner "B" or parnter "C" - this part is good to go and working fine. I do this with ajax on the front end and a cURL processor on the back end so no one leaves our site and just post the data directly to the partner's form.
Unfortunately due to partner "B" and "C"'s required data the forms we post to are different and we have to have 2 separate html form files, one for each partner. The problem is that we need to do this all from one URL, not a separate one for each partner.
I would guess we would use a 'handler' page that has the specific url - http://www.example.com/parterForm.php
Then in the 'handler' page we would make the switch serve the correct content. I need a way to evenly split who we send data to. I'd like to do the switch on a very granular, MS level for example:
if the time = 0-500 ms - serve Parter B page;
if time = 501-1000ms -serve Partner C page;
all done within the 'handler' page - calling the forms as php includes?
I realize this is not a specific code question and I aplogize, this is something I've never done before and am trying to figure out how to do this. I'm a Creative Director btw who codes, no other resource avail.
thanks.
Hmm, yes, you could do that. That would work reasonably well, in fact. The important thing is to make sure the form goes to the right partner. You could use $_SESSION for that, or check which fields were sent and deduce from that which partner was chosen.
For example:
if( fmod(microtime(),1) < 0.5) include("forms/partner1.php");
else include("forms/partner2.php");
Then when submitted:
$partner1fields = array("name","email","country","dateofbirth");
$partner2fields = array("name","address","postcode","ethnicity");
// the above are examples - they should correspond to the $_POST keys you expect
// now check if they match. Array equality depends on order, so sort first
$postkeys = array_keys($_POST);
sort($postkeys);
sort($partner1fields);
sort($partner2fields);
if( $postkeys == $partner1fields) { /* submit to partner 1 */ }
elseif( $postkeys == $partner2fields) { /* submit to partner 2 */ }
else {
echo "<p>Given keys did not match either partner</p>";
echo "<p>POST keys: ".implode(", ",$postkeys)."</p>";
echo "<p>Partner 1 keys: ".implode(", ",$partner1keys)."</p>";
echo "<p>Partner 2 keys: ".implode(", ",$partner2keys)."</p>";
echo "<p>Please report this error to the site administrator.</p>";
exit;
}
First, by MS I assume you mean the latency between client and server?
Use javascript to either load a tiny image from the server or make an ajax call that gets one char or something and time this. For testing you'll need to do some real pings and adjust your js time to reflect the ping round trip. For example, if the js time to load the image is 500ms but ping time is only 80ms then maybe divide by 6 for the result. This will never be very precise as the client and the server both have processing overhead. Make sure to echo no cache headers or past expire times with the image or ajax response.
Easy, if time <= 500 redirect to form A, if time > 500 redirect to form B or use ajax to load them up.
I have implemented a basic auto-complete feature using jQuery autocomplete. I am querying DB every time which is making auto-complete thing quite slow. I am looking for ways to make it faster much like Quora.
Here is the code from front-end:
<script type="text/javascript">
var URL2 = '<?php e(SITE_URL); ?>fronts/searchKeywords';
jQuery(document).ready(function(){
var CityKeyword = jQuery('#CityKeyword');
CityKeyword.autocomplete({
minLength : 1,
source : URL2
});
});
</script>
Here is the code from server side:
function searchKeywords(){
if ($this->RequestHandler->isAjax() ) {
$this->loadModel('Expertise_area');
Configure::write ( 'debug',0);
$this->autoRender=false;
$expertise=$this->Expertise_area->find('all',array(
'conditions'=>array('Expertise_area.autocomplete_text LIKE'=>'%'.$_GET['term'].'%'),
'fields' => array('DISTINCT (Expertise_area.autocomplete_text) AS autocomplete_text'),
'limit'=>5
));
$i=0;
if(!empty($expertise)){
$len = strlen($_GET['term']);
foreach($expertise as $valueproductname){
$pos = stripos($valueproductname['Expertise_area']['autocomplete_text'],$_GET['term']);
$keyvalue = "";
if($pos == 0) {
$keyvalue= "<strong>".substr($valueproductname['Expertise_area']['autocomplete_text'],$pos,$len)."</strong>"
.substr($valueproductname['Expertise_area']['autocomplete_text'],$len);
}else {
$keyvalue= substr($valueproductname['Expertise_area']['autocomplete_text'],0,$pos)."<strong>"
.substr($valueproductname['Expertise_area']['autocomplete_text'],$pos,$len)."</strong>"
.substr($valueproductname['Expertise_area']['autocomplete_text'],$pos+$len);
}
$response[$i]['value']=$valueproductname['Expertise_area']['autocomplete_text'];
$response[$i]['label']="<span class=\"username\">".$keyvalue."</span>";
$i++;
}
echo json_encode($response);
}else{
}
}
}
I have researched a bit and so far following solutions are worth looking at:
Query data on page load and store it in COOKIE to be used in future.
Implement some caching mechanism (memcache??). But my website is on Cakephp which does it internal cahcing if I am right. So will it be worth to go in this direction.
Use some third party indexing mechanism like Solr, Lucene etc. Don't know much about this.
Implement a much complex "Prefix Search" myself
What is the right way to go about it? Please help me out here.
I've never tried this but will be doing it soon for a project I'm working on.
I always considered the possibility of during the initial page load recieveing some AJAX (or perhaps just including it in the page) the top 10 words for each alphabet letter.. e.g.
A - apples, anoraks, alaska, angela, aha, air, arrgh, any, alpha, america
B - butter, bob etc.....
This way when user presses A-Z you can instantly provide them with 10 of the most popular keywords without any further requests, as you already have them stored in an array in the JS.
I'm not sure of size/memory usage but this could be extended further to handle the first 2 letters, e.g. AA, AB, AC.....BA, BB, BC.... ZA, ZB, ZZ... of course many combinations such as words starting with ZZ won't have any data unless it's a music site and it's ZZ Top! This means it probably won't take up so much memory or bandwidth to send this data during initial page load. Only when the user types the 3rd letter do you need to do any further data lookups/transfers.
You auto-update this data every day, week or whatever depending on site usage and the most popular searches.
I am adding a solution to my question which I figured out after a lot of research.
Problem was:
I was using Ajax to fetch keywords from database every time a user changes text in search box
I was doing a wild card search to match search item within entire strings and not just starting of keywords for ex. "dev" would return "social development", "development" etc
Solution:
I have a fixed array of keywords (200) which is not going to increase exponentially in near future. So, instead of doing complex indexing I am currently sending all keywords in an array.
I am sending this data in an array on page load since it is small. If it becomes large, I will fetch it in background via some ajax in different indexed arrays.
I am using jQuery's Autocomplete widget to do rest of thing for me.
For highlighting search item, I am using a hack by working around __renderItem. (Copied from Stackoverflow. Thanks to that!!)
Code:
function monkeyPatchAutocomplete() { //Hack to color search item
jQuery.ui.autocomplete.prototype._renderItem = function( ul, item) {
var re = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + this.term + ")(?![^<>]*>)(?![^&;]+;)", "gi");
var t = item.label.replace(re,"<span style='font-weight:bold;color:#434343;'>" +
"$&" +
"</span>");
return jQuery( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
}
function getKeywords(){
//Function that returns list of keywords. I am using an array since my data is small.
//This function can be modified to fetch data in whatever way one want.
//I intend to use indexed arrays in future if my data becomes large.
var allKeywords = <?php echo json_encode($allKeywords); ?>;
return allKeywords;
}
jQuery(document).ready(function(){
monkeyPatchAutocomplete();
var CityKeyword = jQuery('#CityKeyword');
CityKeyword.autocomplete({
minLength : 1,
source : getKeywords()
});
});
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']);
}
For practicing reasons I programmed a little Texas Holdem Game in PHP with some JQuery Animations. Every action (bet, fold, check, raise, call) is submitted via a HTML form to a PHP script.
Now unfortunately the user is able to just go back to the first betting round after seeing the whole board and the computer's cards and adjusting his betting structure accordingly by using the back-ubtton of the browser.
Is there a practical way for me to prevent this?
Thanks,
Coffeehouse
PS:
A buttonscript is for example this:
if (isset($_POST['call']) AND $_SESSION['bettingcap'] == 1){
$_SESSION['kapitalspieler'] -= $smallbet; // deduct money from player
$_SESSION['pot'] += $smallbet; // add this to the pot
$_SESSION['bettingcap'] = 0; // After call go to next street, so cap is 0
$_SESSION['buttonmodus']=1; // I want to show only certain buttons
$_SESSION['whichstreet']=$_SESSION['whichstreet']+1; // go to next street
$_SESSION['animateagain']='yes'; // show JQuery Animation
}
You need to invalidate the request. That means one request follows after the other.
You do this by storing all requests of that user in the game.
If a new request is send, it can be only added at the end.
You can create the game in memory by initializing it and the pass in all events from all sides until a specific one.
This model does allow you to prevent cheating as well as re-playing a game like in a view mode of previous games.
00 created game ID:#7575
01 player joined seat:1; ID:#12
02 player joined seat:2; ID:#56
03 player joined seat:3; ID:#87
04 deck shuffled order:the cards order here.
05 ...
So you keep these events and if a new request is send by a user you can check if it is okay with the current situation or not.
Perhaps something like this will work.
<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">
From link
I would like to measure how much time a user spends on my website. It's needed for a community site where you can say: "User X has been spending 1397 minutes here."
After reading some documents about this, I know that there is no perfect way to achieve this. You can't measure the exact time. But I'm looking for an approach which gives a good approximation.
How could you do this? My ideas:
1) Adding 30 seconds to the online time counter on every page view.
2) On every page view, save the current timestamp. On the next view, add the difference between the saved timestamp and the current timestamp to the online time counter.
I use PHP and MySQL if this does matter.
I hope you can help me. Thanks in advance!
This is probably pointless.... what if the user has three tabs open and is "visiting" your site while actually working on the other two tabs? Do you want to count that?
Two factors are working against you -
You can only collect point-in-time statistics (page views), and there's no reasonable way to detect what happened between those points;
Even then, you'd be counting browser window time, not user time; users can easily have multiple tabs open on multiple browser instances simultaneously.
I suspect your best approximation is attributing some average amount of attention time per click and then multiplying. But then you might just as well measure clicks.
Why not just measure what actually can be measured?: referrals, page views, click-throughs, etc.
Collecting and advertising these kinds of numbers is completely in line with the rest of the world of web metrics.
Besides—if someone were to bring up a web page and then, say, go on a two week holiday, how best to account for it?
What you could do is check if a user is active on the page and then send an ajax request to your server every X seconds (would 60 secs be fine?) that a user is active or not on the page.
Then you can use the second method you have mentioned to calculate the time difference between two 'active' timestamps that are not separated by more than one or two intervals. Adding these would give the time spent by the user on your site.
google analytics includes a very powerful event logging/tracking mechanism you can customize and tap into get really good measurements of user behavior - I'd look into that
A very simple solution is to use a hidden iframe that loads a php web page periodically. The loaded web page logs the start time (if it doesn't exist) and the stop time. When the person leaves the page you are left with the time the person first came to the site and the last time they were there. In this case, the timestamp is updated every 3 seconds.
I use files to hold the log information. The filename I use consists of month-day-year ipaddress.htm
Example iframe php code. Put this in yourwebsite/yourAnalyticsiFrameCode.php:
<?php
// get the IP address of the sender
$clientIpAddress=$_SERVER['REMOTE_ADDR'];
$folder = "yourAnalyticsDataFolder";
// Combine the IP address with the current date.
$clientFileRecord=$folder."/".date('d-M-Y')." ".$clientIpAddress;
$startTimeDate = "";
// check to see if the folder to store analytics exists
if (!file_exists($folder))
{
if (!mkdir($folder))
return; // error - just bail
}
if (file_exists($clientFileRecord) )
{
//read the contents of the clientFileRedord
$lines = file($clientFileRecord);
$count = 0;
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line)
{
echo($line);
if ($count == 0)
$startTimeDate = rtrim( $line );
$count++;
}
}
if ($startTimeDate == "")
$startTimeDate = date('H:i:s d-M-Y');
$endTimeDate = date('H:i:s d-M-Y');
// write the start and stop times back out to the file
$file = fopen($clientFileRecord,"w");
fwrite($file,$startTimeDate."\n".$endTimeDate);
fclose($file);
?>
The javascript to periodically reload the iframe in the main web page.:
<!-- Javascript to reload the analytics code -->
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById('AnalyticsID').src = document.getElementById('AnalyticsID').src
// document.frames["AnalyticsID"].location.reload();
}
</script>
The iframe in the main web page looks like this:
<iframe id="AnalyticsID" name="AnalyticsID" src="http://yourwebsite/yourAnalyticsiFrameCode.php" width="1"
height="1" frameborder="0" style="visibility:hidden;display:none">
</iframe>
A very simple way to display the time stamp files:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
Analytics results
<br>
<?php
$folder = "yourAnalyticsDataFolder";
$files1 = scandir($folder);
// Loop through the files
foreach ($files1 as $fn)
{
echo ($fn."<br>\n");
$lines = file($folder."/".$fn);
foreach ($lines as $line_num => $line)
{
echo(" ".$line."<br>\n");
}
echo ("<br>\n <br>");
}
?>
</body>
</html>
You get a results page like this:
22-Mar-2015 104.37.100.30
18:09:03 22-Mar-2015
19:18:53 22-Mar-2015
22-Mar-2015 142.162.20.133
18:10:06 22-Mar-2015
18:10:21 22-Mar-2015
I think client side JavaScript analytics is the solution for this.
You have the google analitycs, piwik, and there also commercials tools in JS that do exactly that.