How do I build on a query string? - php

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

Related

Form post action: not seeing query parameters in $_POST

I have a small PHP application (MVC) with a form. The action looks something like this:
<form action="<?php sprintf("/v/.../update?job=%s", $job->id);?>" method="post">
Here $job is a PHP object I pass the view from the controller. I hold onto the id field (an integer) so that I can update the row in the database corresponding to the object.
I'm not seeing this value in $_POST (it is in $GET, though) when I step into my update function for a post request. How should I retrieve this value? Is this expected?
Try to get by $_GET['job'] or remove 'job' from action url and send in hidden text field to get as $_POST['job'].
Also I think your action url is not creating. use echo
<form action="<?php echo sprintf("/v/.../update?job=%s", $job->id);?>" method="post">
you pass your job param as url string, and in this case it can be seen in $_GET or $_REQUEST arraies not $_POST whatever your form action get or post, because this param isn't form input.

On clicking a button on a web page, can a dynamic link be generated? can we navigate webpage to the dynamically generated link

I am new to PHP and javascript programming
I have a string that can be "abc" or "aac" or "aaa" etc based on the inputs given by the user. After the user clicks some button(say submit) I want to generate a dynamic link like www.domain.com/abc or www.domain.com/aac based on string and navigate the user to the generated link. Is this possible?
Thank You
You can actually define a function and set it your form action. Then taking the user input it will be really each in the function to use header('location:YOUR_SITE_URL/'.$_GET['user_input']); die; for redirecting the user to desired url.
Hope that helps.
Yes it is possible, you can pass the string variable throw POST or GET when the user click submit
and then echo the link you want with the string congrenated. assuming you want to use php take a look at the example
$adress = "www.domain.com/";
$string = $_POST["get_string"];
$result = $adress + $string;
echo $result;
Possible, using routing. A real world example is how your usernames get to be part of the URL in social sites like Facebook.
What you need is a database of some sort to store the string, and it's matched data (could be an ID, or some identified) to tell the server what to load when that string is received. You'd also need routing code, which parses the entire url in search of that certain segment which should contain the string. This is how routing works in frameworks like CodeIgniter, Connect and Express.
In JS, routers in Connect look like:
app.route('/users/:username',function(username){
//okay! we got the username!
//now we'll look for it in the database if it's there
});
For PHP, here's an article regarding URL parsing.
In PHP :
Use methode in your page and store the variable to $UrlName (for example)
and continued with
echo("<script>location.href = \"www.domain.com/" . $UrlName . "\";</script>");
First in page1.html:
<form method="post" action="page2.php" >
String: <input type="text" name="string" />
<input type="submit" />
</form>
Then in page2.php:
header('location:www.domain.com/string/'.$_POST['string']);
But you should put a .htaccess containing:
Redirect /string/(.+) /page3.php?string=$1 [B,QSA]
And page4.php:
echo $_GET['string'];

PHP going back and keeping arguments

I have used this page http://www.binarytides.com/blog/php-redirect-go-back-to-previous-page/
to go back
but from
http://page.co/test.php?item=26
I post something to post.php and then call the php Go back function but I go back to
http://page.co/test.php
losing the argument path, any idea?
In Your form fill in the query string to the action attribute, like this:
<form action="?item=26" name="myform">
...
</form>
and after the submission Your HTTP_REFERER will contain this query string so redirect to it will be successfull...
EDIT: If the form is on the page post.php, it is enough to use action="?item=26" - of course You can and should use PHP to write down the number/ID of item from whenever it may come...
Lets say Your item ID is stored in the variable $item_id - then Your action will look like this: action="?item=<?php echo $item_id; ?>".
You should use sessions for stuff like this. Set a session when posting the data and you're set.

how to create search form with into codeigniter uri format?

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&param2=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...

How to set $_GET variable

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!";
}
?>

Categories