SITERAW

Passing Data to Another Page

Do you know what a URL is? It stands for Uniform Resource Locator — in other words, it's how web addresses are written. Every address you see at the top of your browser, like https://www.siteraw.com, is a URL.

Now, I know you probably don't spend your time staring at URLs (you've got better things to do!), but I bet you've noticed some pretty long ones now and then, full of weird characters. For example, after running a search on a site, the address bar might show something like: https://www.siteraw.com/search?q=siteraw.

The part that comes after the question mark in that URL? That's data being passed from one page to another. Let's dig into how that works!

Sending Parameters Through the URL

Earlier, I said that URLs can be used to pass information around. But how does that actually work?

Building a URL to Send Parameters

Let's imagine your website is called siteraw.com and you've got a PHP page called search (like in the intro). To reach that page, you'd use the URL:

https://www.siteraw.com/search

So far, nothing new. What I want to show you now is how to send information to the search page. To do that, we're going to add some data to the end of the URL, like this:

https://www.siteraw.com/search?q=siteraw

What you see after the question mark is a parameter that's being sent to the PHP page. The page can then retrieve that info as a variable. Let's break down the URL:

SITE/PAGE?PARAMETER=VALUE
https://www.siteraw.com/search?q=siteraw

The question mark separates the page name from the parameters. After that, the parameters (or arguments) are written in the format name=value and separated with an ampersand (&) if there are several.

Can we include as many parameters as we want?

In theory, yes — just separate them with &. You could see a URL like this:

hello.php?param1=value1&param2=value2&param3=value3&param4=value4 [...]

The only real limit is the length of the URL. Generally, it's best to stay under 256 characters, though some browsers can handle longer ones. But yeah — you're not gonna fit a whole novel in a URL. 😉

Creating a Link with Parameters

Now that we know how it works, we can create HTML links that go from one page to another and send parameters in the process.

Let's say your site has two files:

  • index.php (the homepage)
  • hello.php

We want to create a link from index.php that leads to hello.php and sends some info along in the URL.

Specifically, two parameters: lastName and firstName, which will contain the user's last and first names.

To do this, open index.php (since that's where the link will be), and insert something like this:

<a href="hello.php?lastName=Smith&firstName=John">Say Hello!</a>

To make the code a bit "cleaner," the & can be written as & inside the link. It has nothing to do with PHP — it's just an HTML thing. Technically, you're supposed to use & in the source code. I'm not doing it here because who cares 😄 — but it's a good habit to form if you want valid HTML.

This link calls hello.php and sends it two parameters:

  • lastName: Smith
  • firstName: John

You've probably guessed where we're going with this — we're calling a page called hello.php that will say "Hello" to the person whose name was passed in the URL.

So how do we retrieve that info in hello.php?

Let's find out. :)

Retrieving Parameters in PHP

Now we know how to form links that send parameters to another page by tacking them onto the end of the URL.

Let's turn our attention to the page that receives those parameters. In our case, that's hello.php. This page will automatically have access to a special array called $_GET. It's an associative array (remember those from the array chapter?) where the keys are the names of the parameters passed in the URL.

Let's revisit our example to make things clear. We created a link to: hello.php?lastName=Smith&firstName=John

That means we'll have access to these variables:

NameValue
$_GET['lastName']Smith
$_GET['firstName']John

We can use these values however we want: process them, display them, whatever. Let's start simple and just display them.

Create a new PHP file called hello.php and add this code:

<p>Hello <?php echo $_GET['firstName']; ?>!</p>

Of course, in a real web page, we'd include all the standard HTML stuff — doctype, <head>, etc. I'm skipping that to keep it simple. The page won't look great (and it definitely won't pass W3C validation), but that's not what we're here for. This is just for testing.

In this case, we're displaying the first name that was sent via the URL. Naturally, we also have access to the last name. So we can display both like this:

<p>Hello <?php echo $_GET['firstName'] . ' ' . $_GET['lastName']; ?>!</p>

As you can see, I threw in a little concatenation like we learned earlier. Nothing fancy — we're just printing two values from the $_GET array. Super straightforward. The only new thing here is that we're pulling values from the URL using this special $_GET array.

Here's what the result looks like:

Hello John Smith!

You should definitely try it on your own to make sure everything clicks.

Never Trust Incoming Data

There's no way I can wrap up this chapter without giving you a proper warning about the dangers that lie in wait for every aspiring webmaster — yes, that includes you! We're going to discover something very important: you should NEVER trust variables passed from one page to another, like the $_GET variable we're working with here.

Okay, I'll admit it — the goal of this section is to scare you a little. Not enough PHP developers are aware of the risks and potential security holes they might face, and that can seriously endanger their website! Yes, I'm being dramatic. Yes, I want you to feel (a little) alarmed! But don't worry — I'll walk you through everything you need to know to stay safe. 😉

What really matters is that you start thinking about these issues right now — not later — especially when you're dealing with parameters received from users.

Everyone Can Mess With URLs

If you've been testing the previous examples on your own machine, you probably saw a URL like this:

http://localhost/siteraw/hello.php?lastName=Smith&firstName=John

And sure enough, the page tells you: "Hello John Smith!" But if you're even slightly curious, you might feel tempted to tweak those parameters directly in the address bar.

You Can Easily Change URL Parameters in Your Browser

Try modifying the URL like this:

http://localhost/siteraw/hello.php?lastName=Smith&firstName=Mark

As you can see, it works! Anyone can change the URL and put whatever they want in there — just by editing the address bar in their browser.

So what's the big deal? Isn't it kind of nice if users can tweak the URL to have the site greet them by their actual name?

Well, maybe — but that's not the point. What this shows us is: you cannot trust the data you receive. Any visitor can change it. Back in index.php, I made a link to greet John Smith, but the page hello.php won't necessarily show "Hello John Smith!" because anyone can tamper with the URL.

Handy Security Measures

Let's try some more devious URL tricks and figure out how to prevent the problems they could cause.

Checking if a Parameter Exists

Let's take it a step further. What's stopping the visitor from removing all parameters from the URL? They could simply go to:

http://localhost/siteraw/hello.php

What does hello.php display now? Try it out! You'll probably get something like:

Hello
Notice: Undefined index: firstName in \www\siteraw\hello.php on line 9
Notice: Undefined index: lastName in \www\siteraw\hello.php on line 9

What happened? We tried to access $_GET['firstName'] and $_GET['lastName'], but since they were removed from the URL, those variables were never created. So they don't exist! PHP gives us a warning that we're trying to use array elements that don't exist — hence the "Undefined index" messages.

To fix this, we can use a handy little function: isset(). This checks whether a variable exists. We'll use it to show a specific message if the first name or last name is missing.

<?php
if (isset($_GET['firstName']) AND isset($_GET['lastName'])) // We have both names
{
    echo 'Hello ' . $_GET['firstName'] . ' ' . $_GET['lastName'] . '!';
}
else // Missing parameters, warn the user
{
    echo 'You need to provide a first name and a last name!';
}
?>

What does this code do? It checks whether $_GET['firstName'] and $_GET['lastName'] exist. If they do, we greet the user. If either (or both) are missing, we display an error message: "You need to provide a first name and a last name!"

Try loading hello.php without any parameters now. You'll see — it gracefully handles the case where the user removed them from the URL. 🙂

Is it really worth bothering with this? I mean, I never mess around with my URLs, and I doubt my visitors do either!

Yes, yes — it's absolutely worth it. You have to prepare for the possibility that the parameters you expect may not be there.

Remember what I told you? Never trust the user. Sooner or later, someone will come along and try to mess with your URL just to see what happens. Your site needs to be ready for that.

And by "user" I don't necessarily mean a human. Most of the bots crawling the web looking for vulnerabilities are automated scripts. The person who wrote the bot might not even remember doing it! (Not all bots are bad, by the way — some are just indexing content, like search engine crawlers.)

In our example, nothing terrible happened — we just got some error messages. But once your website gets more complex, this kind of sloppiness can lead to serious problems.

Validating Parameter Values

Let's go even further with our sneaky URL experiments. We'll tweak the code to handle a new parameter: how many times the greeting should be repeated. So the URL would now look like this:

hello.php?lastName=Smith&firstName=John&repeat=7

The repeat parameter defines how many times the greeting should appear on the page. Can you adjust our code to repeat the greeting that many times? Here's my proposed solution:

<?php
if (isset($_GET['firstName']) AND isset($_GET['lastName']) AND isset($_GET['repeat']))
{
    for ($i = 0 ; $i < $_GET['repeat'] ; $i++)
    {
        echo 'Hello ' . $_GET['firstName'] . ' ' . $_GET['lastName'] . '!<br />';
    }
}
else
{
   echo 'You need to provide a first name, a last name, and a repetition count!';
}
?>

Here we're also checking that repeat exists (isset($_GET['repeat'])). If all the parameters are there, we run a loop (I picked a for loop, but you could also use while). The loop increments a little variable $i to repeat the welcome message as many times as requested.

The result? If you go to:

http://localhost/siteraw/hello.php?lastName=Smith&firstName=John&repeat=7

You'll see the greeting seven times:

Hello John Smith!
Hello John Smith!
Hello John Smith!
Hello John Smith!
Hello John Smith!
Hello John Smith!
Hello John Smith!

Nice! Our page now repeats the greeting, and the number of repetitions is customizable via the URL. Great.

Now... let's get into villain mode. Be mean. Be sneaky. What kind of mischief could someone cause just by tweaking the URL?

I've got one! Let's enter a ridiculously large number for the repetition count — say, 3984986545665159. PHP will loop like crazy, and your computer might struggle to handle that much work. 😈

That's one possibility.

http://localhost/siteraw/hello.php?lastName=Smith&firstName=John&repeat=3984986545665159

Worried about trying it? Don't be — your computer won't catch fire or anything. But it will start gobbling up memory to display all those greetings, and chances are PHP will hit its execution limit and stop. Or if it does finish, your page will be stuffed to the brim with "Hello John Smith!"

Terrifying! So how do we stop this?

By being clever — and cautious. Here's what you should plan for:

What if the number the user sends isn't reasonable?

  • For example, anything above 100 might be too much, so we should reject it.
  • Also, what happens if they request -4 repetitions? That doesn't make sense either. The number should be at least 1.

What if the value isn't even a number? Nothing stops users from replacing repeat with text!

  • What happens if they go to hello.php?lastName=Smith&firstName=John&repeat=Frog? That should definitely be rejected. "Frog" doesn't make sense — we want a positive integer.
  • What if it's repeat=true? That's no good either — we want a number, not a boolean.

To solve all this, we need to:

  • Make sure repeat actually contains a number.
  • Then check that this number falls within a reasonable range (e.g., between 1 and 100).

One good way to make sure it's a number is to force a type conversion to integer (called "casting"). It's a new concept, but super easy to grasp. Look at this:

<?php
$_GET['repeat'] = (int) $_GET['repeat'];
?>

Read it right to left. The (int) is like a conversion pipe. Whatever passes through comes out as an integer.

If the value is already an integer (e.g., 14), it stays the same. But if it's something else (like "frog"), PHP tries to convert it — and ends up with 0.

So after this line runs, $_GET['repeat'] is guaranteed to be an integer. All we have to do now is check that it's between 1 and 100, using a basic condition like you've done before. 😉

Here's the final, secure version of our code that handles every edge case and protects you from any sneaky user behavior:

<?php
if (isset($_GET['firstName']) AND isset($_GET['lastName']) AND isset($_GET['repeat']))
{
    // 1: Force conversion to integer
    $_GET['repeat'] = (int) $_GET['repeat'];

// 2: Only allow values between 1 and 100 if ($_GET['repeat'] >= 1 AND $_GET['repeat'] <= 100) { for ($i = 0 ; $i < $_GET['repeat'] ; $i++) { echo 'Hello ' . $_GET['firstName'] . ' ' . $_GET['lastName'] . '!<br />'; } } } else { echo 'You need to provide a first name, a last name, and a repetition count!'; } ?>

Yes, it's a lot of conditions for something that started off so simple. But it had to be done. You always need to be this careful — check for:

  • The presence of all expected parameters.
  • Whether the values are valid and fall within a sensible range.

Keep that in mind, and you'll be just fine. 🙂

We haven't covered all the risks that come with user input yet. This is just a first look to help you understand the problem. In the next chapter, we'll go even deeper. Yes, it's a bit tricky, but trust me — it's really important!

Using URL parameters is simple: you just grab them from the $_GET array. That should've been pretty straightforward in the first half of this chapter.

But I really wanted to hammer home one thing: you must be vigilant when dealing with user-editable data. Never trust it. As programmers like to say: Never trust user input. Go ahead and tape that to your wall right now. Too many beginner devs have blindly trusted their users ("Come on, no one's going to type 'frog' instead of a number!") — and they've lived to regret it.

But not you. You've got this! I might've been a bit over-the-top here, but it's all for your own good. Pretty soon, checking incoming data will become second nature to you!

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information