Home • ReadSpeaker • Formula 4 • Rivista English4Life • I buoni acquisti • Daisy Stories
Arranger Stories
• Il Blog di Daisy • Grammatica • Studia l'inglese con noi
Risorse sfiziose • Testi paralleli (Wikipedia) • Testi paralleli (altri) • The West Family
Classici in inglese
• Wikibooks •
Corso di base + schede lessicali • Metodo Casiraghi-Jones • Come studiare • Tips • Risposte • Articoli in italiano • Enciclopedia

  IMPARA L'INGLESE CON BABYLON!
Come servizio al nostro pubblico, riportiamo qui a sinistra il box di traduzione di Babylon
. Se c'θ una parola inglese che non capisci, digitala nella casella Traduci... , clicca su GO e subito si aprirΰ una finestra con la traduzione italiana. Per una maggiore comoditΰ e completezza, puoi scaricare qui gratuitamente per un mese Babylon Pro, lo strumento in assoluto piω utile per chi vuole imparare l'inglese. Da oggi anche con il traduttore di frasi inglesi incorporato!
 
 
 


CONTENTS

  1. Accrisoft
  2. Active calendar
  3. ActiveState Komodo
  4. AdLogger
  5. Apache HTTP Server
  6. AutoContent
  7. BakeSale
  8. Bblocked
  9. BBlog
  10. BbPress
  11. Beehive Forum
  12. B2evolution
  13. Bluefish
  14. Chlorine Boards
  15. CMScout
  16. CMSimple
  17. CMS Made Simple
  18. Content Protector
  19. Coppermine Photo Gallery
  20. CRE Loaded
  21. Cutenews
  22. DB DataObject FormBuilder
  23. Divine
  24. Dokeos
  25. DotOrg
  26. Dragonfly CMS
  27. Dreamweaver
  28. Drupal
  29. Dynamic Web page
  30. E107
  31. Eclipse
  32. 25 Essential PHP Functions
  33. FusionBB
  34. Gallery Project
  35. Gedit
  36. Group-Office
  37. HawHaw
  38. IceBB
  39. 4images
  40. Introduction to PHP
  41. Introduction to PHP Learning Guide
  42. IonCube Ltd.
  43. JEdit
  44. Joomla
  45. LAMP
  46. Linux
  47. List of PHP editors
  48. List of PHP libraries
  49. Maguma
  50. Mambo
  51. MediaWiki
  52. MetaBB
  53. Midgard
  54. MiniBB
  55. Monkey Boards
  56. Moodle
  57. MySQL
  58. Ning
  59. Nucleus CMS
  60. Nuke-Evolution
  61. NuSphere Corporation
  62. OpenPHPNuke
  63. Orbit42-Base
  64. OsCommerce
  65. Paamayim Nekudotayim
  66. Phalanger
  67. Php
  68. PHP accelerator
  69. PhpBB
  70. PhpBB Reloaded
  71. PHP Constants
  72. PHPDoc
  73. PhpDocumentor
  74. PHPEdit
  75. PHP Excel Reader
  76. PHP Extension Community Library
  77. PhpGedView
  78. PHP-GTK
  79. PhpLDAPadmin
  80. PHP License
  81. Phplist
  82. PhpMyAdmin
  83. PhpMyVisites
  84. Phpns
  85. PHP-Nuke
  86. PhpPgAdmin
  87. PhpWiki
  88. PmWiki
  89. PostNuke
  90. PSPad
  91. PunBB
  92. PuzzleApps
  93. Quanta Plus
  94. Rasmus Lerdorf
  95. ReallySimpleCMS
  96. Refbase
  97. RGameScript Pro
  98. Santy
  99. SciTE
  100. Serendipity weblog
  101. Simple Machines Forum
  102. SimpleXML
  103. SiteFrame
  104. Smarty
  105. SquirrelMail
  106. Textpattern
  107. Thatware
  108. Think Tank Forums
  109. TikiWiki
  110. TorrentVolve
  111. TYPO3
  112. UBB.threads
  113. UltraEdit
  114. UNITED-NUKE
  115. Variables in PHP
  116. VBulletin
  117. WakkaWiki
  118. Web Application Structure for PHP
  119. Webwm
  120. Wikindx
  121. WikkaWiki
  122. WordPress
  123. WordPress MU
  124. Xaraya
  125. XOOPS
  126. Zen Cart
  127. Zend Engine
  128. Zend Studio
  129. Zend Technologies
  130. Zentri
  131. ZPanel

 



