For the form, use:
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">
and for getting the value, use the get method as follows:
$value = $_GET['name_to_send_using_get'];
$_GET
contains the keys / values that are passed to your script in the URL.
If you have the following URL :
http://www.example.com/test.php?a=10&b=plop
Then $_GET
will contain :
array
'a' => string '10' (length=2)
'b' => string 'plop' (length=4)
Of course, as $_GET
is not read-only, you could also set some values from your PHP code, if needed :
$_GET['my_value'] = 'test';
But this doesn't seem like good practice, as $_GET
is supposed to contain data from the URL requested by the client.
The $_GET
variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz
you can get $_GET['foo']
and $_GET['baz']
. So to set these variables, you only have to make a link to that URL.
You can use GET variables in the action
parameter of your form
element. Example:
<form method="post" action="script.php?foo=bar">
<input name="quu" ... />
...
</form>
This will give you foo
as a GET variable and quu
as a POST variable.
If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:
$_GET['key'] = 'any get value you want';
include('your_other_file.php');
One way to set the $_GET
variable is to parse the URL using parse_url()
and then parse the $query
string using parse_str()
, which sets the variables into the $_GET
global.
This approach is useful,
function setGetRequest($url)
{
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $_GET);
}
$url = 'http://www.example.com/test.php?a=10&b=plop';
setGetRequest($url);
var_dump($_GET);
Result: $_GET
contains
array (
'a' => string '10' (length=2)
'b' => string 'plop' (length=4)
)
I know this is an old thread, but I wanted to post my 2 cents...
Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..
<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>
<button type='button' onClick='ButtonPressed()'>Click me!</button>
<?PHP
if(isset($_GET['next']))
{
echo "This will display after pressing the 'Click Me' button!";
}
?>
You could use the following code to redirect your client to a script with the _GET variables attached.
header("Location: examplepage.php?var1=value&var2=value");
die();
This will cause the script to redirect, make sure the die();
is kept in there, or they may not redirect.
Source: Stackoverflow.com