简体   繁体   English

基于URL变量的PHP重定向

[英]php redirect based on url variable

I want to create a URL redirect based on a URL variable. 我想基于URL变量创建URL重定向。

so, if student%20gender (student gender) is male then go to www.one.com, if female, go to www.two.com. 因此,如果Student%20gender(学生性别)是男性,请访问www.one.com,如果是女性,请访问www.two.com。

couldn't figure this one out yet. 还不知道这个。 any help? 有什么帮助吗?

Question could use a little bit of a better explanation. 问题可以使用更好的解释。 Do you mean that someone is going to http://www.yoursite.com/yourscript.php?student%20gender=male and you want them to be redirected to http://www.one.com ? 您是说有人要访问http://www.yoursite.com/yourscript.php?student%20gender=male并且您希望他们重定向到http://www.one.com吗?

If this is the case, PHP has a built in variable known as $_GET which stores the values listed after a ? 在这种情况下,PHP具有一个内置变量$_GET ,该变量存储在?之后列出的值? in a URL. 在网址中。 So in the above example, we'd see: 因此,在上面的示例中,我们将看到:

$_GET['student gender'] = male;

You can use this to access any number of parameters separated by & 您可以使用它来访问由&分隔的任意数量的参数

So the URL http://www.site.com/index.php?val1=a&val2=b&val3=c would give us: 因此,URL http://www.site.com/index.php?val1=a&val2=b&val3=c将为我们提供:

$_GET['val1'] = a;
$_GET['val2'] = b;
$_GET['val3'] = c;

After this, to do a redirect in PHP the easiest way is to send a Location: header. 此后,要在PHP中进行重定向,最简单的方法是发送Location:标头。 This is done like so: 这样做是这样的:

<?php
header("Location: www.newsite.com");
?>

Combining this with our $_GET variable and some simple logic: 结合我们的$_GET变量和一些简单的逻辑:

<?php
    if($_GET['student gender'] == 'male'){
        header("Location: www.one.com");
        die();
    } else {
        header("Location: www.two.com");
        die();
    }
?>
$var = $_GET['yourvar'];

if($var == 'one'){
    header("Location: http://www.one.com/");
}else if ($var == 'two'){
    header("Location: http://www.two.com/");
}

then do http://www.yoururl.com?yourvar=one 然后执行http://www.yoururl.com?yourvar=one

You also have to make sure you look at the security aspects here, the best way yo accomplish this is 您还必须确保在此处了解安全方面,实现此目标的最佳方法是

$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender'] : false;

switch($gender)
{
    default: //The default action
        //Send back to the gender select form
    break;

    case 'male':
        //Send to male site!
    break;

    case 'female':
        //Send to female site!
    break;
}

This should be sufficient, but please never use $_X['?'] in functions that execute either shell or database queries without sanitation. 这应该足够了,但是请不要在无条件地执行shell或数据库查询的函数中使用$_X['?']

Note: _X being (GET,POST,REQUEST,FILES) 注意: _X为(GET,POST,REQUEST,FILES)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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