duanpacan9388 2015-06-18 02:10
浏览 65
已采纳

html表单中的action属性是否会干扰$ _SESSION全局变量中存储的内容?

Suppose, I have two pages: page01.php and page02.php (their code is presented below).

If I leave action attribute in the form on page01.php empty (i.e. action=""), then access page01.php, fill in the form, press submit, then access page02.php - it all works fine (i.e. $_SESSION variable stores the data submitted on page01.php and can be accessed and viewed on page02.php as expected).

However, when I try to make the form send the user to page02.php (by changing the action atrribute to action="page02.php") it looks like the $_SESSION global variable doesn't store data from page01.php.

My question is: does this happen because the user is redirected to page02.php immediately upon submission of form and the code between php tags on page01.php does not get executed?

I'm aware I can use $_GET or $_POST on page02.php to achieve the desired behavior, but I'm just trying to understand the way action attribute and $_SESSION interact. Thank you.

Page01.php:

<html>
<head>
    <title>Page 01</title>      
</head>
<body>
    <h1>Please fill this form</h1>
    <form action="" method="post">
        Name:  <input name="username">
        <input type="submit" value="send">
    </form>

    <?php   
        session_start();
        if(isset($_POST['username'])) {
            $_SESSION['username']=$_POST['username'];
        }
    ?>
</body>

Page02.php:

<html>
<head>
    <title>Page 02</title>      
</head>
<body>
    <h1>Another temporary page is working</h1>
    <?php
        session_start();
        $expectedName = "Bob";
        if($_SESSION['username'] == $expectedName) {
            echo "Welcome, Bob!";
        }
        else {
            echo "Access denied. You are ". $_SESSION['username']  . ", not Bob.";
        }
    ?>
</body> 

展开全部

  • 写回答

1条回答 默认 最新

  • dpe77294 2015-06-18 02:16
    关注

    action attribute is attribute you specify where the script that will need to be run after submitting.

    so if you want user to be redirected after form has been submitted, you use header() function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部