Useful functions in PHP
從手冊上整理了一些有用且比較常用的php函式, 便於以後查閱.
1. htmlspecialchars
Convert special characters to HTML entities (PHP 4, PHP 5)
string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
quote_style constants ENT_COMPAT Will convert double-quotes and leave single-quotes alone (default) 只處理雙引號The translations performed are:
- '&' (ampersand) becomes '&'
- '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
- ''' (single quote) becomes ''' only when
- '<' (less than) becomes '<'
- '>' (greater than) becomes '>'
Example #1 htmlspecialchars() example
<?php$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
2. htmlspecialchars_decode
(PHP 5 >= 5.1.0)
htmlspecialchars_decode — Convert special HTML entities back to characters
Example #1 A htmlspecialchars_decode() example
<?php$str = '<p>this -> "</p>';
echo htmlspecialchars_decode($str);
// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>
The above example will output:
<p>this -> "</p>
<p>this -> "</p>
3. htmlentities
(PHP 4, PHP 5)
htmlentities — Convert all applicable characters to HTML entities
Example #1 A htmlentities() example
<?php$str = "A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
4. html_entity_decode
(PHP 4 >= 4.3.0, PHP 5)
html_entity_decode — Convert all HTML entities to their applicable characters
Example #1 Decoding HTML entities
<?php$orig = "I'll /"walk/" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
// For users prior to PHP 4.3.0 you may do this:
function unhtmlentities($string)
{
// replace numeric entities
$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("//1"))', $string);
$string = preg_replace('~&#([0-9]+);~e', 'chr("//1")', $string);
// replace literal entities
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}
$c = unhtmlentities($a);
echo $c; // I'll "walk" the <b>dog</b> now
?>
5. strip_tags
(PHP 4, PHP 5)
strip_tags — Strip HTML and PHP tags from a string
Description
string strip_tags ( string $str [, string $allowable_tags ] )Example #1 strip_tags() example
<?php$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "/n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
The above example will output:
Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
6. nl2br
(PHP 4, PHP 5)
nl2br — Inserts HTML line breaks before all newlines in a string
Description
string nl2br ( string $string [, bool $is_xhtml ] )Returns string with '<br />' or '<br>' inserted before all newlines.
Example #1 using nl2br()
<?phpecho nl2br("foo isn't/n bar");
?>
The above example will output:
foo isn't<br />
bar
Example #2 Generating valid HTML markup using the is_xhtml parameter
<?phpecho nl2br("Welcome/r/nThis is my HTML document", false);
?>
The above example will output:
Welcome<br>
This is my HTML document
7. urlencode
(PHP 4, PHP 5)
urlencode — URL-encodes string
Description
string urlencode ( string $str )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.
Example #1 urlencode() example
<?php echo urlencode($url); echo "<br/>"; echo rawurlencode($url); echo "<br/>"; echo urldecode(urlencode($url)); echo "<br/>"; echo rawurldecode(rawurlencode($url)); echo "<br/>"; echo rawurldecode(urlencode($url)); echo "<br/>"; echo urldecode(rawurlencode($url)); ?> result: www.google.com%2F%3Fq%3Dalka+rani%26start%3D100www.google.com%2F%3Fq%3Dalka%20rani%26start%3D100
www.google.com/?q=alka rani&start=100
www.google.com/?q=alka rani&start=100
www.google.com/?q=alka+rani&start=100
www.google.com/?q=alka rani&start=100 8. urldecode
(PHP 4, PHP 5)
urldecode — Decodes URL-encoded string
Description
string urldecode ( string $str )Decodes any %## encoding in the given string.
See also: 9.addslashes
(PHP 4, PHP 5)
addslashes — Quote string with slashes
Description
string addslashes ( string $str )Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (/) and NUL (the NULL byte).
The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.
Example #1 An addslashes() example
<?php$str = "Is your name O'reilly?";
// Outputs: Is your name O/'reilly?
echo addslashes($str);
?> 10.
stripslashes
(PHP 4, PHP 5)
stripslashes — Un-quotes a quoted string
Description
string stripslashes ( string $str )Un-quotes a quoted string.
Example #1 A stripslashes() example
<?php$str = "Is your name O/'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>
See Also
11. mysql_real_escape_string
(PHP 4 >= 4.3.0, PHP 5, PECL mysql:1.0)
mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
Description
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: /x00, /n, /r, /, ', " and /x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
Example #1 An example SQL Injection Attack
<?php// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// This means the query sent to MySQL would be:
echo $query;
?>
The query sent to MySQL:
This would allow anyone to log in without a valid password.
Example #2 A "Best Practice" query
Using mysql_real_escape_string() around each variable prevents SQL Injection. This example demonstrates the "best practice" method for querying a database, independent of the Magic Quotes setting.
- <?php
- if (isset($_POST['product_name']) && isset($_POST['product_description']) && isset($_POST['user_id'])) {
- // Connect
- $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
- if(!is_resource($link)) {
- echo"Failed to connect to the server/n";
- // ... log the error properly
- } else {
- // Reverse magic_quotes_gpc/magic_quotes_sybase effects on those vars if ON.
- if(get_magic_quotes_gpc()) {
- $product_name = stripslashes($_POST['product_name']);
- $product_description = stripslashes($_POST['product_description']);
- } else {
- $product_name = $_POST['product_name'];
- $product_description = $_POST['product_description'];
- }
- // Make a safe query
- $query = sprintf("INSERT INTO products (`name`, `description`, `user_id`) VALUES ('%s', '%s', %d)",
- mysql_real_escape_string($product_name, $link),
- mysql_real_escape_string($product_description, $link),
- $_POST['user_id']);
- mysql_query($query, $link);
- if (mysql_affected_rows($link) > 0) {
- echo"Product inserted/n";
- }
- }
- } else {
- echo"Fill the form properly/n";
- }
- ?>
The query will now execute correctly, and SQL Injection attacks will not work.
9. strtr(PHP 4, PHP 5)
strtr — Translate certain characters
Description
string strtr ( string $str , string $from , string $to ) string strtr ( string $str , array $replace_pairs )This function returns a copy of str , translating all occurrences of each character in from to the corresponding character in to .
If from and to are different lengths, the extra characters in the longer of the two are ignored.
Example strtr() example with two arguments
<?php$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
The above example will output:
See also: 10. realpath(PHP 4, PHP 5)
realpath — Returns canonicalized absolute pathname
Description
string realpath ( string $path )realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path . and return the canonicalized absolute pathname.
Example #1 realpath() example
<?phpchdir('/var/www/');
echo realpath('./../../etc/passwd');
?>
The above example will output:
Example #2 realpath() on Windows
On windows realpath() will change unix style paths to windows style.
<?phpecho realpath('/windows/system32');
?>
The above example will output: