Thursday, 12 October 2017

PHP “&” character in $_GET variable issue i.e., sending PHP variable consisting value '&' through hyperlink

For example, consider the below code,

The $product consisting value jeans&shirts

 $abslink="first.php?purchase=$product";
echo "<a href=\" $abslink \">120 </a> ";
Now the first.php has to receive the value jeans&shirts , here is the below code


 <?php

require "test.php";

$variable = $_GET['purchase'];

echo $variable;

?>

But we receive the output as 'jeans' not 'jeans&shirts' . Since it consisting of & symbol the url break the value and treats the next string as variable name i.e., shirts.
To rectify above problem,
You will want to urlencode() your string:
// Your link would look like this:
'localhost/first.php?purchase='.urlencode('jeans&shirts');
When you want to use it, you would decode it:
echo $variable = urldecode($_GET['purchase']);

EDIT: To test write this:
echo $url = 'localhost/first.php?purchase='.urlencode('jeans&shirts');
echo '<br />';
echo urldecode($url);
Your result would be:
// Encoded
localhost/first.php?purchase=jeans%26shirts
// Decoded
localhost/first.php?purchase=jeans&shirts