Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Basic PHP Website (2018) Adding a Basic Form Checking the Request Method

How can we access variables after posting?

My form works great! But I tried to get creative and add a step not shown in the lesson.

Instead of Thanks for your email. I'll review it shortly! I wanted it to say Thanks for your email Johnny. I'll review it shortly!.

I tried accessing the variable using $_POST[$name] but i keep getting an error. My code looks like this....

<?php 
     echo "<p>Thanks for your email $_POST[$name]. I'll review it shortly!</p>";
?>

6 Answers

So I managed to find a solution to my question with help of Patricia Hector. It took 2 steps.

STEP 1. Update the redirect by adding a name variable to the header

header("location:suggest.php?status=thanks&name=$name");

STEP 2. Use $_GET[] to retrieve the variable from the address bar

<p>Thanks for the email <?php echo ucwords($_GET['name']);?>! I&rsquo; check out your suggestion shortly!</p>

FULL CODE BELOW:

<?php 

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $details = $_POST['details'];

    $email_body = "<pre>";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Details: " . $details . "\n";
    $email_body .= "</pre>";

    // To Do: Send email
    header("location:suggest.php?status=thanks&name=$name");  
}

$pageTitle = "Suggest a Media Item";
$section = "suggest";

include("inc/header.php"); 
?>


<div class="section page">
    <?php
        if(isset($_GET['status']) && $_GET['status'] == "thanks") {
    ?>
    <div class="wrapper">
        <h1><?php echo $pageTitle;?></h1>
        <p>Thanks for the email <?php echo ucwords($_GET['name']);?>! I&rsquo; check out your suggestion shortly!</p>
    </div>
    <?php } else { ?>
    <div class="wrapper">
        <h1>Suggest a Media Item</h1>
        <p>If you think there is something I&rsquo;m missing, let me know! Complete the form to send me an email.</p>
        <form method="post" action="suggest.php?status=thanks">
            <table>
                <tr>
                    <th><label for="name">Name</label></th>
                    <td><input type="text" name="name" id="name"/></td>
                </tr>
                <tr>
                    <th><label for="email">Email</label></th>
                    <td><input type="text" name="email" id="email"/></td>
                </tr>
                <tr>
                    <th><label for="details">Comments</label></th>
                    <td><textarea name="details" id="details" cols="30" rows="10"></textarea></td>
                </tr>
            </table>
            <input type="submit" value="Send">
        </form>
    </div>
    <?php } ?>
</div>

<?php include("inc/footer.php"); ?>

PS. I am only a student, so if for any reason there are any mistakes, or if this is considered a bad practice please let me know. Suggestions are always welcome!

Patricia Hector
Patricia Hector
42,901 Points

No problem, I'll be happy to help out always I can. You are right, the POST method is more secure than the GET method. If you are sending your user to another page on the action attribute when the form gets submitted, the requested information is transfer on the body of the request, so to access that data on the new page you need to use the global variable $_POST.

On the other hand, if the action attribute of your form is blank or set to the default page, the requested data will be accessible on that page. So you can access the global variable $_POST, do whatever you need with your data and then if needed , redirect the user to any other place, and send the information you wanted to echo out via query string, to access on the new page with the global variable $_GET. I thought this one was the approach you were followed.

As a conclusion, the key of this problem (and my confusion) is what value did you give to the action attribute on your form?

I think your code could look like this:

<!--this is index.php | where your FORM lives-->

<form method = "post" action = "thanks.php">
    <input type = "text" name = "name" />
</form>
#this is thanks.php | where your user is redirected to

<?php 
     echo "<p>Thanks for your email" .  $_POST["name"] . ". I'll review it shortly!</p>";
?>

Hope this helps. Ciao.

Patricia Hector my action on the form is "suggest.php?status=thanks"

Patricia Hector
Patricia Hector
42,901 Points

$_POST is an associative array and needs to be accessed using its associative keys. If the name attribute in your input is name

<input type = "text" name = "name" value = "" />

then in the $_POST array this value should be accessed like this

$_POST["name"];
Patricia Hector
Patricia Hector
42,901 Points

I also recommend you to take a look at $_POST array with

var_dump($_POST);

to see what you are exactly generating once you submit your form. Ciao

I've tried both but not working still. I should mention this is after the page gets redirected. I'm not sure if that makes a difference. Here's my code using var_dump($_POST) It returns an empty array.

<?php
        if( isset($_GET["status"]) && $_GET["status"] == "thanks" )  {
            var_dump($_POST);           
        } else {
?>
Patricia Hector
Patricia Hector
42,901 Points

No, you are right, the $_POST array won't work if you are redirecting, but we can try another approach. Before the redirection, save the $_POST["name"] value in a variable and pass it as a query in the URL you are redirecting your user. Then on the other page, you need to access the $_GET array with the name you gave to your variable and echo the value. Something like this:

/* this is info.php (where users fill the form with their general information)
* imagine the form was already submitted with the method = "post" and action = "info.php"
*/

$name = $_POST["name"];
header("location: thanks.php?name=" . $name );

Now on thanks.php file

/* this is thanks.php*/

$name = $_GET["name"];
echo "Thanks for your email " . $name . ". I'll review it shortly!.";

I'm still learning this, so please forgive me if I'm wrong, but isn't the reason we are using $_POST because it is more secure?

Here is the entire code I have from the lesson so far. It is 3 pages condensed down to 1 using conditional statements.

<?php 

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $details = $_POST['details'];


    // var_dump($_POST);
    $email_body = "<pre>";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Details: " . $details . "\n";
    $email_body .= "</pre>";
    // echo $email_body;

    // To Do: Send email
    header("location:suggest.php?status=thanks");  
}

$pageTitle = "Suggest a Media Item";
$section = "suggest";

include("inc/header.php"); 
?>


<div class="section page">
    <?php
        if(isset($_GET['status']) && $_GET['status'] == "thanks") {
    ?>
    <div class="wrapper">
        <h1><?php echo $pageTitle;?></h1>
        <p>Thanks for the email! I&rsquo; check out your suggestion shortly!</p>
    </div>
    <?php } else { ?>
    <div class="wrapper">
        <h1>Suggest a Media Item</h1>
        <p>If you think there is something I&rsquo;m missing, let me know! Complete the form to send me an email.</p>
        <form method="post" action="suggest.php?status=thanks">
            <table>
                <tr>
                    <th><label for="name">Name</label></th>
                    <td><input type="text" name="name" id="name"/></td>
                </tr>
                <tr>
                    <th><label for="email">Email</label></th>
                    <td><input type="text" name="email" id="email"/></td>
                </tr>
                <tr>
                    <th><label for="details">Comments</label></th>
                    <td><textarea name="details" id="details" cols="30" rows="10"></textarea></td>
                </tr>
            </table>
            <input type="submit" value="Send">
        </form>
    </div>
    <?php } ?>
</div>

<?php include("inc/footer.php"); ?>

Through some research I found another way to accomplish this without using $_GET[] which shows in the address bar. This can also be done by creating a $_SESSION[]. This way we don't have to show the variables in the address bar. Sessions should be started, and then either unset or destroyed. I'm not an expert in sessions and learned this just today. In the example given below I've only started the sessions and haven't ended it. I'd suggest some more research on it. Two youtube tutorial I've found helpful are. If anyone with more experience on this has more insight they can share, please share!

  1. Setting PHP Session: https://www.youtube.com/watch?v=WuZBQ706thI&t=3s
  2. Unsetting PHP Sessions: https://www.youtube.com/watch?v=KdYPi8ublKw&t=167s

MY CODE BELOW (More of what I had in mind with my initial Question)

<?php 

session_start();

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $details = $_POST['details'];

    // Email body variable
    $email_body = "<pre>";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Details: " . $details . "\n";
    $email_body .= "</pre>";

    // Session variables
    $_SESSION["name"] = $name;

    // To Do: Send email
    header("location:suggest.php?status=thanks");  
}


$pageTitle = "Suggest a Media Item";
$section = "suggest";

include("inc/header.php"); 
?>


<div class="section page">
    <?php
        if(isset($_GET['status']) && $_GET['status'] == "thanks") {
    ?>
    <div class="wrapper">
        <h1><?php echo $pageTitle;?></h1>
        <p>Thanks for the email <?php echo ucwords($_SESSION['name']);?>! I&rsquo; check out your suggestion shortly!</p>
    </div>
    <?php } else { ?>
    <div class="wrapper">
        <h1>Suggest a Media Item</h1>
        <p>If you think there is something I&rsquo;m missing, let me know! Complete the form to send me an email.</p>
        <form method="post" action="suggest.php?status=thanks">
            <table>
                <tr>
                    <th><label for="name">Name</label></th>
                    <td><input type="text" name="name" id="name"/></td>
                </tr>
                <tr>
                    <th><label for="email">Email</label></th>
                    <td><input type="text" name="email" id="email"/></td>
                </tr>
                <tr>
                    <th><label for="details">Comments</label></th>
                    <td><textarea name="details" id="details" cols="30" rows="10"></textarea></td>
                </tr>
            </table>
            <input type="submit" value="Send">
        </form>
    </div>
    <?php } ?>
</div>

<?php include("inc/footer.php"); ?>