Useful functions in PHP
2008-10-01 11:03
148 查看
从手册上整理了一些有用且比较常用的php函数, 便于以后查阅.
1. htmlspecialchars
Convert special characters to HTML entities (PHP 4, PHP 5)
http://www.php.net/htmlspecialchars[/b]
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) 只处理双引号
ENT_QUOTES
Will convert both double and single quotes 处理双引号和单引号
ENT_NOQUOTES
Will leave both double and single quotes unconverted 不处理双引号和单引号
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (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('~([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
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
Returns string with '<br />' or '<br>' inserted before all newlines.
Example #1 using nl2br()
<?php
echo 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
<?php
echo 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
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
$url = "www.google.com/?q=alka rani&start=100";
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%3D100
www.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
Decodes any %## encoding in the given string.
See also:
rawurlencode()
rawurldecode()
9.
addslashes — Quote string with slashes
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 — Un-quotes a quoted string
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);
?>
[/b]addcslashes()
mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
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
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:
str_replace()
str_ireplace()
ereg()
eregi()
ereg_replace()
eregi_replace()
preg_replace()
10. realpath
(PHP 4, PHP 5)
realpath — Returns canonicalized absolute pathname
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
<?php
chdir('/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.
<?php
echo realpath('/windows/system32');
?>
The above example will output:
[/b]basename()
1. htmlspecialchars
Convert special characters to HTML entities (PHP 4, PHP 5)
http://www.php.net/htmlspecialchars[/b]
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) 只处理双引号
ENT_QUOTES
Will convert both double and single quotes 处理双引号和单引号
ENT_NOQUOTES
Will leave both double and single quotes unconverted 不处理双引号和单引号
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (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('~([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()
<?php
echo 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
<?php
echo 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
$url = "www.google.com/?q=alka rani&start=100";
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%3D100
www.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:
rawurlencode()
rawurldecode()
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[/b]
[/b]addcslashes()
stripcslashes()
get_magic_quotes_gpc()
[/b]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 [b]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:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
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:
hello all, I said hi
See also:
str_replace()
str_ireplace()
ereg()
eregi()
ereg_replace()
eregi_replace()
preg_replace()
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
<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?>
The above example will output:
/etc/passwd
Example #2 realpath() on Windows
On windows realpath() will change unix style paths to windows style.
<?php
echo realpath('/windows/system32');
?>
The above example will output:
C:/WINDOWS/System32
See Also[/b]
[/b]basename()
dirname()
pathinfo()
相关文章推荐
- Useful functions to provide secure PHP application
- Zen Cart在PHP5.3环境下出现的Fatal error: Cannot redeclare date_diff() in /zencart/includes/functions/functions_general.php on line 1481错误的解决方法
- Warning: array_merge() [function.array-merge]: Argument #2 is not an array in e\\class\\functions.php on line 2193
- 9 useful php functions
- 9 Useful PHP Functions and Features You Need to Know
- Cannot use __try in functions that require object unwinding
- C++对象模型——Inline Functions(第四章)
- PHP Warning: Module 'json' already loaded in Unknown on line 0
- 像php一样,在smarty模板中使用in_array检查数组值
- phpmyadmin出现“Cannot start session without errors, please check errors given in your PHP and/or webs”
- FastCGI sent in stderr: "PHP message: PHP Fatal error: Call to undefined function __() in
- 报错PHP Warning: imagejpeg(): Filename cannot be empty in……
- php使用ZipArchive提示Fatal error: Class ZipArchive not found in的解决方法
- PHP微信公众号服务端提示Notice: Undefined index: HTTP_RAW_POST_DATA in xxxx,且无法正常返回的解决办法
- Surrogate Loss Functions in Machine Learning
- 注意php in_array带来的低性能
- PHP操作RabbitMQ消息接收不到的问题【cannot publish to internal exchange 'push-apns' in vhost 'pushHost】
- Dates in PHP and MySQL
- php晋级之路–Life In Blogcn
- usage of fscanf and other read functions in C/C++