I am trying to send a GET message that contains strings with ampersands and can't figure how to escape the ampersand in the URL.
Example:
http://www.example.com?candy_name=M&M
result => candy_name = M
I also tried:
http://www.example.com?candy_name=M\&M
result => candy_name = M\\
I am using URLs manually, so I just need the correct characters.
I can't use any libraries. How can it be done?
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
This does not only apply to the ampersand in URLs, but to all reserved characters. Some of which include:
# $ & + , / : ; = ? # [ ]
The idea is the same as encoding an &in an HTML document, but the context has changed to be within the URI, in addition to being within the HTML document. So, the percent-encoding prevents issues with parsing inside of both contexts.
The place where this comes in handy a lot is when you need to put a URL inside of another URL. For example, if you want to post a status on Twitter:
http://www.twitter.com/intent/tweet?status=What%27s%20up%2C%20StackOverflow%3F(http%3A%2F%2Fwww.stackoverflow.com)
There's lots of reserved characters in my Tweet, namely ?'():/, so I encoded the whole value of the status URL parameter. This also is helpful when using mailto: links that have a message body or subject, because you need to encode the body and subject parameters to keep line breaks, ampersands, etc. intact.
When a character from the reserved set (a "reserved character") has
special meaning (a "reserved purpose") in a certain context, and a URI
scheme says that it is necessary to use that character for some other
purpose, then the character must be percent-encoded. Percent-encoding
a reserved character involves converting the character to its
corresponding byte value in ASCII and then representing that value as
a pair of hexadecimal digits. The digits, preceded by a percent sign
("%") which is used as an escape character, are then used in the URI
in place of the reserved character. (For a non-ASCII character, it is
typically converted to its byte sequence in UTF-8, and then each byte
value is represented as above.) The reserved character "/", for
example, if used in the "path" component of a URI, has the special
meaning of being a delimiter between path segments. If, according to a
given URI scheme, "/" needs to be in a path segment, then the three
characters "%2F" or "%2f" must be used in the segment instead of a raw
"/".
http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
Try using http://www.example.org?candy_name=M%26M.
See also this reference and some more information on Wikipedia.
I would like to add a minor comment to Blender's solution.
You can do the following:
var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');
That outputs:
http://example.com?candy_name=M%26M
The great thing about this it does not only work for &, but for any especial character.
For instance:
var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')
Outputs:
"http://example.com?candy_name=M%26M%3F%3E%3C"
You can use the % character to 'escape' characters that aren't allowed in URLs. See RFC 1738.
A table of ASCII values is given on the Wikipedia page.
You can see & is 26 in hexadecimal - so you need M%26M.
This may help if someone want it in PHP
$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);
If you can't use any libraries to encode the value,
http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...
Just enter your value "M&M", not the full URL ;-)
You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
Related
I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.
For example if I have the URL: http://localhost/proxy.php?user name=Max
the browser will convert it to http://localhost/proxy.php?user%20name=Max.
But if I give the $_GET parameters out, the key is not user name but user_name (note the underscore)!
Is there any possibility to change this behaviour?
From the PHP manual:
Dots in incoming variable names
Typically, PHP does not alter the
names of variables when they are
passed into a script. However, it
should be noted that the dot (period,
full stop) is not a valid character in
a PHP variable name. For the reason,
look at it:
<?php $varname.ext; /* invalid variable name */ ?>
Now, what
the parser sees is a variable named
$varname, followed by the string
concatenation operator, followed by
the barestring (i.e. unquoted string
which doesn't match any known key or
reserved words) 'ext'. Obviously, this
doesn't have the intended result.
For this reason, it is important to
note that PHP will automatically
replace any dots in incoming variable
names with underscores.
And a comment on the page:
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)
PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
I think the only possibility to get the wanted parameters, is to parse them on your own using $_SERVER['QUERY_STRING']:
$a_pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($a_pairs AS $s_pair){
$a_pair = explode('=', $s_pair);
if(count($a_pair) == 1) $a_pair[1] = '';
$a_pair[0] = urldecode($a_pair[0]);
$a_pair[1] = urldecode($a_pair[1]);
$GLOBALS['_GET'][$a_pair[0]] = $a_pair[1];
$_GET[$a_pair[0]] = $a_pair[1];
}
In the old crazy times of register_globals query string was unpacked by PHP into global variables, but the format of variable identifiers is constrained, so obviously spaces couldn't work. This limitation remained, and honestly I believe it's a good idea to keep it this way.
If you really cannot change spaces into underscores in your URLs, just mangle the $_GET array when you process the request and substitute every underscore by a space.
As far as i can remember, i've never seen spaces in URL parameter names...
I think, it would be better to convert all spaces of parameter names into "_".
I have simple problem, I have to replace %20 and other crap from URL. At the moment it looks like this http://exmaple/profile/about/Eddies%20Plumbing. As you can see it's profile link.
Yes I could add str_replace values before every hyperlink, but I have like 10 of them and I think it's bad practice. Maybe there is better solution? What solution would you use? Thanks.
That is not crap, that is a valid unicode representation of a space character. And it's encoded because it's one of the characters that are deemed unsafe by RFC1738:
All unsafe characters must always be encoded within a URL. For
example, the character "#" must be encoded within URLs even in
systems that do not normally deal with fragment or anchor
identifiers, so that if the URL is copied into another system that
does use them, it will not be necessary to change the URL encoding.
So in order to have pretty URLs, you should avoid using reserved and unsafe characters which need encoding to be valid as part of a URL:
Reserved characters: $ & + , / : ; = ? #
Unsafe characters: Blank/empty space and < > # % { } | \ ^ ~ [ ] `
Instead replace spaces with dashes, which serve the same purpose visually while being a safe character, for example look at the Stack Overflow URL for this question. The URL below looks just fine and readable without spaces in it:
http://exmaple/profile/about/eddies-plumbing
You can use Laravel's str_slug helper function to do the hard work for your:
str_slug('Eddies Plumbing', '-'); // returns eddies-plumbing
The str_slug does more that replace spaces with dashes, it replaces multiple spaces with a single dash and also strips all non-alphanumeric characters, so there's no reliable way to decode it.
That being said, I wouldn't use that approach in the first place. There are two main ways I generally use to identify a database entry:
1. Via an ID
The route path definition would look like this in your case:
/profiles/about/{id}/{slug?} // real path "/profiles/about/1/eddies-plumbing"
The code used to identify the user would look like this User::find($id) (the slug parameter is not needed, it's just there to make the URL more readable, that's why I used the ? to make it optional).
2. Via a slug
The route path definition would look like this in your case:
/profiles/about/{slug} // real path "/profiles/about/eddies-plumbing"
In this case I always store the slug as a column in the users table because it's a property relevant to that user. So the retrieval process is very easy User::where('slug', $slug). Of course using str_slug to generate a valid slug when saving the user to the database. I usually like this approach better because it has the added benefit of allowing the slug to be whatever you want (not really needing to be generated from the user name). This can also allow users to choose their custom URL, and can also help with search engine optimisation.
The links are urlencoded. Use urldecode($profileLink); to decode them.
I am parsing the url tha i got in this way ->
$replacingTitle = str_replace('-',' ',$title);
<a href="example.com/category/{{ str_slug($article->title) }}/" />
In your view ...
{{$comm->title}
and in controller using parsing your url as
public function showBySlug($slug) {
$title = str_replace('-',' ',$slug);
$post = Community::where('title','=',$title)->first();
return view('show')->with(array(
'post' => $post,
));
}
I have several strings that look like this:
Lasklé
Jones & Jon
I am trying to send them via the foursquare API to be matched, however it is failing with these characters. Is there a way to sanitise these so they only include English letters i.e. the results would be:
Lasklé
Jones Jon
As it appears using file_get_contents requests both with the 'é' and the '&' in the URL is causing issues.
I checked how the request was sent and realised that the '&' is uneeded and is causing the issues, is it possible to remove all non Letters/Numbers from the name?
What do the strings look like before you pass them? If your string looks like 'Lasklé' then I think you are using the wrong character set when reading the string, try using UTF-8.
If the string looks correct before you pass it on you should try urlencode the string first.
you can use preg_replace() function to replace the part of string using regex
to keep only letters you can use as follow it will also remove space( add \s from expression to keep space)
preg_replace('/[^a-zA-Z]/','',$string);
to keep space in the string or any character to keep you can add it in []
preg_replace('/[^a-zA-Z\s]/','',$string);
Use this to escape (space and '-'). Good for making a custom URL
$string=preg_replace("/[^A-Za-z0-9\s\/\-]/", '', $string);
I'm using codeigniter (newbie at codeigniter).
I have a function getproducts($p1, $p2, $p3) in a controller.
When I call getproducts/0/0/ from my jquery-script (ajax) it works, but I want to call URL like this:
getproducts/0/0/{"0":"13","1":"24"}
it doesn't work. (I get into to google-search-results instead of staying at my local webserver)
I basically want to pass an array to a function in the url somehow when using codeigniter. How should I solve that? Please help :-)
I think you should at least adjust the Codeigniter's config about allowed characters in the URL to include curly braces, comma and double quotes :
$config['permitted_uri_chars'] = ',{}"a-z 0-9~%.:_()#\-';
The reason why you end up on Google might however be something else (does not seem to be Codeigniter related)
Your browser don't think that that is a URL and navigates to google (thinking that you are searching something), I Think.
The main parts of URLs
A full BNF description of the URL syntax is given in Section 5.
In general, URLs are written as follows:
<scheme>:<scheme-specific-part>
A URL contains the name of the scheme being used () followed
by a colon and then a string (the ) whose
interpretation depends on the scheme.
Scheme names consist of a sequence of characters. The lower case
letters "a"--"z", digits, and the characters plus ("+"), period
("."), and hyphen ("-") are allowed. For resiliency, programs
interpreting URLs should treat upper case letters as equivalent to
lower case in scheme names (e.g., allow "HTTP" as well as "http").
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
schemepart = *xchar | ip-schemepart
See http://www.faqs.org/rfcs/rfc1738.html please.
{"0":"13","1":"24"} should be url encoded.
http://php.net/manual/en/function.urlencode.php
I think a better answer for this question would be to use the inbuilt uri to associative array handler. see http://www.codeigniter.com/user_guide/libraries/uri.html?highlight=uri
this stops all that nasty mucking about with config permitted uri characters.
your uri would be: getproducts/p1/0/p2/0/p3/0/p5/13/p6/1/p6/24
and the handler would be something like:
function get_product()
{
$object = $this->uri->uri_to_assoc(4);
}
You need to use URI class's
$this->uri->assoc_to_uri()
Manual wrote,
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
I am trying to do a query string in html.
String that I want to pass is "Book Cover".
But I only managed to get Book.
How should I go about doing it?
Below is my code:
<a href=book.php?category=Book Cover>Book Cover</a>
You need to encode all your query string vars, For example with rawurlencode / rawurldecode
Book Cover
And in PHP:
$category = rawurldecode($_POST['category']);
In HTML the value stops at the space:
<a href=book.php?category=Book Cover>Book Cover</a>
^
If you want to include a space inside a value in HTML you need to add quotes:
Book Cover
^ ^
In HTML both single and double quotes are allowed.
Now the value itself has a problem, too:
book.php?category=Book Cover
`- URL stops here.
This is a relative HTTP URL and as for any HTTP URL the space character is a special value. It can normally not be part of the URL, therefore you need to encode it. This can be done as with any other special character in a HTTP URL with triplet encoding / percentage-encoding replacing the binary value of the character(s) with their hexadecimal number:
book.php?category=Book%20Cover
For the space you have, historically it is even a special-case, you can also encode it with the plus sign.
The later problem is often dealt with by the user agents, but the quotes in HTML are needed otherwise the value gets cut.
And it is generally good practice to place attribute values in HTML inside (double) quotes. So I suggest you to do that.
Why not convert to UTF-8 before encoding?
urlencode(utf8_encode($string));
Looks like you are missing double quotes
Book Cover