Passing & in URL variable with the help of urlencode - php

I have done urlencode of the variable before passing to the URL
http://example.com/Restaurants?alias=F%26B
But when I try to print like in the page
$alias = rawurldecode($_GET['alias']);
echo $alias;
it prints only F. How to solve this?

I doubt that $_GET['alias'] exists when requesting a URL with the query aliasF%26B. It’s rather $_GET['aliasF&B'] that’s getting populated.
In this case you need to use $_SERVER['QUERY_STRING'] to get the full query.

It looks like you are not using the query string "correctly." It should be in key=value pairs. I would look at using $_SERVER['QUERY_STRING'] to get your information instead.

You don't need to urlencode the pair. You only need to urlencode name and a value as such:
Wrong:
urlencode('aliasF=B')
Correct:
urlencode('aliasF') . '=' . urlencode('B')

AFAIK $_GET are already decoded.
See php.net
The superglobals $_GET and $_REQUEST
are already decoded. Using urldecode()
on an element in $_GET or $_REQUEST
could have unexpected and dangerous
results.

It is possible to solve this problem by using a different encoding system specific for your situation:
function encode($string)
{
$result = str_replace("|","||",$string);
return str_replace("&","|20",$result);
}
function decode($string)
{
$result = str_replace("|20","&",$string);
return str_replace("||","|",$result);
}
This will basically create a separate escaping system using the '|' character. That character can be anything you normally don't use and isn't an field separator.
Here, Apache won't transform the URL to something different, thus voiding the conversion. Also browsers won't transform it.
Mind that you would decode($_GET['alias']) and encode() the url that the user is pressing or the script is following.

Related

How to change variables in link of foo?q=some&s=3&d=new

Consider a php script visited with URL of foo?q=some&s=3&d=new. I wonder if there is a paractical method for parsing the url to create links with new variable (within php page). For example foo?q=**another-word**&s=3&d=new or foo?q=another-word&s=**11**&d=new
I am thinking of catching the requested URL by $_SERVER['REQUEST_URI'] then parsing with regex; but this is not a good idea in practice. There should be a handy way to parse variables attached to the php script. In fact, inverse action of GET method.
The $_GET variable contains an already parsed array of the current query string. The array union operator + makes it easy to merge new values into that. http_build_query puts them back together into a query string:
echo 'foo?' . http_build_query(array('q' => 'another-word') + $_GET);
If you need more parsing of the URL to get 'foo', use parse_url on the REQUEST_URI.
What about using http_build_query? http://php.net/manual/en/function.http-build-query.php
It will allow you to build a query string from an array.
I'd use parse_str:
$query = 'q=some&s=3&d=new';
parse_str($query, $query_parsed);
$query_parsed['q'] = 'foo-bar';
$new_query = implode('&', array_map(create_function('$k, $v',
'return $k."=".urlencode($v);'),
array_keys($query_parsed), $query_parsed));
echo $new_query;
Result is:
q=foo-bar&s=3&d=new
Although, this method might look like "the hard way" :)

Why does Symfony escape & characters when using url_for()?

With this Symfony page, I am passing $_GET parameters in the URI like this:
http://www.mysite.com/article?page=4&sort=1
Once in my layout, there are certain links in the page that need to have the same query string in them.
Anyways, using Symfony's url_for() command I'm making URLs like so:
$url = url_for('article/index?.http_build_query($_GET));
That way it makes a new url using the $_GET variables. For some of the links I'm changing the $_GET values ahead of time, like $_GET['sort']=0; before generating the url. That's why I'm using this method.
Anyways, when I look at the generated URL, it now looks like this:
http://www.mysite.com/article?page=4&amp%3Bsort=1
The &amp%3B is the encoded form of & which is just an & character.
So the problem is that when I check for my $_GET parameters in my controller now, there is no longer a sort parameter that is passed. It's now called &amp%3Bsort... It's causing all sorts of issues.
Two questions:
How do I avoid this problem? Can I decode the $_GET parameter key values in my controller or something?
Why is symfony encoding a & character in the first place? It's a perfectly acceptable URI character. Heck, even the encoded value, &amp%3B contains a & !!!
I believe, it is because of output escaping is ON in your application. As a result, $_GET array is wrapped inside sfOutputEscaperArrayDecorator class. You can get a raw value using this: $_GET->getRawValue().
$url = url_for('article/index?.http_build_query($_GET->getRawValue()))
Or you can decode the result query using sfOutputEscaper::unescape
$url = url_for('article/index?.sfOutputEscaper::unescape(http_build_query($_GET)));
Hope this will be useful.
Best if you use Symfony's own method for getting the request parameters. For example, in templates, use:
$sf_request->getParameter('some_param');
If you must use $_GET, maybe try:
((( $sf_data->getRaw('_GET') )))
... to get past the output escaping. Not totally sure if that'll work as is.

Safely pass variables from one php file to another php file in the URL

This might be a basic question and I've been searching for a safe and clean way to do this. Im passing a normal string which CAN include special characters (like $ ^ % etc). How can I do this in the url? For example I have a variable called $text which In addto.php from $_GET. How do I then transfer this to more.php?
'more.php?varname='.urlencode($_GET['text']);
urlencode sounds like what you want.
(from the docs)
This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
You can pass data through an URL, it should be in the form of key/value pairs, but you shouldn't use it to pass too much data because an URL has a limit. You also should not pass sensitive information.
A key/value pair is something like this:
key=value
If you have more then one pair, you need to separate them using the & char. Here is an example:
myScript.php?color1=blue&color2=red
The string after ? is called the Query String. With PHP you can easily access those key/value pairs using the super-global $_GET. So, in myScript.php you do:
$a = $_GET['color1'];
$b = $_GET['color2'];
Now, if you are going to create a dynamic query string, you should use urlencode() at least, so any special characters will be translated to maintain a proper URL format.
Please read the following:
http://php.net/urlencode
http://php.net/manual/en/function.http-build-query.php

How to using get method without field name?

for example the link is:
http://www.test.com/abc.php?config.scp
Is it possible to get the value "config.scp" in the php program? Thanks!
That data is contained in $_SERVER['QUERY_STRING']
If you want a simple string, use $_SERVER['QUERY_STRING'].
If you still need an array with rest of the variables, use $_GET. If you var_dump( $_GET ) on link you provided, you should get:
array(1) {
["config_scp"]=>
string(0) ""
}
You can easily parse it now.
There's one gotcha with dot in that particular query string tho. PHP variables cannot contain dots, so it's changed into _.
Yes... in that case data is field name but be aware that dot is not allowed in $_GET array index.
Also, you can explode $_SERVER['QUERY_STRING'] with & character and look into resulting array for element's value you need.
Hy
See this example:
$url = 'http://www.test.com/abc.php?config.scp';
$p_url = end(explode('?', $url));
echo $p_url;

PHP - Data after "?" in URL displays different information

I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1&param2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.

Categories