Php session post request

deltabluejay / php_session_tutorial.md

PHP elephant

HTTP, or HyperText Transfer Protocol, is the protocol that web browsers use to fetch content from a website and display it to you. If you’re not familiar, a protocol is a predefined set of rules for communication between devices- in other words, they define how computers talk to one another. However, HTTP is a stateless protocol, which means that it has no memory of the past. If you visit a website, your computer will reach out to the web server and request a web page, but after that, the web server keeps no record of who you are or what you do on the site. That means that if you enter any information on that website, login, or otherwise interact with it, that information will disappear as soon as you navigate to another page. This is crucial to allowing web servers to serve a huge volume of people because the server doesn’t have to constantly keep track of who is using the website and what they’re doing. However, when you want to preserve the data that a user gives to the website, this «feature» becomes a problem.

For example, say you are on an online shopping site and decide to add an item to your cart on the item.php page. With just HTTP, when you decide to check your cart at cart.php , you’ll find that all the items in your cart have disappeared. None of it has been saved because HTTP is stateless.

This is where sessions come in. Session data is stored on the server (a.k.a. server-side) and is associated with a session ID given to your web browser. By default, session data persists until the user closes their browser. Thus, until that point or the specified expiration date is reached, state will be maintained. So, how do we implement it?

Читайте также:  Html ожидание загрузки страницы

Before I jump in to the instructions, I’m going to assume you already have a few things set up on your computer:

  • a web server to run your PHP files on (there are tons of other tutorials on this out there, just web search something like «how to set up a PHP web server»)
  • a text editor or IDE to edit your PHP files (I recommend Visual Studio Code)
  • a web browser (if you’re reading this, you’re probably good 🙂 )

First things first: let’s create a basic PHP file to work with. Create a new file named index.php on your server and copy and paste the following code into it:

 # nothing here for right now (see Step 2) ?> > html lang pl-s">en"> head> meta charset pl-s">utf-8" /> meta name pl-s">viewport" content pl-s">width=device-width, initial-scale=1.0" /> head> body> form action pl-s">index.php" method pl-s">POST"> input name pl-s">submission" type pl-s">text">br> button>Submit!button> form>  # If 'submission' is set in the POST request body. if (isset($_POST['submission'])) < # then `echo` (print) its value onto the page echo "Submission: ".$_POST['submission']; > ?> body> html>

This code creates a simple text box and button. When you click the button, it will send a POST request to index.php . The body of the POST request contains the value you wrote in the text box. Then, the page will refresh, and since the submission parameter has now been specified in the POST request ( isset($_POST[‘submission’]) returns true), your input will be printed onto the page beneath the button using PHP’s echo function.

What the page looks like on load

submission demo 1

Entering a value into the input box

submission demo 2

After clicking the button.

submission demo 3

Here is what the body of our POST request looks like. You can see the text that I put in the input box in the Form Data section on the right.

POST demo 1

You might notice that if you close the page and open your site again in a new tab (not your browser’s feature to reopen the last closed tab), the message displayed underneath the button is gone. As explained in the introduction, HTTP on its own does nothing to save information you input, so once you navigate away from the page, any data you provided will disappear.

Step 2: Let’s create a session!

Now that we have the framework for a basic PHP page, let’s create a session. Add this code to the top of your index.php file, inside the first PHP tag (which should currently be empty except for a comment):

session_start(); # this starts our PHP session if (isset($_POST['submission'])) < # create a session array key named `submission` equal to the value of the POST request `submission` parameter $_SESSION['submission'] = $_POST['submission']; >

With this code, every time the page receives a POST request with the submission parameter, we take that value and store it in a session variable of the same name. Now that we have our session variable, we need to display its value on the page. To do that, in the second PHP tag (underneath the form element), modify your code to look like this:

# If the `submission` session variable is set. if (isset($_SESSION['submission'])) < # then `echo` (print) its value onto the page echo "Submission: ".$_SESSION['submission']; >

Similar to the previous version of our code, when the page loads, if $_SESSION[‘submission’] has been set, we retrieve its value and embed it in the page underneath the button.

Now that we’re finished with the changes, your code should now look like this:

 session_start(); # this starts our PHP session if (isset($_POST['submission'])) < # create a session array key named `submission` equal to the value of the POST request `submission` parameter $_SESSION['submission'] = $_POST['submission']; > ?> > html lang pl-s">en"> head> meta charset pl-s">utf-8" /> meta name pl-s">viewport" content pl-s">width=device-width, initial-scale=1.0" /> head> body> form action pl-s">index.php" method pl-s">POST"> input name pl-s">submission" type pl-s">text">br> button>Submit!button> form>  # If the `submission` session variable is set. if (isset($_SESSION['submission'])) < # then `echo` (print) its value onto the page echo "Submission: ".$_SESSION['submission']; > ?> body> html>

Now, if you close and reopen the tab like before, you’ll see that your message is still there!

The message remains even after closing and revisiting the site

session demo 1

We can verify that our site is in fact using a session by using the browser tools. To open the browser tools, you can either right click somewhere in the white space of your website and then click on Inspect or use your browser’s menu system to find the Developer Tools option. On Chrome and Firefox, Developer Tools can be found by clicking the three dots or three lines on the right side of the browser window, then More Tools , then Developer Tools . What you do next will depend on what browser you’re using- I’ll provide instructions for both Chrome and Firefox, but the process should be similar for other browsers. Once you have the browser tools open, if you’re on Chrome, click on the Application tab at the top of the tools window (you may have to click on the two little arrows on the right of the tool tab bar to see it). If you’re on Firefox, click on the Storage tab. Then, for both browsers, find the Cookies dropdown on the left side and expand it. You should see a cookie named PHPSESSID .

Here’s what it looks like in Chrome:

chrome session

And here’s what it looks like in Firefox:

firefox session

As its name suggests, this cookie stores our Session ID. The Session ID is what identifies the browser to the web server so it can link the user to their respective session data. In our code, session_start() begins our session and assigns us an ID, or, if one is already active, resumes the session with the same ID if one is already active.

Step 3: More ways to manipulate sessions

Now that we’ve sucessfully created and accessed session data using PHP, what else can we do with sessions? PHP offers many other methods to view and manipulate session data. I’ll explain just a few of them here.

unset($var) and session_unset()

unset($var) will delete the session variable you pass into it. If you wish to delete all session variables, use session_unset() . These can be useful if you no longer need a session variable anymore.

session_destroy() completely destroys the session. This is different from session_unset() because it destroys all data associated with the session, meaning you’ll have to call session_start() to use session variables again.

session_name($name) returns the name of the session, and if $name is specified, it also sets a new name for the session (while still returning the old name). The name shows up as the name of the cookie we looked at earlier using the browser developer tools (by default, it is PHPSESSID ). This is particularly important if you want to have two sessions on the same domain- without renaming at least one of them, they will conflict with each other.

Here you can see that I changed the name from PHPSESSID to mysession

Session name

There are many more ways to work with PHP sessions than just these, but there are far too many to list them all here. If you want to learn more, I suggest checking out some of the resources below.

  • https://www.php.net/manual/en/book.session.php
    • The official documentation for PHP sessions. Provides great documentation of all the functionalities associated with sessions. However, it doesn’t always provide great examples on how to use it.
    • A great resource by W3Schools for an overview of PHP sessions. Explains how the basics of how to make and use a session and provides example code, but it does not go into very much depth.
    • A great tutorial on using PHP sessions that is similar to this tutorial. Formatted as a walkthrough so it is easy to follow.
    • A resource from GeeksForGeeks that is similar to the one by W3Schools, but it also explains why sessions can be better than cookies.

    Источник

Оцените статью