简体   繁体   English

PHP多重重定向

[英]PHP multiple redirects

I have a $_POST array with a single variable 'listing_type'. 我有一个带有单个变量“ listing_type”的$ _POST数组。 The form submits to a page containing the code below which redirects them to another page with more forms dependent on their initial choice. 表单提交到包含以下代码的页面,该代码将其重定向到具有更多表单(取决于其最初选择)的另一个页面。 Is there a slicker way to do this? 有一种轻松的方法可以做到这一点吗? It works fine but feels clunky... 它工作正常,但感觉笨拙...

<?php // listing-type.php
if ((isset($_POST['listing_type'])) && (!empty($_POST['listing_type']))) {

    switch($_POST['listing_type']) {
        case "1":
            $url = "events/new-event.php";
            break;
        case "2":
            $url = "restaurants/new-restaurant.php";
            break;
        case "3":
            $url = "bars/new-bar.php";
            break;
        case "4":
            $url = "attractions/new-attraction.php";
            break;  
    }
header("Location: $url"); // Perform redirect to given new listing page
}
else {  // Redirect to homepage if no usuable listing_type data from form
    $url = "index.php";
    header("Location: $url");
}

Here's an alternate using an array: 这是使用数组的替代方法:

$urls = array("index.php",
              "events/new-event.php", 
              "restaurants/new-restaurant.php",
              "bars/new-bar.php",
              "attractions/new-attraction.php",);

$url = $urls[!empty($_POST['listing_type']) ? $_POST['listing_type'] : 0];
header("Location: $url"); // Perform redirect to given new listing page
exit;

Many combinations of the above. 以上的许多组合。 Be advised that you don't need empty and isset on the same variable as in your code. 请注意,您不需要为empty ,而是将isset与代码中的变量相同。 empty checks for both. 两者都empty检查。

It's fine except there is no need to have two location calls, and you don't need the else: 很好,除了不需要两个位置调用,并且您不需要else:

$url = "index.php";
if ((isset($_POST['listing_type'])) && (!empty($_POST['listing_type']))) {
    // Switch statement
}

header("Location: $url");

Yes, you can do it. 是的,您可以做到。 I think is a good way, you can improving your code a litle bit but is a good way. 我认为这是一个好方法,您可以稍微改进一下代码,但这是一个好方法。

Anyway, I think if you can do it this one with js during sending the form, o perhaps in you html code, you don't have to make a redirection and don't spent time, improving the speed of your website. 无论如何,我认为如果您可以在发送表单时使用js做到这一点,或者在您的html代码中,您不必进行重定向,也无需花费时间,从而可以提高网站的速度。

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

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