简体   繁体   中英

undefined variable + switch issue

i created $ref variable to find referral websites !

i have two problems :

1- when page opening directly i see notice error that show me $ref id undefined

2- i think my switch code is ok , but it's not working !

<?php

$ip = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];


switch ($ref) {
    case $ref == null :
    echo 'null';

    case $ref == 'http://google.com' :
    echo 'google';


}


?>

why i see noticed php error , for undefined variable ?

so how can i get some variable that maybe not generating on all pages

like referral or maybe HTTP_X_FORWARDED_FOR , this variables depends on client request or client network , so they note generating all times

i want to get value of referral or HTTP_X_FORWARDED_FOR so i can't use isset or empty

please help me how can i solve this problem ?

if(isset($_SERVER['HTTP_REFERER'])) {

$ref = $_SERVER['HTTP_REFERER'];
    switch ($ref) {
        case 'http://google.com' :
            echo 'google';
            break;
        default:
            echo 'came from other site than google';
            break;
    }
}
else {
    echo 'null'; //no referer set
}

this is the case syntax in php.

solution of your first problem is use isset

if(isset($_SERVER['HTTP_REFERER']))
{
    $ref = $_SERVER['HTTP_REFERER'];


    switch ($ref) {
        case $ref == null :
        echo 'null';

        case $ref == 'http://google.com' :
        echo 'google';

    }
  }
  else
  {
     echo "Null"; // $_SERVER['HTTP_REFERER'] is not set
  }

Try this,

echo $_SERVER['HTTP_REFERER']; // to know about the REFERER value
if(isset($_SERVER['HTTP_REFERER'])){
  $ref = $_SERVER['HTTP_REFERER'];
  $ref = parse_url($ref);
  $host = $ref['host'];

  switch ($host) {
    case 'google.com' :  
    case 'www.google.com' :     
        echo 'google';
    break;
    default:
         echo 'null';
    }
}else{
      echo "Not a HTTP_REFERER ";
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM