Please wait

$_GET Superglobal Variable

This chapter will focus on working with user-submitted data. Generally speaking, there are 4 steps you'll take when working with user-submitted data.

  1. Retrieve Data: Retrieve the submitted data from the client.
  2. Validation: Check the data to ensure that it meets certain criteria or formats. This can involve checking data types, lengths, and patterns.
  3. Process Request/Throw Error: Based on the validation, decide what to do with the data. If it's valid, you might process it, save it to a database, or send an email. If it's invalid, you might throw an error or request that the user resubmit the form.
  4. Escape/Sanitize Data: Before displaying the data back to the user or inserting it into a database, sanitize or escape it to prevent security issues like SQL injection or Cross-Site Scripting (XSS).

Throughout this chapter, we'll dive deeper into each step. First, we'll start with retrieving data.

HTTP Methods Recap

We talked about HTTP methods in an earlier chapter. Let's quickly recap them.

HTTP methods are standard request types used in the HTTP protocol to perform actions on a given resource. These methods define what action is to be performed on the resource, allowing for clear communication between the client and server.

One of the methods is called GET. The HTTP GET method is used to request data from a specified resource on a server.

Data sent by the GET method goes through the URL, which means that all the name/value pairs are appended to the URL in the request. This data is visible in the URL, and it appears after a question mark (?), separated by ampersands (&). An example URL with GET parameters might look like this:

http://www.example.com/page.php?name=JohnDoe&age=30

Because the data is part of the URL, it's exposed to anyone who has access to the URL, and it has length limitations, as URLs can only be so long. Therefore, the GET method is typically used for non-sensitive data and is suited for tasks like fetching documents or querying data that doesn't change the server's state.

Grabbing Data from a URL

You can grab data from a URL by using the $_GET superglobal array. This array is used to collect data sent via the HTTP GET method, and it automatically parses the query string parameters in the URL.

Here's how it works:

  1. Client Sends GET Request: The client sends an HTTP GET request to a URL that includes query parameters, like http://www.example.com/page.php?name=JohnDoe&age=30.
  2. PHP Interpreter Parses the URL: When the request reaches the server, the PHP interpreter automatically parses the query string (everything after the ?) and populates the $_GET array with the name-value pairs found in the URL.
  3. Accessing the Data in PHP: You can access this data in your PHP script by using the $_GET array and referring to the named keys like this:
$name = $_GET['name']; // JohnDoe
$age = $_GET['age'];   // 30

The PHP interpreter takes care of parsing the URL, so developers can easily access the query parameters without having to manually dissect the URL.

Checking for Missing Data

A common pitfall beginner developers fall into is forgetting to check if data exists, to begin with before using it. Let's say we wanted to output a user's favorite flavor of ice cream.

$flavor = $_GET['flavor'];
echo "My favorite ice cream flavor is {$flavor}.";

In this example, we're expecting the URL to have a query parameter called flavor. If it does, PHP stores the query parameter's value into the $_GET variable, where it can be referenced as flavor. But what if the query parameter is not provided?

If you try to access a value from the $_GET variable that doesn't exist, PHP will produce an error saying "Undefined index". This is PHP's way of saying, "Hey, you're trying to find something in $_GET that isn't there".

To avoid this, PHP has a function called isset(). isset() is like a question you ask PHP: "Is this thing set? Does it exist?" If it does exist, isset() returns true. If not, it returns false.

We can use isset() together with a ternary operator to avoid the "Undefined index" error. The ternary operator is a shorthand way of writing an if...else statement. It's like a mini decision-maker. Here's how you use it:

$flavor = isset($_GET['flavor']) ? $_GET['flavor'] : 'vanilla';
echo "My favorite ice cream flavor is {$flavor}.";

This line of code can be read as: "If $_GET['flavor'] exists (is set), then assign its value to the variable $flavor. If $_GET['flavor'] does not exist (is not set), then assign the string 'vanilla' to the variable $flavor".

So in simpler terms, this line of code helps us avoid errors by providing a default value when the expected value ($_GET['flavor']) isn't available in the $_GET variable.

Null Coalescing operator

Alternatively, you can use the ?? operator (null-coalescing operator).

$flavor = $_GET['flavor'] ?? 'vanilla';
echo "My favorite ice cream flavor is {$flavor}.";

This line of code can be understood as: "If $_GET['flavor'] is set and is not NULL, assign its value to $flavor. If $_GET['flavor'] is not set or is NULL, assign 'vanilla' to $flavor."

The null coalescing operator provides a more concise way to achieve the same result as the ternary operator with isset(), making the code cleaner and more readable.

Key Takeaways

  • The GET method is used to request data from a specified resource on a server.
  • In PHP, you can access data sent via the GET method using the $_GET superglobal array, which automatically parses the URL parameters.
  • If you attempt to access an undefined index in the $_GET array, PHP will produce a notice error. You can handle this gracefully using techniques like the null coalescing operator (??).
  • The GET method is often used for things like navigation, search queries, or any situation where you want to retrieve data without changing anything on the server.

Comments

Please read this before commenting