首页 > 解决方案 > 在 PHP 联系表单中重定向

问题描述

我在 wordpress 上构建了一个 PHP 联系表单,该表单根据用户选择的区域重定向用户。

我使用“www.google.com”作为测试网址。

但是,表单被重定向到我在 WP 上构建的自定义主题页面。

我哪里错了?

请在下面找到代码:

<html>
    <head>
        <title> Meal Planner </title>
    </head>
    <body>
    <?php
    function checkregion($Region)
    {
        SWITCH ($Region) {
            case "North":
                header('location:https://www.google.com/');
                break;
            case "South":
                header('location:https://www.google.com/');
                break;
            case "East":
                header('location:https://www.google.com/');
                break;
            case "West":
                header('location: https://www.google.com/');
                break;
        }
    }

    checkregion($Region);
    ?>
        <form action="<?= get_template_directory_uri() ?>/custompage1.php " method="POST">
            <p>Name</p> <input type="text" name="name">
            <p>Email</p> <input type="text" name="email">
            <p>Phone</p> <input type="text" name="phone">
            <p>Dropdown Box</p>
            <select name="Region" size="1">
                <option value="North">North</option>
                <option value="South">South</option>
                <option value="East">East</option>
                <option value="West">West</option>
            </select>
            <br/>
            <input type="submit" value="SUBMIT"><input type="reset" value="CLEAR">
        </form>
    </body>
</html>

标签: phphtmlredirectcontact-form

解决方案


checkRegion要在与表单相同的页面上调用您的函数,除非此页面是customepage1.php您需要从表单中删除操作并将 POST 变量Region作为输入参数传递给您的函数。当您调用header函数时,您应该在生成任何 HTML 内容之前调用此函数(除非您已output buffering启用)

<?php

    function checkregion( $Region ) {
        switch ($Region) {
            case 'North': header('Location: https://www.google.com/'); break;
            case 'South': header('Location: https://www.google.com/'); break;
            case 'East': header('Location: https://www.google.com/'); break;
            case 'West': header('Location: https://www.google.com/'); break;
        }
    }
    if( !empty( $_POST['Region'] ) ) checkregion( $_POST['Region'] );
?>
<html>
    <head>
        <title> Meal Planner </title>
    </head>
    <body>
        <form method='POST'>

            <p>Name</p> <input type='text' name='name'>
            <p>Email</p> <input type='text' name='email'>
            <p>Phone</p> <input type='text' name='phone'>
            <p>Dropdown Box</p>

            <select name='Region' size='1'>
                <option value='North'>North
                <option value='South'>South
                <option value='East'>East
                <option value='West'>West
            </select>
            <br />
            <input type='submit' value='SUBMIT'><input type='reset' value='CLEAR'>
        </form>
    </body>
</html>

推荐阅读