Programmazione in linguaggio PHP by Andrea Mantoni Ultima modifica: %%mtime(%d %B %Y) = Introduzione = PHP è il linguaggio di scripting server-side più usato al mondo, grazie sopratutto alle sue elevate performance. confronto con altri linguaggi server-side scripting: - PHP: web-specific language, faster, sintassi semplice, higher security risks, non standardizzato, libreria di funzioni builtin più ampia - JSP: higher security, lower performance, custom tags, embeddable expression language - ASP: Microsoft proprietary, sintassi semplice - Perl: general-purpose language, older, sintassi + complicata OSS.: PHP facilita il riuso di codice scritto in C, mentre JSP facilita il riuso di codice Java. PHP è utilizzato anche come linguaggio di scripting per la shell, per la sua ampia standard library. = Sintassi = In generale, la sintassi di PHP è un mix tra: - linguaggi imperativi C-like - linguaggi di scripting (Bash shellscript, etc.) caratteristiche comuni con C/C++: - freeform-language (gli spazi nel codice sono ignorati) - curly-brace syntax supportata: { ... } - statements are terminated by a semicolon ";" - variable names are case sensitive (BUT NOT function and class names) - implicit casting - implicit boolean expressions (0=false, !0=true) - tipi con storage platform-specific (32-bit, 64-bit, etc.) differenze con C/C++: - implicit variable declaration - weak typing (variable types does not need to be specified in advance) - variables must be prefixed with a dollar symbol in code (come in shellscript) ?? - le variabili possono essere inserite direttamente nelle costanti stringa senza escapes - function and class names case in-sensitive (variables are not) - colon syntax (alternativa a curly-brace syntax): "{" -> ":" "}" -> "endXX;" - arrays as ordered maps == HTML delimiters e commenti == I blocchi di codice PHP devono sempre essere delimitati (altrimenti vengono interpretati come stringhe HTML costanti). delimiters HTML (consigliati/always available): delimiters HTML alternativi (not recommended/optional): (short opening tags) <% ... %> (ASP-style syntax) echo shortcut syntax (req. PHP >=5.4): commenti: /* block comment */ // inline comment # inline comment == Operatori == L'accesso alle variabili (sia in dichiarazione sia in referenziazione) avviene sempre con l'operatore "$": $var = 0; print($var); OSS.: sono supportati tutti gli operatori del C, con alcune aggiunte. arithmetic: + - * / % logical: and, && or, || xor ! comparison (for both numbers and strings): == Equal === Identical = same value and same type != <> Not equal !== Not identical < > ... string: . concatenation (does not modify left-operand) .= append (modify left-operand) OSS.: "+" non funziona per concatenare le stringhe, è solo un operatore aritmetico! array: $a + $b Union $a == $b Equality test = same key/value pairs $a === $b Identity test = same key/value pairs in the same order and of the same types (faster) $a != $b Inequality test $a <> $b Inequality test $a !== $b Non-identity test (faster) error control operator: @expression -> any error messages that might be generated by that expression will be ignored. == Tipi e costanti == Primitive PHP Data Types: (boolean) or (bool) true|false (case insensitive) (integer) 0 (float) 0.0 (string) 'stringa' (single quoted, non supporta slash escapes) "stringa" (double quoted, supporta slash escapes) $str = << value1, key2 => value2, ... ); $arr = array( value1, value2, ... ); // dichiarazione senza chiavi -> vengono assegnate chiavi numeriche auto-incrementate creazione/modifica con square bracket syntax: $arr[key1] = value1; // aggiunge un elemento con chiave "key1" e con valore "value1" $arr[key2] = value2; ... // senza chiavi: $arr[1] = value1; $arr[2] = value2; ... rimozione: unset($arr[key]); // This removes the element from the array unset($arr); // This deletes the whole array append an item: $arr[] = value; ricerca: in_array('fish', $arr)) lunghezza: count($arr) sizeof($arr) // alias del precedente subarray: $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 NOTA: "key" may only be an integer or string "value" may be any value of any type NOTA2: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero). == Control structures == Le strutture di controllo sono le stesse del C: if (condition): // code here elseif (condition): // code here else: // code here endif; switch($n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } OSS.:: non supporta la colon syntax while (expr): // code here break; continue; ... endwhile; do { ... } while(expr); OSS.:: non supporta la colon syntax for(init; cond; exec): statement ... endfor; foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement NOTA: è una versione semplificata di for per ciclare gli array esempi: for ($counter = 0; $counter <= 5; $counter++ ) { $position = strpos( $text, "\n", $position) + 1; } = Builtin functions = empty(var); -> testa se un oggetto/array/stringa è vuoto (ha 0 elementi) isset(var); -> NULL-test unset(var); -> distrugge una variabile count/sizeof(var); -> ritorna la dimensione di un oggetto/array gestione headers: header("Name: value"); // imposta un header nella response header("Location: gal/index.php"); // client-side redirect gestione cookies: setcookie('name', 'value'); gestione sessioni: session_start(); session_destroy(); uscita: exit([ string $status ] ); // termina l'esecuzione dello script corrente die(); // equivalente al prec lettra del body della request: $body = @file_get_contents('php://input'); gestione tempo: string date ( string $format [, int $timestamp = time() ] ); ... http://it1.php.net/manual/en/function.date.php Sono supportate le seguenti funzioni dalla stdlib: sprintf sscanf strlen strcmp strcasecmp strstr strtok strtolower strtoupper substr trim ... http://www.php.net/manual/en/funcref.php http://php.net/quickref.php == Language construct == A differenza delle funzioni, possono essere invocate anche senza parentesi che circondano la lista degli argomenti. echo 'string'; // stampa nello stream HTML print 'string'; // come la precedente, ma ritorna anche uno status (indicating if it was successful or not) include 'url'; // server-side include (se la pagina non è trovata produce un warning) require 'url'; // server-side include (se la pagina non è trovata produce un errore fatale) require_once 'url'; // come le precedenti, include_once 'url'; // + protezione automatica per multiple includes OSS.: non c'è una server-side redirect = Predefined Variables = $GLOBALS $_SERVER $_REQUEST['key'] -> union of _GET, _POST and _COOKIE $_GET['key'] $_POST['key'] $_COOKIE['key'] $_SESSION['key'] -> session scoped data variables $_FILES $_ENV NOTA: se vuota "$_GET['key']" ritorna la stringa "undefined". = Magic Constants = __LINE__ -> current line number __FILE__ -> file path __DIR__ -> directory path __FUNCTION__ -> function name __CLASS__ -> class name __METHOD__ -> method name __NAMESPACE__ -> namespace = HTTP extension = http://www.php.net/manual/en/book.http.php string http_get_request_body(); // NOTE: req. HTTP extension resource http_get_request_body_stream(); = Frameworks = I framework PHP più popolari sono: ... == Custom tags == Le custom HTML tags non sono ufficialmente supportate dal linguaggio, cmq sono state implementate da terze parti: - PHP Simple HTML DOM Parser http://sourceforge.net/projects/simplehtmldom/ - CustomTags http://buggedcom.co.uk/projects/ - PHP/XML Template Engine http://www.hyperkit-software.com/projects/phptemplates/tutorials/writing_your_own_tag_library/index.html - PHP Standard Tag Library - a php templating system modeled after JSTL (req. PHP 5) http://www.redtreesystems.com http://sourceforge.net/projects/php-stl/ https://github.com/jcorbinredtree/php-stl ... http://stackoverflow.com/questions/3220022/creating-custom-html-tags-for-cms/3220078 = Standard library = == String functions == addcslashes() Returns a string with backslashes in front of the specified characters addslashes() Returns a string with backslashes in front of predefined characters bin2hex() Converts a string of ASCII characters to hexadecimal values chop() Removes whitespace or other characters from the right end of a string chr() Returns a character from a specified ASCII value chunk_split() Splits a string into a series of smaller parts convert_cyr_string() Converts a string from one Cyrillic character-set to another convert_uudecode() Decodes a uuencoded string convert_uuencode() Encodes a string using the uuencode algorithm count_chars() Returns information about characters used in a string crc32() Calculates a 32-bit CRC for a string crypt() One-way string encryption (hashing) echo() Outputs one or more strings explode() Breaks a string into an array fprintf() Writes a formatted string to a specified output stream get_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities() hebrev() Converts Hebrew text to visual text hebrevc() Converts Hebrew text to visual text and new lines (\n) into
hex2bin() Converts a string of hexadecimal values to ASCII characters html_entity_decode() Converts HTML entities to characters htmlentities() Converts characters to HTML entities htmlspecialchars_decode() Converts some predefined HTML entities to characters htmlspecialchars() Converts some predefined characters to HTML entities implode() Returns a string from the elements of an array join() Alias of implode() lcfirst() Converts the first character of a string to lowercase levenshtein() Returns the Levenshtein distance between two strings localeconv() Returns locale numeric and monetary formatting information ltrim() Removes whitespace or other characters from the left side of a string md5() Calculates the MD5 hash of a string md5_file() Calculates the MD5 hash of a file metaphone() Calculates the metaphone key of a string money_format() Returns a string formatted as a currency string nl_langinfo() Returns specific local information nl2br() Inserts HTML line breaks in front of each newline in a string number_format() Formats a number with grouped thousands ord() Returns the ASCII value of the first character of a string parse_str() Parses a query string into variables print() Outputs one or more strings printf() Outputs a formatted string quoted_printable_decode() Converts a quoted-printable string to an 8-bit string quoted_printable_encode() Converts an 8-bit string to a quoted printable string quotemeta() Quotes meta characters rtrim() Removes whitespace or other characters from the right side of a string setlocale() Sets locale information sha1() Calculates the SHA-1 hash of a string sha1_file() Calculates the SHA-1 hash of a file similar_text() Calculates the similarity between two strings soundex() Calculates the soundex key of a string sprintf() Writes a formatted string to a variable sscanf() Parses input from a string according to a format str_getcsv() Parses a CSV string into an array str_ireplace() Replaces some characters in a string (case-insensitive) str_pad() Pads a string to a new length str_repeat() Repeats a string a specified number of times str_replace() Replaces some characters in a string (case-sensitive) str_rot13() Performs the ROT13 encoding on a string str_shuffle() Randomly shuffles all characters in a string str_split() Splits a string into an array str_word_count() Count the number of words in a string strcasecmp() Compares two strings (case-insensitive) strchr() Finds the first occurrence of a string inside another string (alias of strstr()) strcmp() Compares two strings (case-sensitive) OSS.: the "==" and "!=" operators only returns true or false strcoll() Compares two strings (locale based string comparison) strcspn() Returns the number of characters found in a string before any part of some specified characters are found strip_tags() Strips HTML and PHP tags from a string stripcslashes() Unquotes a string quoted with addcslashes() stripslashes() Unquotes a string quoted with addslashes() stripos() Returns the position of the first occurrence of a string inside another string (case-insensitive) stristr() Finds the first occurrence of a string inside another string (case-insensitive) strlen() Returns the length of a string strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive) strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive) strncasecmp() String comparison of the first n characters (case-insensitive) strncmp() String comparison of the first n characters (case-sensitive) strpbrk() Searches a string for any of a set of characters strpos() Returns the position of the first occurrence of a string inside another string (case-sensitive) strrchr() Finds the last occurrence of a string inside another string strrev() Reverses a string strripos() Finds the position of the last occurrence of a string inside another string (case-insensitive) strrpos() Finds the position of the last occurrence of a string inside another string (case-sensitive) strspn() Returns the number of characters found in a string that contains only characters from a specified charlist strstr() Finds the first occurrence of a string inside another string (case-sensitive) strtok() Splits a string into smaller strings strtolower() Converts a string to lowercase letters strtoupper() Converts a string to uppercase letters strtr() Translates certain characters in a string substr() Returns a part of a string substr_compare() Compares two strings from a specified start position (binary safe and optionally case-sensitive) substr_count() Counts the number of times a substring occurs in a string substr_replace() Replaces a part of a string with another string trim() Removes whitespace or other characters from both sides of a string ucfirst() Converts the first character of a string to uppercase ucwords() Converts the first character of each word in a string to uppercase vfprintf() Writes a formatted string to a specified output stream vprintf() Outputs a formatted string vsprintf() Writes a formatted string to a variable wordwrap() Wraps a string to a given number of characters == Filesystem functions == basename() Returns the filename component of a path chgrp() Changes the file group chmod() Changes the file mode chown() Changes the file owner clearstatcache() Clears the file status cache copy() Copies a file delete() See unlink() or unset() dirname() Returns the directory name component of a path disk_free_space() Returns the free space of a directory disk_total_space() Returns the total size of a directory diskfreespace() Alias of disk_free_space() fclose() Closes an open file feof() Tests for end-of-file on an open file fflush() Flushes buffered output to an open file fgetc() Returns a character from an open file fgetcsv() Parses a line from an open file, checking for CSV fields fgets() Returns a line from an open file fgetss() Returns a line, with HTML and PHP tags removed, from an open file file() Reads a file into an array file_exists() Checks whether or not a file or directory exists file_get_contents() Reads a file into a string file_put_contents Writes a string to a file fileatime() Returns the last access time of a file filectime() Returns the last change time of a file filegroup() Returns the group ID of a file fileinode() Returns the inode number of a file filemtime() Returns the last modification time of a file fileowner() Returns the user ID (owner) of a file fileperms() Returns the permissions of a file filesize() Returns the file size filetype() Returns the file type flock() Locks or releases a file fnmatch() Matches a filename or string against a specified pattern fopen() Opens a file or URL fpassthru() Reads from an open file, until EOF, and writes the result to the output buffer fputcsv() Formats a line as CSV and writes it to an open file fputs() Alias of fwrite() fread() Reads from an open file fscanf() Parses input from an open file according to a specified format fseek() Seeks in an open file fstat() Returns information about an open file ftell() Returns the current position in an open file ftruncate() Truncates an open file to a specified length fwrite() Writes to an open file glob() Returns an array of filenames / directories matching a specified pattern is_dir() Checks whether a file is a directory is_executable() Checks whether a file is executable is_file() Checks whether a file is a regular file is_link() Checks whether a file is a link is_readable() Checks whether a file is readable is_uploaded_file() Checks whether a file was uploaded via HTTP POST is_writable() Checks whether a file is writeable is_writeable() Alias of is_writable() lchgrp() Changes group ownership of symlink lchown() Changes user ownership of symlink link() Creates a hard link linkinfo() Returns information about a hard link lstat() Returns information about a file or symbolic link mkdir() Creates a directory move_uploaded_file() Moves an uploaded file to a new location parse_ini_file() Parses a configuration file parse_ini_string() Parses a configuration string pathinfo() Returns information about a file path pclose() Closes a pipe opened by popen() popen() Opens a pipe readfile() Reads a file and writes it to the output buffer readlink() Returns the target of a symbolic link realpath() Returns the absolute pathname realpath_cache_get() Returns realpath cache entries realpath_cache_size() Returns realpath cache size rename() Renames a file or directory rewind() Rewinds a file pointer rmdir() Removes an empty directory set_file_buffer() Sets the buffer size of an open file stat() Returns information about a file symlink() Creates a symbolic link tempnam() Creates a unique temporary file tmpfile() Creates a unique temporary file touch() Sets access and modification time of a file umask() Changes file permissions for files unlink() Deletes a file = Fonti = manuale ufficiale http://www.php.net/manual/en/ http://en.wikibooks.org/wiki/PHP_Programming http://it.wikibooks.org/wiki/PHP http://php.html.it/