Can someone help me clean this up and make it more logical? I'm fried right now and can't seem to get a good line of code written :)
I'm trying to capture affiliate id from urls like ?aid=3056677. The idea is IF aff id is set in GET that takes precedence, the session and finally cookie with least. Also, we don't want to set an aff id that does not exist.
Do you know of a more tried and true method of doing this?
session_start(); // start session
// affiliate id
$g_aid = (isset($_GET['aid']) && $_GET['aid'] != '') ? trim($_GET['aid']) : false;
$s_aid = (isset($_SESSION['aid']) && $_SESSION['aid'] != '') ? trim($_SESSION['aid']) : false;
$c_aid = (isset($_COOKIE['aid']) && $_COOKIE['aid'] != '') ? trim($_COOKIE['aid']) : false;
if($g_aid !== false) // use get if set
$aid = $g_aid;
elseif($s_aid !== false) // next use session if get not set
$aid = $s_aid;
elseif($c_aid !== false) // cookie
$aid = $c_aid;
else
$aid = ''; // leave it empty
// if $aid is set is it in the $affiliates array?
//If not use the first key from that array
$aid = (isset($affiliates[$aid])) ? $aid : key($affiliates);
// save it and set it
// (maybe shouldn't be done if already stored?
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
session_start();
// checks if a field is valid
function isValid($aid) {
return (!empty($aid) && trim($aid) != '');
}
// set the affiliate ID
$aid = isValid($_GET['aid']) ? $_GET['aid'] :
isValid($_SESSION['aid']) ? $_SESSION['aid'] :
isValid($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if (!isset($affiliates[$aid])) $aid = key($a);
// save and set
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
Why would you test for session and cookie, in case you have a valid affiliateID from the $_GET array? ==> Make it progressive so that session is only checked, if no GET was found and cookie is only checked if no session was found.
Don't repeat the validation of the affiliateID. ==> Write a validate function and reuse it, you might want to add more rules later on.
Use curly brackets to make your code more readable
$aid or $aff are BAD variable names, $affiliateID instead is a GOOD one! You don't win anything for writing short variables names but you win a lot with writing self-explanatory code.
Bad example, doesn't talk
if (validate($aff))
Good example, talks to you
if (isValid($affiliationID))
So my proposal for change of the core components:
if (isValid($_GET['aid']))
{
$affiliationID = trim($_GET['aid'];
}
else if (isValid($_SESSION['aid']))
{
$affiliationID = trim($_SESSION'aid'];
}
else if (isValid($_COOKIE['aid']))
{
$affiliationID = trim($_COOKIE['aid'];
}
else
{
throw new Exception('No affiliation ID defined');
}
function isValid($affiliationID)
{
if (empty($affiliationID))
{
return false;
}
else
{
return true;
}
}
Thanks guys this is looking better and better. One point that might clarify for you, is that IF an aff id is given in GET it MUST be a valid one that exists before we possibly wipe out someone else's aff id. Money is involved with each transaction and we want an affiliate to get credit for as long as possible.
Regarding empty it's not too useful since whitespace fools it. So unless you trim before using it, I feel it's not accurate enough. So I don't know about the empty for the GET. It's ok for the others because we've already checked them.
Here's what I have so far from your help (does the complex ternary here break when it finds true? I don't want it to keep executing the line):
session_start(); // start session
$aid = !empty($_GET['aid']) ? trim($_GET['aid']) :
!empty($_SESSION['aid']) ? $_SESSION['aid'] :
!empty($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if(!isset($a[$aid])) $aid = key($a);
if(!isset($_SESSION['aid']) || $aid != $_SESSION['aid'])
{
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
}
Related
I'm a completely newbie and trying around in wordpress atm.
I have this function to get first name:
function get_first_name () {
$user_data = get_userdata(get_current_user_id());
return $user_data->first_name;
}
to get the users first name (and display it somewhere afterwards). Now i want to work it like if the user has registered only with his first name it should only get the first name but if he also registered with lastname it should only (!) get last name and ignore the first name.
Can someone help me with this?
A simple ternary statement should do it for you
return $user_data->last_name != '' ? $user_data->last_name : $user_data->first_name;
It is like the longer IF
if ($user_data->last_name != '') {
return $user_data->last_name;
} else {
return $user_data->first_name;
}
I am now using this code for facebook. "https" is active and wordpress site.
<?php
$ref = $_SERVER['HTTP_REFERER'];
if (strpos($ref, 'facebook.com') != false) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
This code works for facebook. I wanted to add twitter, but when I add twitter it doesn't work at all. I tried this.
if (strpos($ref, 'facebook.com', 'twitter.com', 't.co') != false) {
It didn't work that way. If else query or "false" is correct? How can I do it in the simplest way? If the visitor comes from Facebook, Twitter, I don't want to show ads. thanks
strpos() does not check multiple "needles" to look for. You can store them in an array
and iterate over each one individually though:
<?php
$ref = $_SERVER['HTTP_REFERER'];
$sitesWithAdsHidden = [
'facebook.com',
'twitter.com',
't.co',
];
$isHiddenSite = false;
foreach ($sitesWithAdsHidden as $site) {
if (strpos($ref, $site) !== false) {
$isHiddenSite = true;
break;
}
}
if ($isHiddenSite) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
Note that I also changed the strpos comparison to !== because a non-strict check could lead to evaluating to false if the position is actually 0 (the start of the string).
First and foremost, directly from Wikipedia:
"The referrer field is an optional part of the HTTP request sent by the web browser to the web server."
Therefore, you should always check that the Http Referer exists in the request. You can achieve this by using !empty() or isset(), however, for future maintainability, you can also use array_diff and array_keys.
You can then also achieve this without having to iterate over an array using preg_match.
if(!array_diff(['HTTP_REFERER'], array_keys($_SERVER)))
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER']))
// todo: disable adverts
You could also use the null cascading operator to reduce this to one line. Do this if you have no further checks to make from the $_SERVER global variable.
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER'] ?? ''))
// todo: disable adverts
How can I do this easily:
$ipp='/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([\s\:\-]+[0-9]{2,5})/'; // IP Address
preg_match_all($ipp, $line, $matches);
This matches ip:port in multiple formats. I want to define a second criteria like you would do it at a shell script with (A && B) that only match if the port number is NOT "143" exactly. In the future I would might like to extend this with additional ports like "993", "995" etc.
Thanks
Whenever I have to do a task like that, I create a custom function for it so I could modify it, add - remove parameters, if it needs more functions, I create an object. in that case I will just create a function for that tsak.
function check($ip, $against){
$ipChecked = false;
$againstChecked = false;
//pregmatch statement with the ip, if true, the $ipChecked = true;
//pregmatch $against with the ip, if false then $againstChecked = true;
if ($ipchecked === true && $againstChecked===true)
return true;
else
return false;
}
Feel free to customise that function to add any parameter you want
then use it like this:
$ip = '145.254.021';
$against ='143';
$check = check($ip, $against);
if($check === true){
//Insert code here...
}
Did I understood your question well?
I created a bit of code that just condition checks, like below
if ( $pretty_link_url==$_SERVER['HTTP_REFERER']) {
If this condition is true and working, then someone is using their browser with the same URL which is in "$pretty_link_url". "$pretty_link_url" is found in the database, and the if condition runs if they match. Now my question is
Is there anyway to get the result where both url from above $pretty_link_url==$_SERVER['HTTP_REFERER'] the same same as ...
$url = "result";
I don't know if it possible thankyou
I'm not sure what you really want but from your comment I think your looking for:
<?PHP
if ( $pretty_link_url == $_SERVER['HTTP_REFERER']) {
$url = $_SERVER['HTTP_REFERER'];
}else{
$url = ""; // empty or some other value you want to use instead
}
?>
I'm taking a guess at what exactly you're looking for, but is this it?:
$url = '';
if ( $pretty_link_url==$_SERVER['HTTP_REFERER']) {
$url = $_SERVER['HTTP_REFERER'];
}
I have been working on a fancy router/dispatcher class for weeks now trying to decide how I wanted it, I got it perfect IMO except performance is not what I am wanting from it. It uses a route map arrap = /forums/viewthread/:id/:page => 'forums/viewthread/(?\d+)' and loops through my map array with regex to get a match, I am trying to get something better on a high traffic site, here is a start...
$uri = "forum/viewforum/id-522/page-3";
$parts = explode("/", $uri);
$controller = $parts['0'];
$method = $parts['1'];
if($parts['2'] != ''){
$idNumber = $parts['2'];
}
if($parts['3'] != ''){
$pageNumber = $parts['3'];
}
Where I need help is sometime an id and a page will not be present sometime one or the other and sometimes both, so obvioulsy my above code would not cover that, it assumes array item 2 is always the id and 3 is always the page, could someone show me a practical way of matchting up the page and id to a variable only if they exist in the URI and without using regular expressions?
You can see what I have so far on my regular expressions versions in this question Is this a good way to match URI to class/method in PHP for MVC
This seems more extendable:
$parts = explode("/", $uri);
$parts_count=count($parts);
//set default values
$page_info=array('id'=>0,'page'=>0);
for($i=2;$i<$parts_count;$i++) {
if(strpos($parts[$i],'-')!==FALSE) {
list($info_type,$info_val)=explode('-',$parts[$i],2);
if(isset($page_info[$info_type])) {
$page_info[$info_type]=(int)$info_val;
}
}
}
then just use $page_info values. You can easily add other values this way and more levels of '/'.
if ( ! empty($parts['2']))
{
if (strpos($parts['2'], 'id-') !== FALSE)
{
$idNumber = str_replace('id-', '', $parts['2']);
}
elseif (strpos($parts['2'], 'page-') !== FALSE)
{
$pageNumber = str_replace('id-', '', $parts['2']);
}
}
And do the same for $part[3]