In The Beginning: Interpreter, Was A Collection of Perl Scripts in 1995

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

2.

INTRODUCTION PHP has grown to be the most widespread web platformin the world, operational in more than a third of the web servers acrossthe globe. PHP's growth is not only quantitative but also qualitative. More andmore companies, including Fortune companies, rely on PHP to run their business-critical applications, which creates new jobs and increases the demandfor PHP developers. Version 5, due to be released in the very near future, holdsan even greater promise. While the complexity of starting off with PHP remains unchanged and very low, the features offered by PHP today enable developers to reach farbeyond simple HTML applications. The revised object model allows for largescale projects to be written efficiently, using standard object-oriented methodologies. New XML support makes PHP the best language available for processing XML and, coupled with new SOAP support, an ideal platform for creating and using Web Services. Andi Gutmans, and two very prominentPHP developers, Stig Bakken and Derick Rethans, holds the key tounlocking the riches of PHP 5. It thoroughly covers all of the features of thenew version, and is a must-have for all PHP developers who are interested inexploring PHP 5's advanced features.

IN THE BEGINNING

It was eight years ago, when Rasmus Lerdorf first started developing PHP/FI. He could not have imagined that his creation would eventually lead to the development of PHP as we know it today, which is being used by millions of people. The first version of PHP/FI, calledPersonal Homepage Tools/Form Interpreter,was a collection of Perl scripts in 1995. One of the basicfeatures was a Perl-like language for handling form submissions, but it lackedmany common useful language features, such asforloops.

3. GENERATION OF PHP

PHP/FI 2: A rewrite came with PHP/FI 2 in 1997, but at that time the development wasalmost solely handled by Rasmus. After its release in November of that year,Andi Gutmans and Zeev Suraski bumped into PHP/FI while looking for a languageto develop an e-commerce solution as a university project. They discoveredthat PHP/FI was not quite as powerful as it seemed, and its language waslacking many common features. One of the most interesting aspects includedthe waywhileloops were implemented. The hand-crafted lexical scanner wouldgo through the script and when it hit the while keyword it would remember itsposition in the file. At the end of the loop, the file pointer sought back to thesaved position, and the whole loop was reread and re-executed. PHP 3 Zeev and Andi decided to completely rewrite the scripting language.They thenteamed up with Rasmus to release PHP 3, and along also came a new name: PHP:Hypertext Preprocessor, to emphasize that PHP was a different product and notonly suitable for personal use. Zeev and Andi hadalso designed and implementeda new extension API. This new API made it possible to easily support additionalextensions for performing tasks such as accessing databass, spell checkers andother technologies, which attracted many developers who were not part of thecore group to join and contribute to the PHP project. At the time of PHP 3srelease3in June 1998,the estimated PHP installed base consisted of about 50,000domains. PHP 3 sparked the beginning of PHPs real breakthrough, and was thefirst version to have an installed base of more than one million domains. PHP 4

In late 1998, Zeev and Andi looked back at their work in PHP 3 and felt theycould have written the scripting language even better, so they started yet another rewrite. While PHP 3 still continuously parsed the scripts while executing them, PHP 4 came with a new paradigm of compile first, execute later. The compilation step does not compile PHP scripts into machine code; it instead compiles them into byte code, which is then executed by the Zend Engine(Zend stands forZeev) the new heart of PHP 4. Because of this new way of executing scripts, the performance of PHP 4 was much better than that of PHP 3, with only a small amount of backward compatibility breakage Among other improvements was an improved extension API for better run-time performance, a web server abstraction layer allowing PHP 4 to run on most popular web servers, and lots more. PHP 4 was officially released on May 22, 2002,and today its installed base has surpassed 15 million domains.

PHP 5 Basic Language A language that doesnt have everything is actually easier to program in than some that do.Dennis M. Ritchie

PHP borrows a bit of its syntax from other languages such as C, shell, Perl,and even Java. It is really a hybrid language, taking the best features from other languages and creating an easy-to-use and powerful scripting language. When you finish reading this chapter, you will have learned The basic language structure of PHP How PHP is embedded in HTML How to write comments Managing variables and basic data types Defining constants for simple values The most common control structures, most of which are available in other programming languages

Built-in or user-defined functions If you are an experienced PHP 4 developer, you might want to skip to the next chapter, which covers object-oriented support of the language that haschanged significantly in PHP 5. HTML Embading The first thing you need to learn about PHP is how it is embedded in HTML: <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": <?php print "Hello, World"; ?> </BODY> </HTML> In this example, you see that your PHP code sits embedded in your HTML. Every time the PHP interpreter reaches a PHP open tag <?php it runs the enclosed code up to the delimiting ?> marker. PHP then replaces that PHP code with its output (if there is any) while any non-PHP text (such as HTML) is passed through as-is to the web client. Thus, running the mentioned script would lead to the following output: <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": Hello, World </BODY> </HTML>

5. Write a Web Application with PHP

INTRODUCTION The most common use for PHP is building web sites. PHP makes web applications dynamic, enabling users to interact with the site. The web application collects information from the user by means of HTML forms and processes it. Some of the information collected from users and stored at the web site is sensitive information, making security a major issue. PHP provides features that enable you to collect information from the user and to secure the information. Its up to you to develop a complete application using the pieces provided by PHP. This chapter describes how to use the functionality of PHP to build a dynamic web application.

EMBEDDING INTO HTML PHP doesnt have to be embedded in an HTML file, of course; you can create a PHP file that includes no HTML. However, when building a web application, you often use PHP and HTML together in a file. PHP was developed primarily for web use, to be embedded in HTML files as a templating language. When PHP code is included in a file, the file is given the PHP extension (the extension that signals your web server to expect PHP code in the file); usually .php, but a different extension(s), such as .phtml or .php5, can be specified when you configure your web server. The following code shows PHP embedded in HTML: <html> <head><title>Example 1</title></head> <body> <?php /* If it is April 1st, we show a quote */ if (date('md' == '0401')) { echo 'A bookstore is one of the only pieces of evidence we

have '.'that people are still thinking. <i>Jerry Seinfeld</i>'; } else { echo 'Good morning!'; } ?> </body> </html> The line <?php begins the PHP section embedded into the HTML code; the line ?> ends the PHP section. Notice that the code usesecho to send the output. When the text is so simple, the echo statements are acceptable. However, whenyou need to echo text strings that contain single or double quotes, the codebecomes more complicated. If the text to be echoed in the example was a link statement (such as<a href='http...'>), the example would not have worked correctly because the single quotes in the text would conflict with the single quotes enclosing the text string. For such a case, the PHP section can be ended before the text needs to be output and begin again before the PHP code that ends the if block and starts the else bock is needed, as in the following example: <html> <head><title>Example 2</title></head> <body> <?php /* If it is April 1st, we show a quote */ if (date('md' == '0401')) { echo 'A bookstore is one of the only pieces of evidence we '. 'have that people are still thinking. <i>Jerry Seinfeld <i>'; } else { echo 'Good morning!';

} ?> </body> </html> This coding behavior is messy. You are violating one of the principles of programming: Separate logic from content. The following version of embedding stores the text in a variable and then echoes the variable: < ?php /* If it is April 1st, we show a quote */ if (date('md' == '0401')) { $greeting = 'A bookstore is one of the only pieces of '. 'evidence we have that people are still thinking. '. '<i>Jerry Seinfeld</i>'; } else { $greeting = 'Good morning!'; } ?> <html> <head><title>Example 3</title></head> <body> <?php echo $greeting; ?> </body> </html> A shorter form of the PHP tag, <? , can usually be used instead of <?php . The php.ini configuration setting short_tags must be set to on, but this is the default. However, you need to be careful using the short tags because not every server might always have short_tags turned on. Also, short_tags can conflict with XML usage because <? is the start of a processing instruction. An additional tag

<?= is available, which is the equivalent of <?php echo , as the following snippet demonstrates: ...... <html> <head><title>Example 4</title></head> <body> <?= $greeting; ?> </body> </htm

If you want to be sure your application can run on as many systems as possible, you should not rely on short tags because they might be turned off. The rest of the examples in this chapter use the non-short tags everywhere. We also cover some additional techniques for separating code and layout.

USER INPUT Now that you know how to embed PHP code, you probably want to program some kind of user-specified action. For instance, the book webshop needs a login and registration system that requires user action, so we will implement this system as an example. This system requires an HTML form and a place to store the data collected by the form. Because this chapter does not deal with storing data in a database, only an API function is provided when data needs to be stored. After reading some of the later chapters, you will be able to fill these in yourself. We require four things from the user when he or she registers for the shop: email address, first name, last name, and requested password. The HTML code for a form to collect this information looks like this: <html> <head><title>Register</title></head> <body> <h1>Registration</h1> <form method="get" action="register.php">

<table> <tr><td>E-mail address:</td> <td> <input type='text' name='email'/> </td></tr> <tr><td>First name:</td> <td><input type='text' name='first_name'/></td></tr> <tr><td>Last name:</td> <td><input type='text' name='last_name'/></td></tr> <tr><td>Password:</td> <td> <input type='password' name='password'/> </td></tr> <tr> <td colspan='2'> <input type='submit' name='register' value='Register'/> </td> </tr> </table> </form> </body> </html>

OUTPUT:

6.Databases with PHP 5 INTRODUCTION A ubiquitous part of any PHP book is the topic of databases and database interfacing with PHP. This book is no different, simply because most people who write PHP applications want to use a database. Many good books exist on database design and using databases with PHP. This chapter introduces using MySQL and SQLite from PHP, but focuses primarily on the PHP 5, specific details of database interfacing. After you finish reading this chapter, you will have learned Some of the strong and weak points of MySQL and SQLite, and which types of applications at which they excel Interfacing with MySQL with the new Mysqli extension How to use PHP 5s bundled sqlite extension How to use PEAR DB to write more portable database code A Note About Version Numbers This chapter focuses on the new database connectivity features of PHP 5, specifically the mysqli and sqlite extensions. To enjoy all the new functionality described in this chapter, you need reasonably current versions of the various packages: MySQL 4.1.2 or newer SQLite as bundled with PHP 5.0.0 or newer PEAR DB 1.6 or newer MY SQL MySQL and PHP have become the bread and butter of web application builders. It is the combination you are most likely to encounter today and probably for the years to come. Consequently, this is also the first database covered in this chapter. This chapter focuses on the new mysqlior MySQL Improvedextension

that is bundled with PHP 5. As mentioned in the chapter introduction, the mysqli extension requires that you use at least version 4.1.2 of the MySQL. MySQL Strengths and Weaknesses This section contains some information about the strengths and weaknesses of MySQL. Strength: Great Market Penetration MySQL has the biggest market share of any open source database. Almost any web-hosting company can provide MySQL access, and books and articles about MySQL and PHP are abundant. Strength: Easy to Get Started After your database is set up and you have access to it, managing the database is straightforward. Initial access needs to be configured by a database administrator (if that person is not you). Tools such as MySQL Administrator or phpMyAdmin let you manage Your database. Strength: Open-Source License for Most Users MySQL comes with a dual licenseeither GPL or a commercial license. You can use MySQL under the GPL as long as you are not commercially redistributing it. Strength: Fast MySQL has always been relatively fast, much due to its simplicity. In the last few years, MySQL has gained foothold in the enterprise market due to new enterprise class features and general maturity without compromising performance for simple usage. Weakness: Commercial License for Commercial Redistribution I f you bundle MySQL (server or client) with a commercial closed-source product,

you need to purchase a license. MySQL AB have published a FOSS (Free or Open-Source Software) exception to MySQLs license that grants all free or open-source products an exception from this restriction. Strength: Reasonable Scalability MySQL used to be a lightweight database that did not have to drag around most of the expensive reliability features (such as transactions) of systems such as Oracle or IBM DB2. This was, and still is, one of the most important reasons for MySQLs high performance. Today, MySQL has evolved to almost match its commercial seniors in scalability and reliability, but you can still configure it for lightweight use. 7. PHP Interface The mysqli PHP extension was written from the ground up to support the new features of the MySQL 4.1 and 5.0 Client API. The improvements from the old mysql extension include the following: MySQL 151 Native bind/prepare/execute functionality Cursor support SQLSTATE error codes Multiple statements from one query Index analyzer The following sections give an overview of how to use the mysqli extension, and how it differs from the old mysql extension. Almost every mysqli function has a method or property counterpart, and the following list of functions describes both of them. The notation for the methods is similar to $mysqli->connect() for regular methods, calling connect() in an instance of the mysqli class. The parameter list is usually the same between mysqli functions and methods, except that functions in most cases have an object parameter first. Following that, function parameter lists are identical to that of their method counterparts. For the sake of brevity, replaces the method parameter list in the parameter descriptions. .

Connections: shows the mysqli functions that are related to connections. Function Name Description: mysqli_connect(...) $mysqli = new mysqli(...) Opens a connection to the MySQL server. Parameters (all are optional) host name(string) user name(string) password(string) database name(string) TCP port (integer) UNIX domain socket (string) mysqli_init() $mysqli = new mysqli mysqli_options(...) $mysqli->options(...) mysqli_real_connect(...) $mysqli->real_connect(...) Initializes MySQLi and returns an object for use with mysqli_real_connect Set various connection options Opens a connection to the MySQL server mysqli_close(...) $mysqli->close() Closes a MySQL server connection The parameter is connection object (function only) mysqli_connect_errno() Obtains the error code of the last failed connect mysqli_connect_error() Obtains the error message of the last failed connect mysqli_get_host_info(...) $mysqli->host_info

You might also like