[php] How to pass a PHP variable using the URL

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?

This question is related to php url

The answer is


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.


Use this easy method

  $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>";

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)


just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

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