Rc023 php online

1. #23 tech facts at your fingertips Get More Refcardz! Visit CONTENTS INCLUDE: PHP n Configuration n Popular PEAR Packages n Object-Oriented PHP n Regular…
of 7
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Related Documents
  • 1. #23 tech facts at your fingertips Get More Refcardz! Visit CONTENTS INCLUDE: PHP n Configuration n Popular PEAR Packages n Object-Oriented PHP n Regular Expressions n MySQL Integration n Hot Tips and more... By W. Jason Gilmore ABOUT THIS REFCARD POPULAR PEAR PACKAGES PHP is the worlds most popular server-side Web scripting The PHP Extension Application Repository (PEAR) is the de facto language, sporting a syntax simple enough to attract novice service for distributing reusable PHP components. Over 500 programmers yet powerful enough to run some of the worlds packages are available for download from, most popular websites, among them Yahoo!, Facebook, including these popular solutions: GameSpy, and Vimeo. PEAR Packages Description This reference card was created to help you quickly navigate Auth Facilitates authentication against IMAP, LDAP, plaintext files, some of PHPs most commonplace features, including object- most modern databases, RADIUS, and other authentication oriented programming, array and string manipulation, regular solutions. expressions, and MySQL integration. Config Aids in the management of application configuration data HTML_QuickForm2 Streamlines the creation, processing, and validation of HTML forms. CONFIGURATION HTML_Table Simplifies the generation of dynamic HTML tables HTTP_Upload Assists in the management of files uploaded through an PHPs behavior can be configured at a variety of levels: HTML form. Mail Facilitates transmission of e-mail through a website by Global Configuration supporting multiple mailer backends (including PHPs native The php.ini file is PHPs configuration file, containing more mail() function, Sendmail, and SMTP) than 200 directives capable of tweaking nearly every aspect of MDB2 A database abstraction layer supporting numerous databases, including MySQL, PostgreSQL, Oracle, and MS the languages behavior. This file is parsed every time PHP is SQL. invoked, which for the server module version occurs only when Net_UserAgent_ Provides information regarding the users browser and the web server starts, and every time for the CGI version. Detect operating system. PHPDocumentor Automates the code documentation creation and Host- and Directory-specific Configuration management process If you lack access to the php.ini file, you may be able to change PHPUnit Aids in the creation, execution and analysis of application desired directives within Apaches httpd.conf or .htaccess files. tests For instance, to force the display of all PHP errors for solely your XML_RPC Supports creation of PHP-driven XML-RPC clients and development domain (for instance, servers. add the following to a .htaccess file: php_flag display_errors on POPULAR FRAMEWORKS Each directive is assigned one of three permis- Web frameworks help the programmer to embrace best practices, Hot sion levels (PHP_INI_ALL, PHP_INI_PER_DIR, PHP_ simultaneously decreasing errors and eliminating redundant code. Tip INI_SYSTEM) which determines where it can be If you havent yet settled upon a framework, consider checking out set. Be sure to consult the PHP documentation one or several of the following popular solutions: before tweaking settings outside of the php.ini file. See for a complete list of directives. Get More Refcardz (They’re free!) Script-specific Configuration Occasionally youll want to tweak directives on a per-script basis. n Authoritative content For instance to change PHPs maximum allowable execution n Designed for developers time for a script tasked with uploading large files, you could call n Written by top experts the ini_set() function from within your PHP script like so: n Latest tools & technologies ini_set(max_execution_time, 60); n Hot tips & examples Changing the PHP File Extension n Bonus content online PHPs default file extension is .php, however you can change it to whatever you please by adding the desired extension to the n New issue every 1-2 weeks AddType directive within Apaches httpd.conf file. For instance to configure Apache to recognize .dzone as a supported PHP file Subscribe Now for FREE!PHP extension: AddType application/x-httpd-php .php .dzone DZone, Inc. |
  • 2. 2 PHP tech facts at your fingertipsPopular Frameworks, continued Object-Oriented PHP, continuedFramework Source Class ConstantsCakePHP Class constants are defined with the const keyword, and canCodeIgniter be referenced through the scope resolution operator (::). ForeZ Components instance, to define a constant identifying the RadioStation classPrado minimum supported PHP version:symfony Framework const MIN_PHP_VER = 5.3; You can then reference it outside the class like so: OBJECT-ORIENTED PHP echo RadioStation::MIN_PHP_VER; Extending ClassesCreating a Class Class hierarchies can be created using the extends keyword. ForA class defines the behavior and characteristics of an entity youd instance, an application tasked with cataloging all major medialike to represent in an application. A sample class follows: outlets might first define a MediaOutlet class which definesclass RadioStation { private $_id; some broad characteristics, and then child classes such as private $_name; RadioStation and TVStation would inherit from it: private $_frequency; class MediaOutlet { private $_band; protected $owner; private $_audioStream; protected $residentCountry; public function setBand($band) { $this->_band = $band; public function setOwner($owner) { } ... } public function getBand() { } return $this->_band; class RadioStation extends MediaOutlet { } ... ... }} If you wanted to prevent child classes (in this case,Object Instantiation RadioStation) from overriding a parent method, prefix it with the final keyword. For instance:To create an instance of a class (known as an object), you call theclass name like you would a function, preceding it with the new final public function setOwner($owner) {keyword: ... }$wtvn = new RadioStation(); Class AbstractionClass Constructors The aforementioned MediaOutlet class would be moreConstructors are useful for performing initialization tasks at accurately defined as an abstract class, because it would neverclass instantiation time, thereby saving you the hassle of calling be explicitly instantiated (instead, one would instantiate derivedadditional class methods. Constructors are declared using the classes such as RadioStation, TVStation, Newspaper, etc.).__construct() method, like so: Abstract classes are declared using the abstract keyword:function __construct($id="") { If specific station ID is requested, retrieve it // abstract class MediaOutlet { from the database ... if (isset($id)) } $this-find($id);} You can choose to override any methods found within an abstract class, which would then be inherited by its child classes,Class Destructors or alternatively you can declare them as abstract, requiring theseCustom class destructors can perform tasks when the object is methods be defined by any child.destroyed. You can create a destructor using the __destruct()method: Creating Interfacesfunction __destruct() { An interface helps developers rigorously enforce application printf(The radio station %s has been destroyed!, specifications, and is similar to an abstract class, but contains $this-name);} solely the required method signatures. Any class implementing the interface must also implement all defined interface methods.Attribute and Method Visibility Interfaces are defined using the interface keyword and theirPHP supports three levels of attribute and method visibility: names are typically prefixed with a capital I:Attribute and Description interface IRadioStation {Method Visibility public function setBand($band);Public Public attributes and methods can be accessed anywhere public function getBand(); }Private Private attributes and methods are only accessible within the class that defines them class RadioStation implements IRadioStation {Protected Protected attributes and methods are available to the class ... and its subclasses. } DZone, Inc. |
  • 3. 3 PHP tech facts at your fingertips Multidimensional Arrays, continued WORKING WITH ARRAYS Referencing an element isnt unlike the methods used forThe array is one of programmings most powerful data structures, indexed and associative arrays; its just a tad more verbose:capable of managing a seemingly endless variety of data. $channel = $stations[FM][WTVN];Creating an Array Determining Array SizeThe following two examples all create an array named $stations The number of elements found in an array can be determinedconsisting of three elements: using the count() function: // Outputs 3 stations are being tracked $stations = array ( printf(%d stations are being tracked, WTVN, WBNS, count($stations)); WYTS); Sorting Arrays $stations = array(); $count = array_push($stations, WTVN, WBNS, WYTS); PHP offers a powerful assortment of functions (more than 70) capable of sorting arrays in a variety of ways. Most of theseYou can create an array consisting of a character- or numerically- functions accept an optional parameter which can change thebased range using the range() function: sorting behavior. Four values are supported, including SORT_// $teenListenerDemographic = REGULAR for comparing elements without implicit typecasting,// array(13,14,15,16,17,18,19) SORT_NUMERIC for comparing elements numerically, SORT_STRING$teenListenerDemographic = range(13,19); for comparing elements as strings, and SORT_LOCALE_STRING, for sorting elements according to the defined locale.Retrieving Array Contents Description FunctionIndexed arrays such as those created so far can be accessed Sort an array while maintaining the bool asort(array $array [, int $sort_flags])according to their numerical offset (beginning with a zero- key associationbased offset). For instance to retrieve the second value in the Reverse sort an associative array bool arsort(array $array [, int $sort_flags])$stations array: while maintaining key association$callSignal = $stations[1]; Sort an associative array by key, bool ksort(array $array [, int $sort_flags]) maintaining index associationPerhaps the most flexible way to enumerate array contents is Reverse sort an associative array by bool krsort(array $array [, int $sort_flags])through the foreach statement: key, maintaining index associationforeach($stations AS $station) Sort an array case-insensitively in an bool natcasesort($array array) order logically presumed by humans printf(%sbr /, $station); Sort an array in an order logically bool natsort(array $array)Associative Arrays presumed by humans Sort an array in reverse order bool rsort(array $array [, int $sort_flags])Associative arrays give developers the opportunity to assignmeaningful context to both the array value and its corresponding Sort an array according to the bool usort(array $array, callback specifications of a user-defined $comparison_function)key: function$stations = array( Sort an array according to the bool uasort(array $array, callback WTVN = 610, specifications of a user-defined $comparison_function) WBNS = 1460, function, maintaining index WYTS = 1230 association); Key sort an array according to the bool uksort(array $array, callback specifications of a user-defined $comparison_function)You can then obtain a value (in this case the station/band) by functionreferencing its call signal: Consult the PHP manual for a complete listing: http://www.php.// $channel = 610 net/array.$channel = $stations[WTVN];The foreach statement proves equally useful for navigating STRING PARSINGassociative arrays:foreach($stations AS $key = value) PHP supports over 100 functions identified as specific to string printf(%s = %sbr /, $key, $value); parsing and manipulation. Following are the most commonlyMultidimensional Arrays used tasks.Multidimensional arrays are useful for representing more Description Functioncomplex data structures: Converting an array $stations = array(WTVN,WBNS,WYTS); to a string $stations = implode(,, $stations)$stations = array( // $stations = WTVN,WBNS,WYTS AM = Converting a string $stations = WTVN,WBNS,WYTS; array(WTVN = 610, to an array $stations = explode(,, $stations); // $stations[0]=WTVN, $stations[1]=WBNS, WBNS = 1460, $stations[2]=WYTS WYTS = 1230), Counting words in $sentence = Columbus is home to numerous FM = radio stations; a string array(WLVQ = 96.3, $words = str_word_count($sentence); WNCI = 97.9) // $words = 7 See also: count_chars()); DZone, Inc. |
  • 4. 4 PHP tech facts at your fingertipsString Parsing, continued Metacharacters A Match only beginning of stringDescription Function b Match a word boundaryConverting $callsign = strtoupper(wtvn);a string to B Match anything but word boundary // $callsign = WTVNuppercase See also: lcwords(), strtolower(), ucfirst(), d Match a digit character ucwords() D Match a non-digit characterStrip HTML and PHP $input = You won the a href=http://www. s Match a whitespace charactertags from a string example.comlottery!/a. $clean = strip_tags($input); S Match a non-whitespace character // $clean = You won the lottery! [] Enclose a character class See also: htmlentities(), htmlspecialchars() () Enclose a character grouping or define backreferenceReplace all $phrase = Big rockers listen to rock radio; $ Match end of lineoccurrences of a $phrase = str_replace(rock, talk, $phrase);substring // $phrase = Big talkers listen to talk radio ^ Match beginning of line See also: substr_replace(), strireplace(), . Match any character except for newline strtr() Quote the next metacharacterReturn part of a string $description = WFAN: Sports Radio 66;as specified by an $callsign = substr($description, 0, 4); w Match any string containing underscore and alphanumericoffset See also: strrchr() characters W Match a string containing anything but underscore andCompare two strings if (strcasecmp(WTVN, wtvn) == 0) alphanumericl characterscase-insensitively echo The strings are equal in a case- insensitive context. POSIX Regular Expression Functions See also: strncasecmp() PHP supports seven functions as defined by the POSIX 1003.2Convert newline $stations = WTVN: 610nWLW: 700nWYTS: 1230; specification, including these commonly used solutions:characters to the $html = nl2br($stations);HTML br / tag // $html = WTVN: 610br /WLW: 700br /WYTS: int ereg(str $pattern, str $string Search $string for a $pattern. You can optionally 1230 [, array $regs]) include the $regs parameter, which will cause See also: htmlentities(), htmlspecialchars() an array of the same name to be returned containing each match. See eregi() for case- insensitive counterpart. string ereg_replace(str Replace any patterns found in string with REGULAR EXPRESSIONS $pattern, str $replacement, str replacement. See eregi_replace() for case- $string) insensitive counterpart. array split(str $pattern, str Split $string into an array, dividing it accordingPHPs regular expression features borrow heavily from both the $string [, int $limit]) to $pattern. See spliti() for case-insensitivePerl and POSIX formats, and in fact are formally identified as counterpart.such. POSIX Regular Expression SyntaxPerl-compatible (PCRE) Regular Expression Functions [0-9] Any decimal digit from 0 - 9PHP supports eight PCRE-specific functions, including these [a-z] Any character from lowercase a through lowercase zcommonly used solutions: [A-Z] Any character from uppercase A through uppercase Z Function Description [A-Za-z] Any character from upper case A through lowercase z array preg_grep(str Searches $subject for $pattern, returning an array of p+ Any string containing at least one p $pattern, array $subject matches. The optional $flags parameter can be set to p* Any string containing zero or more ps [, int $flags]) PREG_GREP_INVERT, causing an array consisting of unmatched elements to be returned. p? Any string containing zero or one p p{N} Any string containing sequence of two ps int preg_match(str Determines whether $pattern exists in $subject. If p{N,M} Any string containing sequence of between N and M ps $pattern, str $subject [, $matches is defined, a similarly named variable will array $matches [, int be returned containing the matches. If $flags is set to p{2,} Any string containing sequence of at least two ps $flags [, int $offset]]]) PREG_OFFSET_CAPTURE, the string offset value will p$ Any string with p at the end of it also be returned for each match. See preg_match_all() for a variation of this function. ^p Any string with p at the beginning of it [^a-zA-Z] Any string not containing characters a-z through A-Z mixed preg_ Searches $subject for $pattern, replacing any replace(mixed $pattern, instances with $replacement. See preg_replace_ p.p Any string containing p followed by any character, followed by mixed $replacement, callback() for a variation of this function. another p mixed $subject [, int $limit [, int $count]]) Regular Expression Examples Validating a Phone NumberCommon PCRE Pattern Modifiers Presumes the required format is XXX-XXX-XXXX.Modifier Description // PCREg Perform a global search if (preg_match(/^[2-9]{1}d{2}-d{3}-d{4}$/, 614- 599-2599))i Perform a case-insensitive search echo Valid number!;m Treat the string as multiple lines ( // POSIXs Ignore newline characters if (ereg(^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$, 614-x Ignore white space and comments 999-2599))u Stop at the first match (ungreedy search) echo Valid number!; DZone, Inc. |
  • 5. 5 PHP tech facts at your fingertipsValidating a Username Telling Time with PHP, continuedPresumes username is between 6 and 10 alphabetical andnumerical characters. Month Parameters// PCRE F Full text representation of monthif (preg_match(/^[a-z0-9]{6,10}$/i, 800gilmore)) m Numeric representation of month echo Valid username!; M Three letter textual representation of month// POSIX n Numeric representation of month, without leading zerosif (eregi(^[a-z0-9]{6,10}$, 800gilmore)) t Number of days in given month echo Valid username!; Year ParametersTurn URLs into hyperlinks L Whether date is a leap year// PCRE o ISO-8601 year number$text = Go to; Y Full numeric representation of year$html = preg_replace(/s(w+://)(S+.?)(w+)/, y Two digit representation of year a href=123123/a, $text);// POSIX$text = Go to ; Date Function Examples$html= ereg_replace([a-zA-Z]+://(([.]?[a-zA- July 29, 2008 print date(F j, Y);Z0-9_/-])*), a href=00/a, $string); 7/29/08 print date(m/j/y);// $html = Go to a href= http://www.wjgilmore. Today is Tuesday, July 29 10:45:21am printf(Today is %s, date(l, F j h:i:sa));com There are 31 days in July. printf(There are %d days in %s., date(t), date(F)); TELLING TIME WITH PHP Setting the TimezoneThe Date Function You can set the timezone for all scripts by setting the date. timezone configuration directive within the php.ini file, or onThe date() f unction is perhaps one of PHPs most commonly a per-script basis using the date_default_timezone_set()used functions, capable of retrieving nearly every temporal function.attribute of a specific timestamp.string date(string $format [, $int $timestamp]) Other Useful Functionsa Lowercase Ante meridiem and Post meridiem Function DescriptionA Uppercase Ante meridiem and Post meridiem int mktime([int $hour [, int $min [, int Returns the Unix timestamp for a given $sec [, int $month [, int $day [, int $year dateB Swatch Internet Time [, int $is_dst]]]]]]])c ISO 8601 date int time() Returns current timestampe Timezone identifier string setlocale(int $category, string Sets the script localeg 12-hour hour format without leading zeros $locale)G 24-h
  • We Need Your Support
    Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

    Thanks to everyone for your continued support.

    No, Thanks