2015-04-06 83 views
2

我有2个页面(a.php,b.php)会将获取变量(变量名称为状态)发送到c.php。

而且我得到的GET变量c.php

<?php 
$status=$_GET['status'] 
?> 

而且我想我能为$状态不同的动作,这意味着如果$状态来形式a.php只会,我可以做一些事情,如果$ status来自b.php,我可以做不同的胜利。

if($status is come form a.php){ 
    // some action 

} 
elseif($status is come form b.php){ 
    // some action 

} 

现在的问题是如何识别到$状态是从哪里来的? 我知道$_SERVER在php中的变量可以帮助我识别,但是哪个变量是最好的解决方案?

+0

添加另一个'$ _GET'值来标记它来自哪里或者为每个页面传递不同的'status'值... – cmorrissey

回答

3

只需在两页上添加另一个变量$_GET['sender'];(A & B)以验证哪一个正在发送数据。

然后执行:

if($_GET['sender'] == "A"){ 

} 
elseif($_GET['sender'] == "B"){ 

} 
+0

like a.php?status ='something'&sender = A? – paul0080

+0

是的!但它在'c.php?status ='something'&sender = A' –

+0

这是工作,谢谢你的回答。 – paul0080

1

最近,我有这个确切的问题及其几个方法可解。事实上不只是一对夫妇。

选项1 可以使用$ _ SERVER [“HTTP_REFERRER”],但每个文档是客户依赖,而不是调用客户发送一个请求,以便它应被视为不可靠的。正如Darkbee在评论中指出的那样,它也有安全缺陷。

现在在我的情况。

选项2 - 隐藏字段或图像

<form action="somepage.php"> 
    <input type="hidden" name="option1_name1" value="Arbitary value" /> 
    <input type="image" name="option1_name1" value="Arbitary value" /> 
</form> 

选择3个独特的名字 - 在所有形式的名称相同,但设定不同的值。

<form action="somepage.php"> 
    <input type="hidden" name="input_name1" value="unique value" /> 
    <input type="image" name="input_name2" value="unique value" /> 
</form> 

<?php 

    $test = $_POST; 
    // just for test here. you need to process the post var 
    // to ensure its safe for your code. 

    // Used with option 2 
    // NOTE: unique names per form on both input or submit will 
    // lead to this unwieldy if else if setup. 

    if (!empty($test['option1_name1'])) { 
     // do this 
    } else if (!empty($test['option1_name2'])) { 
     // do that 
    } else { 
     // do the other 
    } 


    // Used with option 3 
    // By setting all the form input names the same and setting 
    // unique values instead you just check the value. 
    // choose the input name you want to check the value of. 

    if (!empty($test['input_name1'])) { 

     switch ($test['input_name1']) { 

      case 'some value': 

        // do your thing 
       break; 
      case 'some other': 

        // do this thing 
       break; 
      default: 
        //do the other 
       break; 
     } 

     } 

两种用法都有各自的好处,如果你在一个文件中有大块,如果否则,如果可能会中将优先选择,你可以很容易地找到每个部分,但如果你的代码是一个小的块,然后交换机将它更易于阅读。

+1

只是一个注释:引用者可以被伪造,并且不应该被信任以进行安全检查 – DarkBee

+0

感谢您评论darkbee,是的,它不应该用于验证页面作为独立提交的位置。 – Chris