PHP LANGUAGE AND PRODUCTS
This article is from:
http://en.wikiversity.org/wiki/25_Essential_PHP_Functions

All text is available under the terms of the GNU Free Documentation License: http://en.wikipedia.org/wiki/Wikipedia:Text_of_the_GNU_Free_Documentation_License 

25 Essential PHP Functions

From Wikiversity

 
Jump to: navigation, search

This is a list of 25 interesting PHP functions that are useful in a variety of situations. Please do not make changes to the actual set of functions without first discussing them on the talk page.

Contents

  • 1 Function list
  • 2 Ceil()
    • 2.1 Usage
    • 2.2 Practical applications
    • 2.3 See also
  • 3 Count()
    • 3.1 Usage
    • 3.2 Practical applications
  • 4 Die()
    • 4.1 Usage
    • 4.2 Practical applications
    • 4.3 See also
  • 5 Echo()
    • 5.1 Usage
    • 5.2 Practical applications
  • 6 Empty()
    • 6.1 Usage
    • 6.2 Practical applications
    • 6.3 Pitfall
  • 7 Exit()
  • 8 file_get_contents()
    • 8.1 Usage
    • 8.2 Practical applications
  • 9 file_put_contents()
    • 9.1 Usage
    • 9.2 Practical applications
    • 9.3 PHP4 Workaround
  • 10 getenv()
    • 10.1 Usage
    • 10.2 Practical applications
    • 10.3 See also
  • 11 header()
    • 11.1 Usage
    • 11.2 Practical applications
    • 11.3 See also

 

Function list

Following is the raw list of 25, in alphabetical order:

  1. ceil()
  2. count()
  3. die()
  4. echo()
  5. empty()
  6. exit()
  7. file_get_contents()
  8. file_put_contents()
  9. getenv()
  10. header()
  11. htmlentities()
  12. include()
  13. ini_set()
  14. isset()
  15. mail()
  16. md5()
  17. mkdir()
  18. phpinfo()
  19. preg_match()
  20. print_r()
  21. rand()
  22. require()
  23. str_replace()
  24. str_len()
  25. trim()

 

Ceil()

float ceil (float value)

Rounds up the supplied float value to the next integer and returns the result.

 

Usage

<?php
$a = 2.444;
echo ceil($a); // 3
?>

 

Practical applications

Can be used to check if a number divides evenly with another - for example:

<?php
$num1 = 5;
$num2 = 7;
$div = $num2 / $num1;
if (ceil($div) == $div)
    echo "$num2 divides into $num1 evenly.";
else
    echo "$num2 does not divide into $num1 easily ($div).";
?>

 

See also

  • Floor() - function that does the opposite

 

Count()

int count (mixed var)

Returns an integer value of the number of elements in the supplied variable - generally an array, as anything else will return 1.

 

Usage

<?php
$stuff[0] = 4;
$stuff[1] = 3;
$stuff[2] = 2;
echo count($stuff); // 3
?>

 

Practical applications

Handling every element of an array - for example:

<?php
$values[] = 5;
$values[] = 3;
$values[] = 6;
$values[] = -1;
$num = count($values);
for ($i=0; $i < $num + 1; $i++) $values[$i] += 2;
?>

Bear in mind that this could be done without count() using the foreach case structure anyway.

 

Die()

void die ([string status])

Terminates the current script execution. If parameter 'status' is specified, also displays 'status' in an error message. Alias for exit().

 

Usage

<?php
if (!file_get_contents("stats.txt")) die("Could not fetch statistics history.");
?>

 

Practical applications

Terminating the script if a database connection cannot be opened.

<?php
mysql_connect("localhost","root","") or die("Could not connect to database server.");
?>

 

See also

  • Exit() - function that does exactly the same thing, but sounds slightly more graceful

 

Echo()

void echo (string outputstring)

