img jiji262

Useful functions in PHP

发表于2008/10/1 11:03:00  1404人阅读

从手册上整理了一些有用且比较常用的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
Will convert double-quotes and leave single-quotes alone (default) 只处理双引号
Will convert both double and single quotes 处理双引号和单引号
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 '&lt;'
  • '>' (greater than) becomes '&gt;'

Example #1 htmlspecialchars() example

$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

2. htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode —  Convert special HTML entities back to characters

Example #1 A htmlspecialchars_decode() example

$str = '<p>this -&gt; &quot;</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 -> &quot;</p>

3. htmlentities

(PHP 4, PHP 5)

htmlentities — Convert all applicable characters to HTML entities

Example #1 A htmlentities() example

$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
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

$orig = "I'll /"walk/" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; 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


string strip_tags ( string $str [, string $allowable_tags ] )

Example #1 strip_tags() example

$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


string nl2br ( string $string [, bool $is_xhtml ] )

 Returns string with '<br />' or '<br>' inserted before all newlines.

Example #1 using nl2br()

echo nl2br("foo isn't/n bar");

The above example will output:

foo isn't<br />

Example #2 Generating valid HTML markup using the is_xhtml parameter

echo nl2br("Welcome/r/nThis is my HTML document", false);

The above example will output:

This is my HTML document

7. urlencode

(PHP 4, PHP 5)

urlencode — URL-encodes string


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

$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));
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


string urldecode ( string $str )

 Decodes any %## encoding in the given string.

See also:


(PHP 4, PHP 5)

addslashes — Quote string with slashes


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

$str = "Is your name O'reilly?";

// Outputs: Is your name O/'reilly?
echo addslashes($str);


(PHP 4, PHP 5)

stripslashes — Un-quotes a quoted string


string stripslashes ( string $str )

 Un-quotes a quoted string.

Example #1 A stripslashes() example

$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


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

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";

// 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.

  1.  <?php
  2. if (isset($_POST['product_name']) && isset($_POST['product_description']) && isset($_POST['user_id'])) {
  3.    // Connect
  4.    $link = mysql_connect('mysql_host''mysql_user''mysql_password');
  5.    if(!is_resource($link)) {
  6.        echo "Failed to connect to the server/n";
  7.        // ... log the error properly
  8.    } else {
  10.        // Reverse magic_quotes_gpc/magic_quotes_sybase effects on those vars if ON.
  11.        if(get_magic_quotes_gpc()) {
  12.            $product_name        = stripslashes($_POST['product_name']);
  13.            $product_description = stripslashes($_POST['product_description']);
  14.        } else {
  15.            $product_name        = $_POST['product_name'];
  16.            $product_description = $_POST['product_description'];
  17.        }
  18.        // Make a safe query
  19.        $query = sprintf("INSERT INTO products (`name`, `description`, `user_id`) VALUES ('%s', '%s', %d)",
  20.                    mysql_real_escape_string($product_name$link),
  21.                    mysql_real_escape_string($product_description$link),
  22.                    $_POST['user_id']);
  23.        mysql_query($query$link);
  24.        if (mysql_affected_rows($link) > 0) {
  25.            echo "Product inserted/n";
  26.        }
  27.    }
  28. else {
  29.    echo "Fill the form properly/n";
  30. }
  31. ?>

 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 , 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

$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:
10. realpath

(PHP 4, PHP 5)

realpath — Returns canonicalized absolute pathname


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

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.

echo realpath('/windows/system32');

The above example will output:


See Also


0 0



取 消