This document provides a summary of various PHP concepts including:
- Configuration options at the global, host/directory, and script level using php.ini, .htaccess, and ini_set().
- Popular PHP frameworks like CakePHP, CodeIgniter, Symfony, and Zend Framework.
- Object-oriented PHP concepts like classes, objects, class constants, inheritance, abstraction, interfaces and visibility.
- Working with arrays including indexed, associative, and multidimensional arrays. Functions for sorting, retrieving values, and determining size.
- String parsing functions for conversion, manipulation, replacement and comparison of strings.
This document provides a summary of key PHP concepts including configuration, object-oriented programming, arrays, and string parsing. It discusses how to configure PHP at global, host-directory, and script levels. It also covers creating and extending classes, class constants and abstraction, interfaces, and visibility. The document also summarizes working with indexed, associative, and multidimensional arrays as well as over 70 sorting functions. It concludes with an overview of common string parsing functions.
Web sphere user group march 2012 - desktop single sign-on in an active dire...Dave Hay
- This presentation tells the story of a particular ISSC project – however, the story is relevant to many other clients, projects and requirements
- Understand how to integrate WebSphere Application Server, and related products, with Active Directory.
- Understand how to implement desktop single sign-on with WebSphere Portal, IBM Web Content Manager, IBM Connections etc.
- Share the lessons that we learned Consider the next steps.
Dave hay desktop single sign-on in an active directory worldDave Hay
The document discusses integrating WebSphere Application Server with Active Directory to enable desktop single sign-on. It covers key concepts needed to understand such as Kerberos, SPNEGO, Active Directory domains and forests. It also outlines the configuration steps required in WebSphere Application Server such as setting up a federated repository with Active Directory and ensuring the correct attribute mappings are defined to support single sign-on. Manual editing of configuration files is warned may be needed to maintain the attribute mappings.
Dave hay desktop single sign-on in an active directory worldDave Hay
The document provides an overview of a project to implement desktop single sign-on with WebSphere Application Server and related IBM products using Active Directory for user authentication. Key aspects included integrating WAS with Active Directory using LDAP and Kerberos, configuring the WAS Federated Repository and attribute mappings, and ensuring the proper Microsoft and WAS software versions and prerequisites were met. Proper configuration and testing of the WAS to Active Directory connection was emphasized.
IBM Connections and Desktop Single Sign-On using Microsoft Active Directory, ...Dave Hay
This document discusses integrating IBM Connections with Active Directory to enable single sign-on for desktop users. It describes Active Directory, Kerberos authentication, and the prerequisites for configuring WebSphere Application Server and Connections to work with Active Directory such that users can authenticate once using their Windows credentials and access Connections and other applications without reauthenticating.
The document provides an overview of JavaScript for PHP developers. It discusses similarities and differences between JavaScript and PHP syntax, including variables, arrays, conditionals, loops, functions, objects, prototypes, and more. It also summarizes the built-in JavaScript API, including global functions, constructors, and properties and methods of objects like Object, Array, Function, String, Number, Math, Date, and Error.
The document contains observations from a HighEdWeb conference in October 2010. It notes that individuals have a sense of humor but institutions and brands do not, and that the community is the greatest asset as it contains brilliant people wanting to share and collaborate. It concludes by saying the future of the web is bright and those in the community are becoming leaders.
This document provides a summary of key PHP concepts including configuration, object-oriented programming, arrays, and string parsing. It discusses how to configure PHP at global, host-directory, and script levels. It also covers creating and extending classes, class constants and abstraction, interfaces, and visibility. The document also summarizes working with indexed, associative, and multidimensional arrays as well as over 70 sorting functions. It concludes with an overview of common string parsing functions.
Web sphere user group march 2012 - desktop single sign-on in an active dire...Dave Hay
- This presentation tells the story of a particular ISSC project – however, the story is relevant to many other clients, projects and requirements
- Understand how to integrate WebSphere Application Server, and related products, with Active Directory.
- Understand how to implement desktop single sign-on with WebSphere Portal, IBM Web Content Manager, IBM Connections etc.
- Share the lessons that we learned Consider the next steps.
Dave hay desktop single sign-on in an active directory worldDave Hay
The document discusses integrating WebSphere Application Server with Active Directory to enable desktop single sign-on. It covers key concepts needed to understand such as Kerberos, SPNEGO, Active Directory domains and forests. It also outlines the configuration steps required in WebSphere Application Server such as setting up a federated repository with Active Directory and ensuring the correct attribute mappings are defined to support single sign-on. Manual editing of configuration files is warned may be needed to maintain the attribute mappings.
Dave hay desktop single sign-on in an active directory worldDave Hay
The document provides an overview of a project to implement desktop single sign-on with WebSphere Application Server and related IBM products using Active Directory for user authentication. Key aspects included integrating WAS with Active Directory using LDAP and Kerberos, configuring the WAS Federated Repository and attribute mappings, and ensuring the proper Microsoft and WAS software versions and prerequisites were met. Proper configuration and testing of the WAS to Active Directory connection was emphasized.
IBM Connections and Desktop Single Sign-On using Microsoft Active Directory, ...Dave Hay
This document discusses integrating IBM Connections with Active Directory to enable single sign-on for desktop users. It describes Active Directory, Kerberos authentication, and the prerequisites for configuring WebSphere Application Server and Connections to work with Active Directory such that users can authenticate once using their Windows credentials and access Connections and other applications without reauthenticating.
The document provides an overview of JavaScript for PHP developers. It discusses similarities and differences between JavaScript and PHP syntax, including variables, arrays, conditionals, loops, functions, objects, prototypes, and more. It also summarizes the built-in JavaScript API, including global functions, constructors, and properties and methods of objects like Object, Array, Function, String, Number, Math, Date, and Error.
The document contains observations from a HighEdWeb conference in October 2010. It notes that individuals have a sense of humor but institutions and brands do not, and that the community is the greatest asset as it contains brilliant people wanting to share and collaborate. It concludes by saying the future of the web is bright and those in the community are becoming leaders.
The document provides instructions for installing and configuring phpMyAdmin 2.10.3. It discusses requirements, introduction, quick install, setup script usage, upgrading from older versions, and using different authentication modes. The quick install process involves untarring the downloaded files, ensuring correct file ownership, and configuring either by manually editing config.inc.php or using the setup script.
PHP is a scripting language originally designed for web development. It allows code to be embedded into HTML pages to produce dynamic web content. PHP code is executed by the PHP runtime on the web server. A small sample PHP code displays "Hello World" by echoing a string. PHP supports various data types including integers, arrays, strings, and resources. It can be optimized for speed by reducing the size of compiled code. PHP includes many open source libraries and allows extensions to be built to add new functionality.
PHP is a scripting language originally designed for web development. It allows code to be embedded into HTML pages to produce dynamic web content. PHP code is executed by the PHP runtime on the web server. A small sample PHP code displays "Hello World" by using PHP echo tags within HTML tags. PHP supports various data types including integers, arrays, strings, and resources. It can be optimized for speed by reducing the size of compiled code. PHP includes many open source libraries and allows extensions to be built to add new functionality.
PHP may seem to be a very easy language but many of don't know how PHP works. We will discuss the less known facts about PHP and we will also cover some common type of software design patterns used with PHP
This document is a seminar presentation on web development using core PHP. It introduces PHP as a server-side scripting language created in 1994. It discusses how PHP can be used to connect to MySQL databases and build dynamic websites. It also introduces XAMPP as a tool for setting up a local development environment with Apache, MySQL, and PHP on Windows, Linux, and Mac systems. The presentation provides an overview of PHP's history and popularity, how to install PHP and connect to databases, and concludes with the potential of PHP for web development.
PHP stands for Hypertext Preprocessor and is a widely used scripting language originally designed for web development. PHP code is embedded into HTML and interpreted by a web server to generate dynamic web pages. PHP can also be run from the command line. It includes many libraries and extensions that allow it to interface with different systems. PHP's configuration file php.ini determines aspects of its behavior and is searched in several default locations upon startup.
The document discusses PHP, an open-source scripting language commonly used for web development. It can be embedded into HTML pages and is used to dynamically generate webpage content. PHP code is executed on the server and generates HTML that is sent to the browser. The document also discusses using XAMPP, a free and open-source cross-platform web server solution stack, to install and run PHP, MySQL, and Apache on your local computer for testing websites.
PHP is a general-purpose scripting language well-suited for server-side web development that runs on web servers. It allows creation of dynamic web page content by executing PHP code within requested files. PHP is portable across most web servers, operating systems, and platforms and can interface with several database systems. The PHP source code is freely available for users to develop, modify, and expand applications. PHP primarily operates as an interpreter that takes input containing text and PHP instructions and outputs another stream of data commonly in HTML format.
The LAMP stack is an open-source software platform for building dynamic web sites and web applications. It stands for Linux, Apache HTTP Server, MySQL database, and PHP programming language. Linux provides the operating system foundation. Apache is the web server software. MySQL is the database management system. PHP is the programming language most commonly used to develop dynamic web applications that interact with the database. The LAMP stack is highly flexible, scalable, and free to use, making it a popular choice for hosting web applications and sites.
PHP PEAR is a standard for PHP code style and a library of reusable PHP code packages. It contains modules for common functions like validation, authentication, mailing, and database interaction. PEAR packages can be easily included and provide benefits like time savings, standardized code quality, and access to contributions from an open source community. Some example PEAR modules are for validation, authentication, mailing, and generating SQL statements from database table data.
The document discusses 3-tier architecture and PHP scripting. It describes a 3-tier architecture with presentation, application, and persistence layers. The presentation layer includes the browser, application layer includes a web server and PHP scripts, and the persistence layer includes a relational database. It provides details on PHP, including its history, syntax based on C, function library, and use for embedding scripts in HTML pages. It also includes a basic photo album code example and resources for learning more about PHP.
PHP Programming course provides the knowledge necessary to design and develop dynamic, database-driven web pages using PHP version 5. PHP is a language written for the web, quick to learn, easy to deploy and provides substantial functionality required for e-commerce. This course introduces the PHP framework and syntax, and covers in depth the most important techniques used to build dynamic web sites. Students also learn how to configure PHP and the Apache Web Server. Comprehensive hands on exercises are integrated throughout to reinforce learning and develop real competency.
PHP is a server-side scripting language that is commonly used for web development and can be embedded into HTML code. It allows developers to manage dynamic content, connect to databases, track sessions, and build e-commerce sites. PHP code runs on the server and generates HTML that is sent to the user's browser. It is free, runs on most server platforms, and has a large community of developers. LIT Susant K Rout offers PHP training courses in Bhubaneswar, Odisha, India to teach participants how to use PHP for web development.
PHP is a widely used scripting language originally designed for web development. It allows server-side code to produce dynamic web page content. PHP code is embedded into HTML and executed by a PHP interpreter on the web server to create web pages. It can be deployed on most web servers and operating systems free of charge. Some key points about PHP include:
- It was created by Rasmus Lerdorf in 1995 and is now produced by The PHP Group.
- PHP code is interpreted from HTML files and outputs HTML. It focuses on server-side scripting to generate dynamic web content.
- Popular frameworks built with PHP include CakePHP, Symfony, CodeIgniter, and Zend Framework.
PHP (Hypertext Preprocessor) is a popular general-purpose scripting language that is primarily used for web development. It is a server-side scripting language, which means it is executed on the server and generates dynamic web pages. PHP is embedded within HTML code and can be used to create dynamic content, interact with databases, handle form data, and perform various other web-related tasks.
Facebook uses a LAMP stack with additional services and customizations for its architecture. The LAMP stack includes PHP, MySQL, and Memcache. PHP is used for its web programming capabilities but has scaling issues. MySQL is used primarily as a key-value store and is optimized for recency of data. Memcache provides high-performance caching. Additional services are implemented using Thrift for cross-language communication and include News Feed, Search, and Scribe for logging. Services allow storing code closer to data in more efficient compiled languages.
Facebook uses a LAMP stack with additional services and customizations for its architecture. PHP and MySQL are used for the main web and data tiers but have limitations for large scale. Services are implemented using Thrift for cross-language communication and Scribe for distributed logging. Services allow storing code closer to data and using optimized languages. The News Feed and Search architectures distribute work across tiers with Thrift calls and aggregate data using services.
Facebook uses a LAMP stack with additional services and customizations for its architecture. PHP and MySQL are used for the main web and data tiers but have limitations for large scale. Services are implemented using Thrift for cross-language communication and Scribe for distributed logging. Services allow storing code closer to data and using optimized languages. The News Feed and Search architectures incorporate services, distributed data storage, and caching to provide personalized experiences for over 120 million active users.
The document provides instructions for installing and configuring phpMyAdmin 2.10.3. It discusses requirements, introduction, quick install, setup script usage, upgrading from older versions, and using different authentication modes. The quick install process involves untarring the downloaded files, ensuring correct file ownership, and configuring either by manually editing config.inc.php or using the setup script.
PHP is a scripting language originally designed for web development. It allows code to be embedded into HTML pages to produce dynamic web content. PHP code is executed by the PHP runtime on the web server. A small sample PHP code displays "Hello World" by echoing a string. PHP supports various data types including integers, arrays, strings, and resources. It can be optimized for speed by reducing the size of compiled code. PHP includes many open source libraries and allows extensions to be built to add new functionality.
PHP is a scripting language originally designed for web development. It allows code to be embedded into HTML pages to produce dynamic web content. PHP code is executed by the PHP runtime on the web server. A small sample PHP code displays "Hello World" by using PHP echo tags within HTML tags. PHP supports various data types including integers, arrays, strings, and resources. It can be optimized for speed by reducing the size of compiled code. PHP includes many open source libraries and allows extensions to be built to add new functionality.
PHP may seem to be a very easy language but many of don't know how PHP works. We will discuss the less known facts about PHP and we will also cover some common type of software design patterns used with PHP
This document is a seminar presentation on web development using core PHP. It introduces PHP as a server-side scripting language created in 1994. It discusses how PHP can be used to connect to MySQL databases and build dynamic websites. It also introduces XAMPP as a tool for setting up a local development environment with Apache, MySQL, and PHP on Windows, Linux, and Mac systems. The presentation provides an overview of PHP's history and popularity, how to install PHP and connect to databases, and concludes with the potential of PHP for web development.
PHP stands for Hypertext Preprocessor and is a widely used scripting language originally designed for web development. PHP code is embedded into HTML and interpreted by a web server to generate dynamic web pages. PHP can also be run from the command line. It includes many libraries and extensions that allow it to interface with different systems. PHP's configuration file php.ini determines aspects of its behavior and is searched in several default locations upon startup.
The document discusses PHP, an open-source scripting language commonly used for web development. It can be embedded into HTML pages and is used to dynamically generate webpage content. PHP code is executed on the server and generates HTML that is sent to the browser. The document also discusses using XAMPP, a free and open-source cross-platform web server solution stack, to install and run PHP, MySQL, and Apache on your local computer for testing websites.
PHP is a general-purpose scripting language well-suited for server-side web development that runs on web servers. It allows creation of dynamic web page content by executing PHP code within requested files. PHP is portable across most web servers, operating systems, and platforms and can interface with several database systems. The PHP source code is freely available for users to develop, modify, and expand applications. PHP primarily operates as an interpreter that takes input containing text and PHP instructions and outputs another stream of data commonly in HTML format.
The LAMP stack is an open-source software platform for building dynamic web sites and web applications. It stands for Linux, Apache HTTP Server, MySQL database, and PHP programming language. Linux provides the operating system foundation. Apache is the web server software. MySQL is the database management system. PHP is the programming language most commonly used to develop dynamic web applications that interact with the database. The LAMP stack is highly flexible, scalable, and free to use, making it a popular choice for hosting web applications and sites.
PHP PEAR is a standard for PHP code style and a library of reusable PHP code packages. It contains modules for common functions like validation, authentication, mailing, and database interaction. PEAR packages can be easily included and provide benefits like time savings, standardized code quality, and access to contributions from an open source community. Some example PEAR modules are for validation, authentication, mailing, and generating SQL statements from database table data.
The document discusses 3-tier architecture and PHP scripting. It describes a 3-tier architecture with presentation, application, and persistence layers. The presentation layer includes the browser, application layer includes a web server and PHP scripts, and the persistence layer includes a relational database. It provides details on PHP, including its history, syntax based on C, function library, and use for embedding scripts in HTML pages. It also includes a basic photo album code example and resources for learning more about PHP.
PHP Programming course provides the knowledge necessary to design and develop dynamic, database-driven web pages using PHP version 5. PHP is a language written for the web, quick to learn, easy to deploy and provides substantial functionality required for e-commerce. This course introduces the PHP framework and syntax, and covers in depth the most important techniques used to build dynamic web sites. Students also learn how to configure PHP and the Apache Web Server. Comprehensive hands on exercises are integrated throughout to reinforce learning and develop real competency.
PHP is a server-side scripting language that is commonly used for web development and can be embedded into HTML code. It allows developers to manage dynamic content, connect to databases, track sessions, and build e-commerce sites. PHP code runs on the server and generates HTML that is sent to the user's browser. It is free, runs on most server platforms, and has a large community of developers. LIT Susant K Rout offers PHP training courses in Bhubaneswar, Odisha, India to teach participants how to use PHP for web development.
PHP is a widely used scripting language originally designed for web development. It allows server-side code to produce dynamic web page content. PHP code is embedded into HTML and executed by a PHP interpreter on the web server to create web pages. It can be deployed on most web servers and operating systems free of charge. Some key points about PHP include:
- It was created by Rasmus Lerdorf in 1995 and is now produced by The PHP Group.
- PHP code is interpreted from HTML files and outputs HTML. It focuses on server-side scripting to generate dynamic web content.
- Popular frameworks built with PHP include CakePHP, Symfony, CodeIgniter, and Zend Framework.
PHP (Hypertext Preprocessor) is a popular general-purpose scripting language that is primarily used for web development. It is a server-side scripting language, which means it is executed on the server and generates dynamic web pages. PHP is embedded within HTML code and can be used to create dynamic content, interact with databases, handle form data, and perform various other web-related tasks.
Facebook uses a LAMP stack with additional services and customizations for its architecture. The LAMP stack includes PHP, MySQL, and Memcache. PHP is used for its web programming capabilities but has scaling issues. MySQL is used primarily as a key-value store and is optimized for recency of data. Memcache provides high-performance caching. Additional services are implemented using Thrift for cross-language communication and include News Feed, Search, and Scribe for logging. Services allow storing code closer to data in more efficient compiled languages.
Facebook uses a LAMP stack with additional services and customizations for its architecture. PHP and MySQL are used for the main web and data tiers but have limitations for large scale. Services are implemented using Thrift for cross-language communication and Scribe for distributed logging. Services allow storing code closer to data and using optimized languages. The News Feed and Search architectures distribute work across tiers with Thrift calls and aggregate data using services.
Facebook uses a LAMP stack with additional services and customizations for its architecture. PHP and MySQL are used for the main web and data tiers but have limitations for large scale. Services are implemented using Thrift for cross-language communication and Scribe for distributed logging. Services allow storing code closer to data and using optimized languages. The News Feed and Search architectures incorporate services, distributed data storage, and caching to provide personalized experiences for over 120 million active users.
1. #23
tech facts at your fingertips
Get More Refcardz! Visit refcardz.com
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 world's 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 world's packages are available for download from http://pear.php.net/,
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 PHP's 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
PHP's 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 PHP's native
The php.ini file is PHP's 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 language's 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 user's browser and
www.dzone.com
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 Apache's 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 http://dev.wjgilmore.com), 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 haven't 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
http://www.php.net/ini for a complete list of directives. Get More Refcardz
(They’re free!)
Script-specific Configuration
Occasionally you'll want to tweak directives on a per-script basis. n Authoritative content
For instance to change PHP's 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
PHP's 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 Apache's httpd.conf file. For instance to
configure Apache to recognize .dzone as a supported PHP file Subscribe Now for FREE!
PHP
extension: Refcardz.com
AddType application/x-httpd-php .php .dzone
DZone, Inc. | www.dzone.com
2. 2
PHP
tech facts at your fingertips
Popular Frameworks, continued Object-Oriented PHP, continued
Framework Source Class Constants
CakePHP http://www.cakephp.org/ Class constants are defined with the const keyword, and can
CodeIgniter http://www.codeigniter.com/ be referenced through the scope resolution operator (::). For
eZ Components http://ez.no/ezcomponents instance, to define a constant identifying the RadioStation class'
Prado http://www.pradosoft.com/ minimum supported PHP version:
symfony http://www.symfony-project.org/
Zend Framework http://framework.zend.com/ 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 Classes
Creating a Class
Class hierarchies can be created using the extends keyword. For
A class defines the behavior and characteristics of an entity you'd
instance, an application tasked with cataloging all major media
like to represent in an application. A sample class follows:
outlets might first define a MediaOutlet class which defines
class 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 the
class name like you would a function, preceding it with the new final public function setOwner($owner) {
keyword: ...
}
$wtvn = new RadioStation();
Class Abstraction
Class Constructors
The aforementioned MediaOutlet class would be more
Constructors are useful for performing initialization tasks at
accurately defined as an abstract class, because it would never
class instantiation time, thereby saving you the hassle of calling
be explicitly instantiated (instead, one would instantiate derived
additional 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 these
Custom 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 Interfaces
function __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 their
PHP 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. | www.dzone.com
3. 3
PHP
tech facts at your fingertips
Multidimensional Arrays, continued
WORKING WITH ARRAYS
Referencing an element isn't unlike the methods used for
The array is one of programming's most powerful data structures, indexed and associative arrays; it's just a tad more verbose:
capable of managing a seemingly endless variety of data. $channel = $stations[FM][WTVN];
Creating an Array Determining Array Size
The following two examples all create an array named $stations The number of elements found in an array can be determined
consisting 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 these
You can create an array consisting of a character- or numerically- functions accept an optional parameter which can change the
based 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 Function
Indexed 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 association
based 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 association
Perhaps 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 association
foreach($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 assign
meaningful 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 function
referencing 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 PARSING
associative 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 commonly
Multidimensional Arrays used tasks.
Multidimensional arrays are useful for representing more Description Function
complex 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. | www.dzone.com
4. 4
PHP
tech facts at your fingertips
String Parsing, continued Metacharacters
A Match only beginning of string
Description Function
b Match a word boundary
Converting $callsign = strtoupper(wtvn);
a string to B Match anything but word boundary
// $callsign = WTVN
uppercase
See also: lcwords(), strtolower(), ucfirst(),
d Match a digit character
ucwords() D Match a non-digit character
Strip HTML and PHP $input = You won the a href=http://www. s Match a whitespace character
tags 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 backreference
Replace all $phrase = Big rockers listen to rock radio;
$ Match end of line
occurrences 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 metacharacter
Return 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 alphanumeric
offset See also: strrchr() characters
W Match a string containing anything but underscore and
Compare two strings if (strcasecmp(WTVN, wtvn) == 0) alphanumericl characters
case-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.2
Convert 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 according
PHP's regular expression features borrow heavily from both the $string [, int $limit]) to $pattern. See spliti() for case-insensitive
Perl and POSIX formats, and in fact are formally identified as counterpart.
such.
POSIX Regular Expression Syntax
Perl-compatible (PCRE) Regular Expression Functions
[0-9] Any decimal digit from 0 - 9
PHP supports eight PCRE-specific functions, including these
[a-z] Any character from lowercase a through lowercase z
commonly 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 p's
[, 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 p's
int preg_match(str Determines whether $pattern exists in $subject. If
p{N,M} Any string containing sequence of between N and M p's
$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 p's
$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 Number
Common PCRE Pattern Modifiers Presumes the required format is XXX-XXX-XXXX.
Modifier Description // PCRE
g 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 (
// POSIX
s 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. | www.dzone.com
5. 5
PHP
tech facts at your fingertips
Validating a Username Telling Time with PHP, continued
Presumes username is between 6 and 10 alphabetical and
numerical characters. Month Parameters
// PCRE F Full text representation of month
if (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 zeros
if (eregi('^[a-z0-9]{6,10}$', '800gilmore')) t Number of days in given month
echo Valid username!;
Year Parameters
Turn URLs into hyperlinks L Whether date is a leap year
// PCRE
o ISO-8601 year number
$text = Go to http://www.wjgilmore.com.;
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 http://www.wjgilmore.com. ;
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'));
comhttp://www.wjgilmore.com.
There are 31 days in July. printf(There are %d days in %s.,
date('t'), date('F'));
TELLING TIME WITH PHP
Setting the Timezone
The Date Function You can set the timezone for all scripts by setting the date.
timezone configuration directive within the php.ini file, or on
The date() f unction is perhaps one of PHP's 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 Functions
a Lowercase Ante meridiem and Post meridiem Function Description
A 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 date
B Swatch Internet Time
[, int $is_dst]]]]]]])
c ISO 8601 date
int time() Returns current timestamp
e Timezone identifier
string setlocale(int $category, string Sets the script locale
g 12-hour hour format without leading zeros $locale)
G 24-hour hour format with leading zeros
int strtotime(string $time [, int $now]) Converts English textual date/time
h 12-hour hour format with leading zeros description into a Unix timestamp
H 24-hour hour format with leading zeros bool checkdate(int $month, int $day, Validates the date composed by the
i Minutes with leading zeros int $year) $month, $day, and $year arguments.
I Specifies whether date is in daylight savings time array getdate([int $timestamp]) Retrieves a timestamp as an associative
array. Associative keys include seconds,
O Difference to Greenwich time (GMT) in hours minutes, hours, mday (day of the
P Difference to Greenwhich time (GMT) with colon between hours and month), wday (day of week), mon
minutes (month), year, yday (day of the year),
weekday, month, and 0 (seconds since
r RFC 2822 date
UNIX Epoch)
s Seconds, with leading zeros
T Timezone abbreviation PHP 5.1.0 introduced an object-oriented DateTime class. See
u Milliseconds http://www.php.net/DateTime for more information.
U Seconds since Unix Epoch
Date-related Examples
z Timezone offset in seconds
Output December 25 $date = date('l', mktime(0,0,0,12,25,2008));
Day Parameters falls on a Thursday printf(December 25 falls on a %s, $date);
d Day of month, two digits with leading zeros Output Next month is printf(Next month is %s, date('F', strtotime('+1
August. month')));
D Three letter textual representation of day
Output Last Friday $date = date('F d, Y', strtotime('Last Friday'));
j Day of month without leading zeros
fell on July 25, 2008 printf(Last Friday fell on %s, $date);
l Textual representation of day
Output Oggi è setlocale(LC_ALL, it_IT);
N ISO-8601 numeric representation
martedì printf(Oggi egrave; %s, strftime(%A));
S Two character English ordinal suffix for day of month
Retrieve a page's last- echo date('l, F j h:i:sa', filemtime($_SERVER[SCRIPT_
w Numeric representation of day of week modified date NAME]));
z Numerical offset of day of year
Calculate the $date1 = strtotime(2008-08-14);
difference between $date2 = strtotime(2008-07-11);
Week Parameters two dates
$diff = $date2 - $date1;
W ISO-8601 week number of year printf(Difference in days: %s, $diff / 60 / 60 / 24);
DZone, Inc. | www.dzone.com
6. 6
PHP
tech facts at your fingertips
Retrieving data as an indexed array:
MYSQL INTEGRATION while ($row = $result-fetch_row() {
printf(%S, $row[0]);
Although PHP supports several popular databases, MySQL }
remains by far the most common database solution. PHP's Retrieving data as an object:
MySQL support has evolved considerably in recent years, with while ($row = $result-fetch_object() {
the MySQLi (MySQL Improved) extension being the current printf(%S, $row-callsign);
recommended solution. Here are the most commonly used }
methods.
Determining the Number of Rows Affected and Retrieved
To determine the number of affected rows after sending an
The PHP 5.3 release includes a new MySQL
Hot INSERT, UPDATE, or DELETE query, use the affected_rows
driver known as mysqlnd (MySQL Native Driver).
Tip This driver eliminates the need for a previously
property.
required special licensing exception (FLOSS), and Example:
eliminates the need to have MySQL installed on the same ma- $result = $mysqli-query(UPDATE stations SET station =
'610' WHERE callsign = 'WTVN');
chine as PHP. It has already been integrated with the mysql printf(Rows affected: %d, $result-rows_affected);
and mysqli extensions, with PDO support in the works.
To determine how many rows were returned when using a
SELECT query, use the num_rows property:
Connecting to MySQL $result = $mysqli-query(SELECT * FROM stations WHERE
state ='Ohio');
The mysqli extension provides a number of ways to connect to
MySQL, but the easiest involves just passing the connection data printf(Rows affected: %d, $result-num_rows);
along when instantiating the mysqli class:
Working with Prepared Statements
mysqli new mysqli([string host [, string user [, string
pswd Prepared statements both optimize query performance and
[string dbname [int port [string socket]]]]]]); decrease the possibility of SQL injection attacks by separating
the query data from the logic, first passing the query to MySQL
Here's an example:
for preparation, binding variables to the query columns, and
$mysqli = new mysqli(localhost, webuser, secret,
corporate); finally passing the data to MySQL for query execution.
To prepare a query, create the query, and then initialize a
Handling Connection Errors
statement object using the stmt_init() method:
In case of connection error you can retrieve both the error $query = INSERT INTO stations VALUES(?, ?);
number and error string using the errno() and error()
$stmt = $mysqli-stmt_init();
methods. Example:
if ($mysqli-errno) { Next the query is prepared by passing it to MySQL using the
printf(Unable to connect: %s, $mysqli-error); prepare() method:
exit(); $stmt-prepare($query);
}
Next, bind the parameters using the bind_param() method:
Sending a Query to the Database $stmt-bind_param('ss', WTVN, 610);
Once the connection has been established, you can begin Finally, execute the prepared statement using the execute()
querying the database. Queries are sent using the query() method:
method: $stmt-execute();
mixed query(string $query [, int $resultmode])
You can also use prepared statements to retrieve results. The
Setting the optional $resultmode parameter to MYSQLI_USE_ general process used to execute the previous INSERT query is
RESULT will cause query() to return the result as an unbuffered identical to that required for executing a SELECT query, except
set. that the bind_param() method is not required, and you bind
Example: results following a call to the execute() method. An example
$result = $mysqli-query(SELECT callsign FROM follows:
stations);
$query = SELECT callsign, frequency FROM stations
Sending INSERT, UPDATE, and DELETE queries works ORDER BY callsign;
identically. For instance, sending an UPDATE query works like $stmt = $mysqli-stmt_init();
this: $stmt-prepare($query);
$result = $mysqli-query(UPDATE stations SET station $stmt-execute();
= '610' WHERE callsign = 'WTVN'); $stmt-bind_result($callsign, $frequency);
while ($stmt-fetch())
Retrieving Data printf(%s: %sbr /, $callsign, $frequency);
Data can be parsed from the result set using a number of data
structures, including via associative and indexed arrays, and Transactions
objects. By default the MySQLi extension will render each query
permanent upon successful execution, actually changing the
Retrieving data as an associative array:
while ($row = $result-fetch_array(MYSQLI_ASSOC) { database's contents when INSERT, UPDATE, and DELETE queries
printf(%S, $row[callsign]); are processed. However the success of some tasks depend upon
} the successful execution of several queries, and until all have
DZone, Inc. | www.dzone.com