Outputs data to the current stream (console, apache request etc.). Is more a language construct than a function, and can therefore be used without the parenthesis.

 

Usage

<?php
echo("Some text."); // Will output 'Some text.'
echo "Some text."; // Will output 'Some text.' just as above
?>

 

Practical applications

<?php
if ( $_SESSION['loggedin'] )
{
    echo "Welcome, " . $_SESSION['username'];
}
else
{
    echo "Access denied. This area is for members only. Please login.";
}
?>

 

Empty()

bool empty (mixed var)

Used to check if a variable is empty. Note: It is used to only check variables, thus empty(trim($var)); will result in a parse error.

 

Usage

<?php
$var = 'Hello';
if (empty($var))
    echo 'The variable is empty';
else
    echo 'The variable is not empty'; // True in this case
?>

 

Practical applications

<?php
$name = $_POST['name'];
if (empty($name))
    echo 'You need to enter your name';
?>

 

Pitfall

0 is considered empty.

<?php
$var = 0;
if (empty($var))
    echo 'The variable is empty'; // True in this case
else
    echo 'The variable is not empty'; 
?>

 

Exit()

void exit ( [String status] )
void exit ( int status )

Exactly the same as die.

 

file_get_contents()

String file_get_contents ( String filename [, boolean use_include_path [, resource context [, int offset [, int maxlen]]]] )

Reads a file into a string.

 

Usage

<?php
echo file_get_contents('my_file.txt');
?>

 

Practical applications

<?php
$contents = file_get_contents('data.txt');
echo $contents; // Would output whatever is in the file
?>

 

file_put_contents()

int file_put_contents ( string filename, mixed data , int flags , resource context )

Writes data to a file. The flags can be FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX.

Note: This is a PHP5 function only.

Will return false on failure, or the number of bytes written to the file.

 

Usage

<?php
file_put_contents('my_file.txt', 'Hello', FILE_APPEND); // Will append 'Hello' to the specified file
?>

 

Practical applications

<?php
$ip = $_SERVER['REMOTE_ADDR']; // Get client's IP address
file_put_contents('ips.txt', "\n",$ip, FILE_APPEND);
?>

 

PHP4 Workaround

There is nothing really special about this function, except it saves your time (it basically calls fopen, fwrite and fclose). Here is something that can be used for making sure your PHP script works with PHP5 and PHP4:

<?php
if (function_exists('file_put_contents') === false)
{
    function file_put_contents($file, $data)
    {
        $fh = @fopen($file, 'w');
        if ($fh === false)
            return false;
        else
        {
            fwrite($fh, $data);
            fclose($fh);
            return true;
        }
    }
}
?>

This is of course a very basic replacement and does not take into account any flags which goes beyond the scope of this document.

 

getenv()

string getenv ( string varname)

Returns the value of an environment variable

 

Usage

<?php
echo getenv('HTTP_USER_AGENT');  //will output what web browser is currently viewing the page
?>

 

Practical applications

Allows you to execute commands based on server information

<?php
if (strpos(getenv('HTTP_USER_AGENT'), "Mozilla") > 0)
{
    // Execute Mozilla specific code
}
?>

 

See also

  • apache_getenv()
  • phpinfo()
  • putenv()
  • Superglobals

 

header()

void header (string string [, bool replace [, int http_response_code]] )

Updates the HTTP headers that are sent to the web browser

 

Usage

<?php
header("Cache-Control: no-cache");
?>

 

Practical applications

One use for the header fuction is to redirect the browser to a diffrent web site

<?php
if ($_POST['username'] == "")
{
    header("Location: http://my.url.com");
    exit;
}
// Redirects the browser to http://my.url.com
?>

Another is to change how the browser will interpret the data that is sent to it

<?php
header("Content-Type: text/xml")
echo '<?xml version="1.0" encoding="ISO-8859-1" ?>';
// Rest of XML output
?>

 

See also

  • HTTP/1.1 specification
  • headers_sent()
  • setcookie()
Retrieved from "http://en.wikiversity.org/wiki/25_Essential_PHP_Functions"

 

AVAILABLE
WIKIBOOKS

•••••••••••

 

 

Translate Text
Original text: