未定义的变量+开关问题

时间:2014-01-23 11:48:49

标签: php variables

我创建了$ ref变量来查找推荐网站!

我有两个问题:

1-当直接打开页面时,我看到通知错误,显示$ ref id undefined

2-我认为我的开关代码没问题,但它无法正常工作!

<?php

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


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

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


}


?>

为什么我看到注意到php错误,对于未定义的变量?

那么如何才能得到一些可能不会在所有页面上生成的变量

就像推荐或者HTTP_X_FORWARDED_FOR一样,这些变量取决于客户端请求或客户端网络,所以他们注意到所有时间生成

我希望获得推荐或HTTP_X_FORWARDED_FOR的价值,因此我无法使用issetempty

请帮助我如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

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
}

这是php中的案例语法。

答案 1 :(得分:0)

第一个问题的解决方案是使用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
  }

答案 2 :(得分:0)

试试这个,

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 ";
 }
相关问题