How do I pass a variable in URL using PHP? - php

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.

Related

PHP (Yii) Passing variable to controlle via form

I have a variable in my view $models which I want to pass to my controller for a function which I'm calling using a submit button.
<?php echo CHtml::beginForm('', 'post');?>
<fieldset>
<?php echo CHtml::submitButton('Confirm', array('name'=>'confirm', 'class'=>'btn btn-danger')); ?>
</fieldset>
<?php echo CHtml::endForm(); ?>
how do I access the $models variable from the function in the controller.
I'm not entirely sure how this works and I would have thought I could just use $_POST['models'] but it's saying it's an undefined variable (although I can var_dump on the page and it's definitely not) so I think i'm just trying to access it incorrectly or not submitting it correctly.
This is a html form submission and php syntax problem, but not yii-specific.
Whatever framework you use, even in plain static html, the basic idea of form submission is the same: if you want to send data to a page with a form, you need to put that data in your form, either as a form input the end-user can enter or select (text inputs, dragdown boxes, radios and checkboxes), or as a hidden input. Page2 doesn't care if $models was set on Page1. You need to send the data to Page2.
In PHP, you can't display an array with echo $arrayVar.
For your specific problem, I assume $models is an array of models. Do NOT pass the whole models' definition in your form, just pass their primary key ids. On your next action, just fetch back those models with YourMode::model()->findByPk(). I think you could do this two ways:
<?php
// Idea 1 (untested code)
// Convert an array of ids to a string
$tmp = array();
foreach($models as $model){
$tmp[] = $model->yourPrimaryKey;
}
echo '<input type="hidden" name="whateveryourparamis" value="'.CHtml::encode( implode('|',$tmp)).'">';
// $whateveryourparamis will be a string like: "47|388|638|877". Use explode() to convert it to an array
// Your could also use json_encode/json_decode instead of implode/explode
// Idea 2 (untested code)
// Pass an array of ids (yeah, this is possible)
foreach($models as $model){
echo '<input type="hidden" name="whateveryourparamis[]" value="'.CHtml::encode($model->yourPrimaryKey).'">';
}
// $whateveryourparamis will be an array like: array(47, 388, 638, 877)
?>
I suppose this ain't the best way to achieve what you want, but you can always access the controller through:
$controller = Yii::app()->controller;
And then do with it whatever you want, for storing a variable in your controller, you probably will have to add a variable to your class.
Another variant would be to use CStatePersister http://www.yiiframework.com/doc/api/1.1/CStatePersister or you could also directly write in to $_SESSION..
From what you write, I suppose you should use Sessions for storing that data.

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'];

Storing redirect URL for later use

I'm trying to store the redirect URL for use a few pages later but I'm having trouble figuring out how to get it from one place to another.
Usually I'd just pass a variable thru the URL, but since my redirect URL contains URL variables itself, this doesn't exactly work.
To give you a better idea of what I'm trying to do, here's the structure.
PAGE 1: User can click a link to add content on PAGE 2
PAGE 2: User enters text. Submitting the form on this page calls "formsubmit.php" where the MySQL data entries are handled. At the end of this I need to redirect the user to PAGE 1 again. The redirect URL needs to exactly match what was originally on PAGE 1
Does anyone have any suggestions on how to go about this?
You should use $_SESSION to store the variable in session memory. As far as specifics go with how to handle this in particular, you should be able to figure it out (store the variable, check if it exists later, if so redirect etc etc) but $_SESSION is going to be much more efficient / less messy than trying to pass things back and forth in query strings.
To declare a session variable you would do something like this:
$_SESSION['redirUrl'] = "http://www.lolthisisaurl.com/lolagain";
And then to reference it you just do
$theUrl = $_SESSION['redirUrl'];
Here is some material to get you started: http://php.net/manual/en/reserved.variables.session.php
I would recommend either using session variables, or storing the redirect url in a hidden form parameter. Session variables are pretty simple; just initialize the session (once, at the top of each page), and then assign variables to the $_SESSION global var:
<?php
session_start();
...
$_SESSION['redirect_url'] = whatever.com;
...
Hidden form parameters work by sending the data from page to page as form data. On the backend, you would add code that would put the URL to be stored in a form variable:
<input type='hidden' name='redirect_url' value='<?php echo $redirect_url; ?>';
On each page, you can take the URL out of the $_POST or $_GET variable (whichever is appropriate) and insert it into a hidden form in the next page.
You can use urlencode and urldecode to pass a string that contains elements that would otherwise break a url in a url query.
I can see two possible solutions :
get the previous page from document.referrer ([edit] find more info on this SO thread : getting last page URL from history object - cross browser?)
store the previous url via a session variable ([edit] MoarCodePlz pointed this out in his answer)
Regards,
Max
You can add this hidden field in to your form:
<input type="hidden" name="referer" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
Then use header() to redirect to this page:
header('Location: '. $_POST['referer']);

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