i have a question about formatting the URL parameters in php
page 1 can have these 2 url
http://somewhere.com/page1.php?foo=1
and
http://somewhere.com/page1.php
now on page 1, when i click a button, i want it to redirect to its self but with an additional parameters in the URL like so
http://somewhere.com/page1.php?foo=1&bar=2
or
http://somewhere.com/page1.php?bar=2
depending on the current url. How can i do this in php?
thanks, Vidhu
First, check if a certain $_GET
parameter is set, using isset
.
If it is, echo
a certain link. If not, echo
a different link.
if( !isset($_GET['bar']) ){
echo '<a href="?bar=2">link</a>';
}
else{
echo '<a href="page1.php">link</a>';
}
The following form will submit to the same url with parameters added.
<form action="<?php echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" method="get">
<?php
// Iterate through our query string and add each key value pair as a hidden input
foreach ($_GET as $key => $value)
{
?>
<input type="hidden" name="<?php echo $key; ?>" value="<?php echo $value; ?>"/>
<?php
}
?>
<!-- new parameter to add -->
<input type="hidden" name="foo" value="1"/>
<input type="submit"/>
</form>
You can do a simple get system, So you will need to check if ?foo=1
is set if it is you can echo its content. If you want to show content for bar=2
check if its set and echo its content. This is just a simple way there more ways though.
Simply you can do with $_SERVER['PHP_SELF']
For example
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
<input type="hidden" name="foo" value="1"/>
<input type="submit"/>
</form>
Here the htmlentities() is used to avoid PHP_SELF exploitation as a security precaution
If you wish to avoid hidden input fields you can append the query parameters like action="<?php echo $_SERVER['PHP_SELF']; ?>?foo=1&bar=2"
I'm using these PHP functions to help me build urls correctly:
parse_str()
parse_url()
http_build_query()
http-build-url()
Example:
<?php
function add_parameters($parameters) {
parse_str($_SERVER['QUERY_STRING'], $old_parameters_as_array);
return $_SERVER['PHP_SELF'].'?'.http_build_query(array_merge($old_parameters_as_array, $parameters));
}
echo '<a href="'.add_parameters(array('bar' => 2)).'">Link</a>';