Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a PHP variable using the URL

Tags:

url

php

I want to pass some PHP variables using the URL.

I tried the following code:

link.php

<html>
<body>
<?php
$a='Link1';
$b='Link2';
echo '<a href="pass.php?link=$a">Link 1</a>';
echo '<br/>';
echo '<a href="pass.php?link=$b">Link 2</a>';
?></body></html>`</pre></code>

pass.php
<pre><code>`<html>
<body>
<?php
if ($_GET['link']==$a)
{
echo "Link 1 Clicked";
} else {
echo "Link 2 Clicked";
}
?></body></html>

Upon clicking the links Link1 and Link2, I get "Link 2 clicked". Why?

like image 722
chetan Avatar asked Mar 26 '11 03:03

chetan


People also ask

How do you pass a variable in a URL?

To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.

How can we send ID through URL in PHP?

Use PODS Style MySQL to Send ID in URL This is the most common method used in PHP to make URLs dynamic and send ID(s). Once we have created dynamic, hyper references, we are all set to use $_GET['id']; and store it in a variable. That way, we can use any logic on this selected ID.

What PHP variable is used to access URL variables?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL.


2 Answers

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

like image 129
ace Avatar answered Oct 23 '22 03:10

ace


You're passing link=$a and link=$b in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

// and

echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

The value of $a also isn't included on pass.php. I would suggest making a common variable file and include it on all necessary pages.

like image 24
Tim Cooper Avatar answered Oct 23 '22 03:10

Tim Cooper