Having a problem here....
I can't seem to find a good way to 'add' and 'subtract' $variables to an URL string....
Here is my example:
in the url I have http://mywebsite.com/index.php?y=2011
For source code I have:
$currentPage = $_SERVER['PHP_SELF'];
Then if I want to add different $variables to the url string, I have been trying this...:
echo '<a href="$currentPage.&t=col">College</a>';
But it isn't keeping the value of the current URL.. .?
It displays : http://mywebsite.com/index.php?&t=col
Instead of : http://mywebsite.com/index.php?y=2011&t=col (doesn't keep the $y variable)
I also need to find a way to change the $y and $t variable by any links, so I can easily change it to 2010, or 2009, with keeping the current $t variable.. ???
Thanks in advance!
HERE IS What I came up with from the great help!!!
$url = "http://www.mywebsite/index.php?";
foreach($_GET as $key=>$val){
$url.="$key=$val&"; }
echo '<a href="' . htmlspecialchars($url . 't=col') . '">College</a>';
As you may know, all variables passed through an URL are available in the $_GET array. Therefore, you can set up your link with something like this:
$url = "http://site.com/index.php?";
foreach($_GET as $key=>$val){
$url.="$key=$val&"; }
This gives you the benefit of also checking for certain variables and removing some that might be added by the user maliciously. And it also allows you to change your variables accordingly, as $key will contain either t or y
echo '<a href="$currentPage.?y=$_GET[\'y\'].&t=col">College</a>';
I don't think your question is actually related to URL manipulation. It's mainly a basic PHP syntax issue. In PHP, single-quoted and double-quoted strings are handled differently. In double-quoted ones you get variable interpolation, something you don't get in the other type:
$foo = 'world!';
echo "Hello, $foo"; // Prints «Hello, world!»
echo 'Hello, $foo'; // Prints «Hello, $foo»
However, that's all double-quoted string have in particular. You cannot insert arbitrary PHP code inside a string and get it executed:
echo "Size: strlen($foo) . 'chars'"; // Will *not* print «Size: 6 chars»
You can get the full reference in the Strings chapter of the PHP manual.
Additionally, you can concatenate strings with the .
operator (see String Operators):
echo 'Hello, ' . $foo; // Prints «Hello, world!»
Once you are familiar with these concepts, you should find it easy to do.
You can make use of the http_build_query() function to rebuild your query, adding the extra parameter you want.
// build the query data
$queryData = array(
'y' => $_GET['y'],
't' => 'col',
);
// get the query string
$queryString = http_build_query($queryData);
// ... somewhere later in the script
// we remember to escape HTML characters. as long as $currentPage has characters
// and cannot be manipulated by the client (which, if it is coming from PHP_SELF, it
// cannot be afaik), we should be safe
echo '<a href="' . htmlspecialchars($currentPage . $queryString) . '">College</a>';