How do i set the variable that the $_GET function will be able to use, w/o submitting a form with action = 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.
You can create a link , having get variable in href.
<a href="www.site.com/hello?getVar=value" >...</a>
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.
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,
if you want to test GET parameter handling without making actual queries, e.g. for testing the incoming parameters for existence and input filtering and sanitizing of incoming vars.
and when you don't want to construct the array manually each time, but use the normal URL
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)
)
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');
note: i must add that while this is ok for dev/test/debug, it is considered bad programming and i wouldn't recommend using this method in prod. it would be better to pass the processed values to the function/class instead of having it read the $_GET directly.
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.
simply write basic code to set get method value in php
Syntax :- $_GET['< get method variable name>']='';
Ex :- $_GET['send']='invoice';
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.
For the form, use:
<form name="form1" action="" method="get">
and for getting the value, use the get method as follows:
$value = $_GET['name_to_send_using_get'];
As #Gaurav and #Sander Marechal said, it's possible to add directly at the end of the URL the GET parameters to send to the web page. It works in the majority of cases. But unfortunately, there is an issue with that because an URL cannot accept any character. Some special characters have to be properly encoded to get a valid URL.
Suppose you have an index.php and you want to set a with the value &b= which contains special characters. When I submit the form of the following code, the URL sent is index.php?a=&b= and PHP prints Array ( [a] => [b] => ). So, PHP believes there is two parameters but I only want the parameter a.
You may also notice that the form method is set to POST because if you set it to GET the parameters at the end of the action URL will be ignored. For more details about that see this #Arjan's answer.
<form action="index.php?a=&b=" method="post">
<input type="submit">
</form>
<?php print_r($_GET); ?>
One solution could be to use the PHP function urlencode. But, as you can see in the following code it's not really convenient to use, especially if you have many parameters to encode. When, I submit this form the URL sent is index.php?a=%26b%3D and PHP prints Array ( [a] => &b= ) as expected.
<form action="index.php?a=<?=urlencode("&b=")?>" method="post">
<input type="submit">
</form>
<?php print_r($_GET); ?>
But, instead of urlencode function I recommend using hidden input. Thanks to this tag you can send GET parameters dynamically set by PHP. Besides, these parameters are automatically encoded with the URL standard. And you don't need to use & to separate several parameters: use one input to set one parameter. When, I submit this form the URL sent is index.php?a=%26b%3D and PHP prints Array ( [a] => &b= ) as expected.
<form action="" method="get">
<input type="hidden" name="a" value="<?php echo "&b="; ?>">
<input type="submit">
</form>
<?php print_r($_GET); ?>
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!";
}
?>
Related
What I have is that when someone clicks a link on my index it calls index.php?action=signup and that will display a signup form.
How do I then cause the signup form to maintain the action=signup portion of the query string so that when the user clicks "Submit" the new query string is index.php?action=signup&email=user#email.com?
What is the best way to set this up? Should I somehow split the actions into GET and the data into POST?
I am not sure if I am describing this correctly but I want to keep all my functions on the index.php so when I integrate .htaccess everything will be like www.site.com/signup, www.site.com/login and so on.
The best way to do this on a form submission is to change the <form> action to the correct URL and the method to GET, like so:
<form action="index.php?action=signup" method="GET">
Then, hidden in your form, you put something like the following:
<input type="hidden" name="action" value="signup" />
Then your URL will contain the correct parameters when it is submitted.
However, if you need to modify this server side, then you can get all of your query parameters via $_SERVER['QUERY_STRING']. Use parse_str to get an array of values, and use http_build_query to recreate the query string:
Example:
$params = array();
parse_str( $_SERVER['QUERY_STRING'], $params);
$params['email'] = 'user#email.com';
echo http_build_query( $params); // Will output a new query string for your URLs
How can i pass a post array to a functing then pull out the params i.e
so i am posting the following.
url=http%3A%2F%2Fwww.facebook.com%2Ftest&userId=680410999&location=Cardiff&lang=en_US&social=facebook
can i grab it like this from the function????
function login($_POST){
//then output the var her.
$_POST['url']; etc
}
this is to save me doing the following in my ajax.php file
function login($_POST['url'],$_POST['userId'],$_POST['location'],$_POST['lang']){
}
any help pls
First you should use $_GET and not $_POST. Second you don't need to call your function parameter as $_GET. You can do this:
function login($array)
{
// do stuff with array
}
and then call the function in this way:
login($_GET);
An additional suggest is to read the following quote and that is the difference of actual parameters towards formal parameters:
Formal parameters are the parameters as they are known in the function
definition. Actual parameters (also known as arguments) are what are
passed by the caller.
The other answers you have got should solve this problem for you.
Just some more advice, remember to clean any $_POST and $_GET data that you are using in your code.
For example, if you are using it in a database query then you will need to use mysql_real_escape_string(); and if you are echo'ing the data then use htmlentities();
If I unserstand you correctly you want a function that you call and pass it an array (in your case the $_POST or $_GET array) as a parameter.
So your function would look something like this:
// not sure what you're doing with your login options but here's an example of getting them out of the array and putting them in variables - using the url as an example here...
var url;
function login($loginOptions) {
// set the url from the array
url = $loginOptions["url"];
// do the same for all your other variable...
}
Then you would call your function like so:
login($_POST); // or $_login($_GET); depending on what you're using
And that's it!
I think what you mean is parsing array to a function for this I will tell you to use a function and connected it with SESSION as this below. You can use the $_GET[$var] to retrieve the variable but it's quite hard to be handled by the method get, you can use the method $_POST and combine it with session to save the data , I will explain how to collaborate the session each page so that you can easily retrieve the variable you wanted.
Here's the code :
<?php
session_start();
if(isset ($_POST['postedit']))
{
$_SESSION['url'] = $_POST['urlsend'];
header("location:dua.php");
}
?>
<html>
<body>
<form action="satu.php" method="POST">
Name : <input type="text" name="urlsend"> <br> <br>
<input type="submit" name="postedit" value="SEND DATA">
</form>
</body>
</html>
<?php
session_start();
if(isset ($_SESSION['url']))
{
//if data empty then will be redirected to the previous page
echo $_SESSION['url'];
}
?>
I created with dynamic data even you can choose to use this method or other method. I hope you can understand.
dear all, i'm a noob in codeigniter,
i would like to ask for advise, on how to create a search form that would result to url as:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
the form would be like
<form action="http://domain/class/index">
<input name="searchvar1" value="searchvar1val">
<input name="searchvar2" value="searchvar2val">
<input type="submit">
</form>
what is the best practice for this?
i've googled around including stackoverflow posts, still can't find any solution.
thanks :)
~thisismyfirstposthere
update ::
i would like to emphasize that my objective is to process search variables from the uri string (above), not from post vars; so i think setting the form search to POST is not an option? :)
update (2)
i don't think this can be done out of the box in codeigniter, i'm thinking of client-processing the form vars/vals into the form action in URI format using jQuery.
will post an update here later when done.
taking a look at the user_guide :
$this->uri->assoc_to_uri()
Takes an associative array as input
and generates a URI string from it.
The array keys will be included in the
string. Example:
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
and i think if your form is this:
<form action="http://domain/class/index/search">
<input name="product" value="shoes">
<input name="size" value="large">
<input name="color" value="red">
<input type="submit">
</form>
then somewhere in the search controller do this $this->uri->assoc_to_uri($data); IMHO will produce product/shoes/size/large/color/red
hey guys, thanks for replying and discussing, I think imma go with flow:
View --> form --> jquery, on form submit: replace action attribute with form params --> controller with uri string --> rest of the process
the jquery part would be something like this
$("#searchFormID").submit(function(){
// $(this).serialize() outputs param1=value1¶m2=value2 string
// var.replace(regex, string) outputs param1/value1/param2/value2 string
// newact would be http://localhost/class/index/param1/value1/param2/value2
var newact = $(this).attr("action") + "/" + $(this).serialize().replace(/&|=/g,"/");
$(this).attr("action", newact); // or $(this).attr("target", newact);
return true;
});
notes:
add an id attribute to the form -> for the form selector in jquery
use post method in the form (this is default in codeigniter) -> so action url will not be populated with the GET string
You may want to enable query strings and use $_GET. IMO, this is a perfect example what the query string is intended for.
Make sure to change your form to <form method="get" action="http://domain/class/index">
You will then have a query string in your URL like ?searchvar1=value1&searchvar2=value2
You can access parts of the string like this: $this->input->get('searchvar1')
With the method you are currently using, if a user searches for any characters that are not allowed in your $config['permitted_uri_chars'], you will have to do a lot of encoding and decoding yourself to make sure the string is safe/readable in your URL. The CI Input class takes care of this for you, so it is my recommendation.
Another disadvantage to URI segment based search params is that there is no proper way to express an array like ?values[]=one&values[]=two&values[]=three. There are hacks to work around this, but they are all exactly that: hacks. you will eventually run into trouble.
Using $_POST is very tedious and forces the use of form submits for paginated results and links, and also ensures that you cannot link to the search results or use the back button properly.
If you must use this method, simply have the form post to your controller, read the input, and then redirect() to the url that you construct from it. littlechad has the right idea for this method in his answer
// This URL:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
// With this:
$search = $this->uri->uri_to_assoc();
// Produces this:
array(
'searchvar1' => 'searchvarval1',
'searchvar2' => 'searchvarval2',
);
// And you can use it like this:
$arg1 = $search['searchvar1'];
$arg2 = $search['searchvar2'];
To get TO this url, you can do something like this with your form post (in the controller after post):
$var1 = $this->input->post('searchvar1');
$var2 = $this->input->post('searchvar2');
redirect('searchvar1/'.urlencode($var1).'/searchvar2/'.urlencode($var2));
I'm sure you can see how much more work this is than just using the tried-and-true query string...
I have a variable called $tags, which just references from a database field. When the user clicks a link with the given $tags output in it, I want that data to be stored in a variable on the target page.
For instance, the user is on a todolist.php, that contains several tasks. They can see the parts associated with this task by clicking a link that goes to a partslist.php page. In the link, I need to contains the $tags data, so javascript on the partslist.php page knows what part to highlight.
So I need to know 1) how do I output $tags in the link of todolist.php, and 2) how do I receive that output and store it on a variable on the partslist.php page?
I have done similar POST and GET commands, but I can't quite figure this out.
partslist.php?tags=<?php echo urlencode($tags) ?> .. is this what you are asking ? Or there are multiple tags ? Please give examples / code blocks / links
On the partslists side you can do this :
$tags = $_GET['tags']; // You don't need urldecode here, because $_GET is a supergobal and it is already decoded.
You pass URLs to pages in one of two ways: $_GET or $_POST. $_POST requires that you have a form setup like:
<form method="post" action="page.php">
<input type="text" name="myvariable" value="test">
<input type="submit">
</form>
And $_GET requires that you link to the page like:
click me
In the first scenario, when the user hits submit, page.php will have access to the variables submitted from the $_POST array. In this case, $_POST['myvariable'] will equal "test";
In the second, $_GET['myvariable'] will equal test.
is $tags an array?
If so you can output the $tags array in the following format
partslist.php?tags[]=tag1&tags[]=tag2&tags[]=tag3
if you would then output the $_GET global in the partslist.php script you would end up with an array like this:
Array
(
[tags] => Array
(
[0] => "tag1"
[1] => "tag2"
[2] => "tag3"
)
)
If the URL for the link they click on contains URL parameters, those will be available on the target page. For instance,
// Generate a link like this with PHP
<a href="somepage.php?name=bob&weight=150">
// On somepage.php
$name = $_GET['name'];
$weight = $_GET['weight'];
Note: for security, you may want to encrypt this data before putting it in the link, and decrypt it on the other end.
For the part where you hand some data to Javascript, you can interpolate PHP in your Javascript the same as your HTML. So, you could say:
//JS
var foo = <?PHP echo $foo ?>;
Alternately, you could store data in an HTML element:
<div id="foo" data="<?PHP echo $data ?>">
... and then grab that using Javascript.
I've never really thought about this, but it helps with some security of something I'm currently working on. Is it possible to submit GET data without an actual input field, and instead just getting it from the URL?
If so, how would I go about doing this? It kind of makes sense that it should be possible, but at the same time it makes no sense at all.
Perhaps I've been awake too long and need some rest. But I'd like to finish this project a bit more first, so any help you can offer would be appreciated. Thanks
Yes. If you add some query-string to yourl url, you can obtain that in php using $_GET without form submitting.
Going to this URL adress http://yoururl/test.php?foo=bar cause echoing foo (if there will be no foo query string, you'll get warning).
# test.php
echo $_GET['foo'] # => bar
Is this what you mean?
Link
// page.php
echo $_GET['type']; // foobar
This is what I understand of your question:
You have a <form method="get" action="foo.php">-like tag on your page
You have a series of <input type="text" name="bar"/> in your page
You want to pass additional GET parameters that are not based on an input from the form
If so, it is possible, but I hardly see how it could help with security. Input from a client cannot be trusted, so even if you hardcode the GET value, you have to check it serverside against SQL injection, HTML injection/XSS, and whatnot.
You have two ways:
Use a hidden input: <input type="hidden" name="myHiddenGetValue" value="foobar"/>
Add the GET parameter to the form action: <form method="get" action="foo.php?myHardcodedGetValue=foobar">
If what you meant is that you want to have a GET request without a form, you just need to pass all the GET parameters to the href of a link:
Click here!
Yes it's possible. Just append the GET data to the link.
For example:
<a href="main.htm?testGet=1&pageNo=54>Test</a>
You can also use Javascript to build the url.
If you happen to be using jQuery and want to build the GET data dynamically you can do this:
var getParams = { testGet:1, pageNo:54 };
$(".myLink").attr("href", url + "?" + $.param(getParams));