Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly URL encode a string in PHP?

Tags:

php

urlencode

I'm making a search page, where you type a search query and the form is submitted to search.php?query=your query. What PHP function is the best and that I should use for encoding/decoding the search query?

like image 438
Ali Avatar asked Jan 20 '11 08:01

Ali


People also ask

What is the best way to URL encode a string?

In JavaScript, PHP, and ASP there are functions that can be used to URL encode a string. PHP has the rawurlencode() function, and ASP has the Server. URLEncode() function. In JavaScript you can use the encodeURIComponent() function.

Can you encode a string in PHP?

Definition and UsageThe utf8_encode() function encodes an ISO-8859-1 string to UTF-8. Unicode is a universal standard, and has been developed to describe all possible characters of all languages plus a lot of symbols with one unique number for each character/symbol.

What is %20 in the URL?

A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.


2 Answers

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

  • urlencode encodes according to application/x-www-form-urlencoded (space is encoded with +) while
  • rawurlencode encodes according to the plain Percent-Encoding (space is encoded with %20).
like image 120
Gumbo Avatar answered Sep 25 '22 02:09

Gumbo


The cunningly-named urlencode() and urldecode().

However, you shouldn't need to use urldecode() on variables that appear in $_POST and $_GET.

like image 23
Oliver Charlesworth Avatar answered Sep 24 '22 02:09

Oliver Charlesworth