Introduction to LAMP :
LAMP is an open source Web development platform based on Linux, Apache, MySQL, and PHP[or Perl/Python]. PHP(short for PHP Hypertext Preprocessor) is a programming language for which Perl or Python is sometimes substituted. The term was coined in Europe, where these programs are commonly used together and have become something of a standard development environment. The name derives from the first letters of each of the programs. Each program is an open source standard in its own right: Linux is the operating system; Apache is the most commonly-used Web server;MySQL is a relational database management system (RDBMS) with add-on tools for Web-based administration; and PHP is a popular object-oriented scripting language that encompasses the best features of many other programming languages to make it efficient for Web development. Developers that use these tools with a version of a Windows operating system instead of Linux are said to be using WAMP. History of LAMP The scripting component of the LAMP stack has its origins in the CGI web interfaces that became popular in the early 1990s. This technology allows the user of a web browser to execute a program on the web server, and to thereby receive dynamic as well as static content. Programmers used scripting languages with these programs because of their ability to manipulate text streams easily and efficiently, even when they originate from disparate sources. For this reason system designers often referred to such scripting systems as glue languages. Michael Kunze coined the acronym LAMP in an article for the German computing magazine c’t in 1998. The article aimed to show that a bundle of free software could provide a viable alternative to commercial packages. Knowing about the IT-world’s love of acronyms, Kunze came up with LAMP as a marketing-like term to increase the popularity of free software. O’Reilly and MySQL AB have made the term popular among English-speakers. Indeed,MySQL AB has since based some of its marketing efforts on the popularity of the LAMPstack. Components of LAMP As stated above LAMP is made of four major components: • Linux: the operating system [although any operating system can be used ranging from Unix(and its other variants), MAC OS to even Windows] Linux is OS of choice because its Free and wide availability and Security and its stability.
Note: to read more about Linux please read our Linux tutorial athttp://education.ebizelindia.com • Apache: the Web server: Often referred to as simply Apache, a public-domain open source Web server developed by a loosely-knit group of programmers. The first version of Apache, based on theNCSA httpd Web server, was developed in 1995. Core development of the Apache Web server is performed by a group of about 20 volunteer programmers, called the Apache Group. However, because the source code is freely available, anyone can adapt the server for specific needs, and there is a large public library of Apache add-ons. In many respects, development of Apache is similar to development of the Linux operating system. The original version of Apache was written for UNIX, but there are now versions that run under OS/2, Windows and other platforms(almost all popular platforms). The name is a tribute to the Native American Apache Indian tribe, a tribe well known for its endurance and skill in warfare. A common misunderstanding is that it was called Apache because it was developed from existing NCSA code plus various patches, hence the name a patchy server, or Apache server. • MySQL:
A relational database management system famous for being OPEN SOURCE, usually free and highly efficient. Essentially a database is defined as an organized collection of data. The DBMS sits “on top of” this data providing and interface between the database and the user. MySQL is a simple, yet powerful Open Source Software relational database management system that uses SQL. For more details, see http://www.mysql.com or read ourMySQL courses at http://education.ebizelindia.com • PHP(Perl/Python):
the programming language. PHP is a programming language for which Perl or Pythonis sometimes substituted. The term was coined in Europe, where these programs are commonly used together and have become something of a standard development environment. The name derives from the first letters of each of the programs.
Getting Your Environment Ready :
PHP and MySQL are usually associated with LAMP (Linux, Apache, MySQL, PHP). However, most PHP developer ( including me ) are actually using Windows when developing the PHP application. So this page will only cover the WAMP ( Windows, Apache, MySQL, PHP ). You will learn how to install Apache, PHP, and MySQL under Windows platform. The first step is to download the packages : • Apache : http://httpd.apache.org/
• PHP : http://www.php.net/
• MySQL :www.mysql.com You should get the latest version of each packages. As for the example in this tutorial i’m using Apache 2.0.63 (apache_2.0.63-win32-x86-no_ssl.msi ), PHP 5.2.5 (php-5.2.5-Win32.zip) and MySQL 5.0. Now let’s start the installation process one by one: • Installing Apache
• Installing PHP
• Modifying Apache Configuration
• Installing MySQL
• Modifying PHP Configuration File 1. Installing and Configuring on Windows Installing Apache Installing apache is easy if you download the Microsoft Installer ( .msi ) package. 1. Just double click on the icon to run the installation wizard. 2. Click next to continue installation. 3. Accept the license agreement and click on Next 4. Click next until you see the Server Information window. You can enter localhost for both the Network Domain and Server Name. As for the administrator’s email address you can enter anything you want. If you are Windows XP(or any other NT based Windows OS) Install Apache as Serviceso every time you start Windows, Apache is automatically started. 5. Click the Next button and choose Typical installation. Click Next one more time and choose where you want to install Apache ( I installed it in the default location C:\Program Files\Apache Group ). Click the Next button and then the Install button to complete the installation process. To see if you Apache installation was successful open up you browser and typehttp://localhost in the address bar. You should see something like this : By default Apache’s document root is set to htdocs directory. The document root is where you must put all your PHP or HTML files so it will be process by Apache ( and can be seen through a web browser ). Of course you can change it to point to any directory you want. The configuration file for Apache is stored in C:\Program Files\Apache Group\Apache2\conf\httpd.conf ( assuming you installed Apache in C:\Program Files\Apache Group ) . It’s just a plain text file so you can use Notepad to edit it. For example, if you want to put all your PHP or HTML files in C:\www just find this line in the httpd.conf : DocumentRoot “C:/Program Files/Apache Group/Apache2/htdocs” and change it to : DocumentRoot “C:/www” After making changes to the configuration file you have to restart Apache ( Start > Programs > Apache HTTP Server 2.0.50 > Control Apache Server > Restart ) to see the effect. Another configuration you may want to change is the directory index. This is the file that Apache will show when you request a directory. As an example if you typehttp://education.ebizelindia.com without specifying any file the index.php file will be automatically shown. Suppose you want apache to use index.php, index.php or main.php as the directory index you can modify the DirectoryIndex value like this : DirectoryIndexindex.php index.php main.php Now whenever you request a directory such ashttp://localhost/ Apache will try to find the index.php file or if it’s not found Apache will use index.php. In case index.php is also not found then main.php will be used. Installing PHP First, extract the PHP package (php-5.2.5-Win32.zip ). I extracted the package in theC:\ drive. Change the new created directory name to php ( just to make it shorter ). Then copy the file php.ini-dist in PHP5 directory to you windows directory ( C:\Windows or C:\Winnt depends on where you installed Windows ) and rename the file to php.ini. directory to you windows directory ( C:\Windows or C:\Winnt depends on where you installed Windows ) and rename the file to php.ini. This is the PHP configuration file and we’ll take a look what’s in it later on. Next, move the php5ts.dll file from the newly created php directory into the Apache2\bin subdirectory. Quoting from php installation file you can also place php5ts.dll in other places such as : • In the directory where apache.exe is start from ( C:\Program Files\Apache Group\Apache2 \bin)
• In your %SYSTEMROOT%\System32, %SYSTEMROOT%\system and %SYSTEMROOT% directory. Note: %SYSTEMROOT%\System32 only applies to Windows NT/2000/XP)
• In your whole %PATH% Modifying Apache Configuration Apache doesn’t know that you just install PHP. We need to tell Apache about PHP and where to find it. Open the Apache configuration file in C:\Program Files\Apache Group\Apache2\conf\httpd.conf and add the following three lines : LoadModule php5_module “c:/php/php5apache2.dll”
#note the location may differ depending upon where you have installed PHP on your system.
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps The first line tells Apache where to load the dll required to execute PHP and the second line means that every file that ends with .php should be processed as a PHP file. You can actually change it to anything you want like .php or even .asp! The third line is added so that you can view your php file source code in the browser window. You will see what this mean when you browse this tutorial and click the link to the example’s source code like this one. Now restart Apache for the changes to take effect ( Start > Programs > Apache HTTP Server 2.0 > Control Apache Server > Restart ) . To check if everything is okay create a new file, name it as test.php and put it in document root directory ( C:\Program Files\Apache Group\Apache2\htdocs ).
The content of this file is shown below:
<?php
phpinfo();
?>
phpinfo() is the infamous PHP function which will spit out all kinds of stuff about PHP and your server configuration. Type http://localhost/test.php on your browser’s address bar and if everything works well you should see something like this : Installing MySQL For Detailed installation guide of MySQL please refer to our MySQL tutorial, which contains installation as well as configuration instruction for MySQL. Modifying PHP Configuration File ( php.ini ) PHP stores all kinds of configuration in a file called php.ini. You can find this file in the directory where you installed PHP. Sometimes you will need to modify this file for example to use a PHP extension. I won’t explain each and every configuration available just the ones that often need modification or special attention. Some of the configurations are : 1. register_globals
2. error_reporting and display_errors
3. extension and extension_path
4. session.save_path
5. max_execution_time register_globals Before PHP 4.2.0 the default value for this configuration is On and after 4.2.0 the default value is Off. The reason for this change is because it is so easy to write insecure code with this value on. So make sure that this value is Off in php.ini. error_reporting and display_errors Set the value to error_reporting = E_ALL during development but after production set the value to error_reporting = E_NONE . The reason to use E_ALL during development is so you can catch most of the nasty bugs in your code. PHP will complain just about any errors you make and spit out all kinds of warning ( for example if you’re trying to use an uninitialized variable ). However, after production you should change the value to E_NONE so PHP will keep quiet even if there’s an error in your code. This way the user won’t have to see all kinds of PHP error message when running the script. One important thing to note is that you will also need to set the value of display_erros to On. Even if you set error_reporting = E_ALL you will not get any error message ( no matter how buggy our script is ) unless display_errors is set to On. extension and extension_path PHP4 comes with about 51 extensions such as GD library ( for graphics creation and manipulation ), CURL, PostgreSQL support etc. These extensions are not turned on automatically. If you need to use the extension, first you need to specify the location of the extensions and then uncomment the extension you want. The value of extension_path must be set to the directory where the extension is installed which is PHP_INSTALL_DIR/ext, with PHP_INSTALL_DIR is the directory where you install PHP. For example I installed PHP in C:\php so the extensions path is : extension_path = “C:/php/ext/” Don’t forget to add that last slash or it won’t work After specifying the extension_path you will need to uncomment the extension you want to use. In php.ini a comment is started using a semicolon (;). As an example if you want to use GD library then you must remove the semicolon at the beginning of ;extension=php_gd2.dll to extension=php_gd2.dll session.save_path This configuration tells PHP where to save the session data. You will need to set this value to an existing directory or you will not be able to use session. In Windows you can set this value as: session.save_path = c:/windows/temp/ max_execution_time The default value for max_execution_time is 30 ( seconds ). But for some scripts 30 seconds is just not enough to complete it’s task. For example a database backup script may need more time to save a huge database. If you think your script will need extra time to finish the job you can set this to a higher value. For example to set the maximun script execution time to 15 minutes ( 900 seconds ) you can modify the configuration as max_execution_time = 900 PHP have a convenient function to modify PHP configuration in runtime, ini_set(). Setting PHP configuration using this function will not make the effect permanent. It last only until the script ends.
Alternatives available on Windows If you are familiar with windows or want to develop your website on Windows then move it to Linux based Host server. Then there are multiple windows equivalent of theLAMP stack. LAMP stands for Linux (Operating System), Apache (Web Server), Mysql (Database), and PHP (Scripting Language). Under these alternatives, instead of using Linux as the Operating System, you use one of the Microsoft Windows OSes such as XP, 2000 or 2k3. Why use Windows instead of Linux Windows OSes since 2000 i.e. 2k, XP , 2k3 have been extremely stable as opposed to their predecessors. So if you are proficient in Windows, then there is no reason not to use it for web hosting. (barring security, but that’s another issue). Secondly if you want to develop your site off line and then move it to a LAMP Stack, and you are not familiar with Linux, then these Windows based alternatives serves as an ideal prototyping environment. You can do almost every thing with them that you can do in LAMP, furthermore they are extremely easy to install, configure, administer and use. Since with these windows alternatives comes as a single bundle (Apache+PHP+MySQL), you don’t need to download and install them separately. Just install and you are ready to go. Given below are some alternatives available for LAMP stack on Windows: 1. XAMPP [www.apachefriends.org/en/xampp-windows.php] 2. WAMP server [www.en.wampserver.com/download.php] 3. Easy PHP
[http://downloads.sourceforge.net/quickeasyphp/EasyPHP-2.0b1-
setup.exe?modtime=1166851545&big_mirror=0] 4. PHPTriad
[http://downloads.sourceforge.net/phptriad/phptriad2-2-
1.exe?modtime=1013817600&big_mirror=0]
ntroduction to PHP:
PHP, which is recursive acronyms for “PHP Hypertext Preprocessor”, is a server-side,HTML embedded scripting language used to create dynamic Web pages. Much of its syntax is borrowed from C, Java and Perl with some unique features thrown in. The goal of the language is to allow Web developers to write dynamically generated pages quickly. In an HTML page, PHP code is enclosed within special PHP tags. When a visitor opens the page, the server processes the PHP code and then sends the output (not the PHPcode itself) to the visitor’s browser. It means that, unlike JavaScript, you don’t have to worry that someone can steal your PHP script. PHP offers excellent connectivity to many databases including MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, and Generic ODBC. The popular PHP-MySQL combination (both are open-source products) is available on almost every UNIX host. Being web-oriented, PHP also contains all the functions to do things on the Internet – connecting to remote servers, checking email via POP3 or IMAP, url encoding, setting cookies, redirecting, etc. History of PHP PHP stands for PHP: Hypertext Preprocessor, with that PHP standing for Personal HomePage/Form Interpreter . This type of acronym is known as a retronym. Originally, in 1994, the language was designed as a small set of binaries used to collect some basic site traffic data. In 1997 the parser was rewritten by two Israelis and the name was changed to the current acronym — it being determined that hypertext preprocessor was a decidedly more acceptable name in the business world. PHP is an open-source language, used primarily for dynamic web content and server-side applications. It is often pointed to as the main competitor with: • Microsoft’s C# – Visual Basic.NET – ASP family,
• Sun’s Java – JSP
• Macromedia’s ColdFusion
• CGI – Perl PHP has many open-source libraries included with the core build, and many more are readily available. Extensions exist to help PHP interface with a number of systems, including IRC, a number of compression formats, and Windows API. Other extensions exist to let PHP generate file formats on-the-fly, such as a popular extension which allows PHP to create Macromedia Flash movies. Since version 3, PHP has integrated object oriented features. Version 5 built substantially on this limited functionality, and PHP now has robust object oriented capabilities, including interfaces, exceptions, destructions, and abstracts. PHP reached wide-spread popularity with version 4, released in 2000. In 2004 PHP 5 was debuted, and it is now considered one the top languages used for server-side scripting. PHP/FI PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts ‘Personal Home Page Tools’. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to » release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code. PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project. PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0. PHP 3 PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI’s existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted. One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0’s extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0’s tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax. The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain ‘PHP’, with the meaning being a recursive acronym – PHP: Hypertext Preprocessor. By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet. PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing. PHP 4 By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP’s core. The design goals were to improve performance of complex applications, and improve the modularity of PHP’s code base. Such applications were made possible by PHP 3.0’s new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently. The new engine, dubbed ‘Zend Engine’ (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTPsessions, output buffering, more secure ways of handling user input and several new language constructs. Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet. PHP’s development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project. PHP 5 PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.
Why PHP?:
It’s no secret that there are alternatives to PHP: ASP, JSP, Cold Fusion, and Perl, to name just a few. While each of these languages has differences in syntax and structure, when it comes down to it, they can all produce the same results. So, why would you choose PHP over other options? – Simplicity. For people new to programming, this is frequently the strongest appeal. Even those with little or no programming experience can quickly get up to speed and begin creating full-fledged applications. Because it was specifically designed for creating web applications, PHP has a host of built-in functions to handle common needs. – PHP is Open Source. Because PHP’s source code is freely available, a community of developers is always working to improve, add to, and find bugs in the language. Open Source means you never need to rely on the manufacturer to release the next version if something doesn’t work or pay for expensive upgrades. – Stability, and compatibility. Currently, PHP runs stable on a range of operating systems including most flavors of UNIX, Windows and Macs and integrates well with most popular servers including IIS and Apache. PHP is also endowed with other goodies, like native support for many popular databases, an extensible architecture, and a processor that not only uses fewer resources on the server than many of its competitors, but also displays pages in record time.In Short : PHP scripting and MySQ database enables programmers to create a programme that’ll run on any computer, regardless of operating system. PHP has thousands of programming functions to facilitate almost any task.
Where do PHP Stands? No doubt much of its popularity is due to its relative ease to learn, and its notorious looseness. Arrays and variables in PHP are able to hold any type of object, variables need not be declared, and the syntax is remarkably simple. Unlike many languages, such as C# or Perl, which have primarily a following of more generalist programmers, many PHP programmers know no other language. This occasionally causes it to be dismissed as a lesser language, but its growing popularity and the many robust and efficient sites built using it as a structure seem to dispel this myth. PHP has occasionally been criticized for what are viewed by some as security flaws, in comparison to languages such as ASP. A lack of easily understandable error messages, a sometimes overly robust configuration file, and an obviously incomplete set of built-in functions are also pointed to as areas which could use marked improvement. Development continues apace, however, and with each successive build, PHP appears to address more and more of the concerns raised by its open-source community. PHP and other Languages
1. PHP vs. ASP?
2. PHP vs. Cold Fusion?
3. PHP vs. Perl? 1. PHP vs. ASP? ASP is not really a language in itself, it’s an acronym for Active Server Pages, the actual language used to program ASP with is Visual Basic Script or JScript. The biggest drawback of ASP is that it’s a proprietary system that is natively used only on Microsoft Internet Information Server (IIS). This limits it’s availability to Win32 based servers. There are a couple of projects in the works that allows ASP to run in other environments and webservers: InstantASP from Halcyon (commercial), Chili!Soft ASP from Chili!Soft (commercial) and OpenASP from ActiveScripting.org (free). ASP is said to be a slower and more cumbersome language than PHP, less stable as well. Some of the pros of ASP is that since it primarily uses VBScript it’s relatively easy to pick up the language if you’re already know how to program in Visual Basic. ASP support is also enabled by default in the IIS server making it easy to get up and running. The components built in ASP are really limited, so if you need to use “advanced” features like interacting with FTP servers, you need to buy additional components. 2. PHP vs. Cold Fusion? PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. Cold Fusion has better error handling, database abstraction and date parsing although database abstraction is addressed in PHP 4. Another thing that is listed as one of Cold Fusion’s strengths is its excellent search engine, but it has been mentioned that a search engine is not something that should be included in a web scripting language. PHP runs on almost every platform there is; Cold Fusion is only available on Win32, Solaris, Linux and HP/UX. Cold Fusion has a good IDE and is generally easier to get started with, whereas PHPinitially requires more programming knowledge. Cold Fusion is designed with non-programmers in mind, while PHP is focused on programmers. A great summary by Michael J Sheldon on this topic has been posted to the PHP mailing list. A copy can be found here. 3. PHP vs. Perl? The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and can because of this get very complicated. The flexibility / complexity of Perl makes it easier to write code that another author / coder has a hard time reading. PHP has a less confusing and stricter format without losing flexibility. PHP is easier to integrate into existing HTML than Perl. PHP has pretty much all the ‘good’ functionality of Perl: constructs, syntax and so on, without making it as complicated as Perl can be. Perl is a very tried and true language, it’s been around since the late eighties, but PHPis maturing very quickly. 4. PHP vs. JSP
| Function / Feature | JSP | PHP |
| Programming Approach | Completely object oriented Advantage: Clean code Disadvantage: Too descriptive |
Scripting with object oriented support Advantage: Functional and quick coding, you can use OOP practices at your convenience Disadvantage: May get clumsy |
| String and data manipulation | Rich library, too much descriptive and object oriented code | Rich functionality. Functional and easy coding. |
Web Oriented features
|
Almost everything is built in or supported by libraries. Complicated and too much of code. | Inbuilt functionality. Easy to use functions, written for the specific tasks |
| Database Access features | Standard JDBC structure/ Use EJB/ Struts framework built over JDBC. Descriptive and too much overhead or boiler plate code involved. Uses the same API for all databases using JDBC drivers | Dedicated inbuilt libraries for most of the commonly used databases. Very tight integration with MySQL and PostGRESQL. Very minimal boiler plate code required. The libraries and results are straight forward and easy to use. |
| XML/XSL/XPATH | Use standard SAX/DOM parsers. Too much boiler plate code involved. Well defined APIs and stable implementations are available for XSL and XPATH | SAX and DOM parsers available are easy to use and to the point. Another library, Simple XML provides very easy OO approach to handling XML data. XSL and XPATH functionality is also built in. |
| Extensibility | Java Classes and Libraries. Run’s in sandbox and hard JNI approach needed to integrate with server programs. | PHP/C/Any thing executable by the underlying OS platform. Can very easily interact with programs on the server. Very good support for native code. |
| Dynamic Graphics/PDF and bells and whistles | Almost everything has a readymade library | Supported internally or though libraries. |
| Web Services/SOAP | Addon Libraries like Axis, JAX-WS, etc. | In Built |
| Portals | Spec JSR-168 and 286 | Many different Portal frameworks |
If Pre-requisite you choose PHP as your development language, what you need to get started depends on: • Sound knowledge of HTML. * • Working knowledge of JavaScript(optional, but strongly recommended) ** • Sound Knowledge of SQL and knowledge of any RDBMS software (MySQL recommended)*** • Access to a web server that have Apache, MySQL and PHP configured on it
OR
• Apache + MySQL + PHP installed on your machine. • Any Text editor(for beginner level) or WYSIWYG editor (for advanced scripting). • phpMyAdmin or any other MySQL administration tool installed. PHP is as dependent on HTML as any language that generates web pages. If you don’t know HTML PHP won’t do you much good as you will have difficulty displaying the results of your PHP processing since for all practical purposes the purpose of PHP is to generate HTML. If you don’t have access to a web server, that’s not going to create a problem, you can configure Apache+ MySQL + PHP on your windows machine as demonstrated in chapter 1.2(or use any of it’s bundled alternative listed in chapter 1.3). Develop your web site on Windows and when you are done with development make it live on any Linux based host (believe me almost 80-90% companies are developingLAMP solutions work this way). * Please refer to our XHTML tutorial for HTML.
** Please refer to our JavaScript tutorial for more information on JavaScript
*** Please go through our MySQL tutorial for in-depth information on MySQL.
Choosing an Editor On Linux Bluefish –
Supports any protocol that is supported by GNOME VFS. (FTP, SSH…) gedit –
gedit is a free software, UTF-8 compatible text editor for the GNOME desktop environment. It is designed to have a clean, simple interface inspired by the ideals of the GNOME project. gPHPEdit–
gPHPedit is a GPL-based, small UTF-8 compatible text editor for the GNOME desktop environment, written by Andy Jeffries. It is similar to gedit with the difference that it is designed for PHP and HTML text editing. The current version is 0.9.91, released on July 5, 2006. On Windows ConTEXT
Freeware editor with syntax highlighting It is a freeware text editor for Microsoft Windows, aimed at software developers. It can open and edit very large files, while requiring only modest amounts of RAM and hard drive space to run. Crimson Editor – lightweight editor. Supports FTP Programmer’s Notepad Programmer’s Notepad (PN1) is an open-source text editor targeted at users who work with source code. It was released in 1998. PN1’s successor, Programmer’s Notepad 2 (PN2), was released in 2002 and is now based on Scintilla. Possibly the most distinctive feature common to both versions is the combination tabbed document interface and multiple document interface called “Tabbed MDI” by the developer. The TDI is parent to the MDI. Notepad++
Notepad++ is a free source code editor for Windows. The project is hosted on SourceForge.net, from where it has been downloaded over eight million times. This project, based on the Scintilla editor component, is written in C++ with pure Win32 API calls and uses STL. The aim of Notepad++ is to offer a slim and efficient binary with a totally customizable GUI.
Testing your Environment While there’s nothing wrong with getting started writing PHP scripts sing no-frills editors such as Windows Notepad or vi, chances are you’re soon going to want to graduate to a full-fledged PHP-specific development solution. Several open source and commercial solutions are available. The best way to verify your PHP installation is by attempting to execute a PHP script. Open a text editor and add the following lines to a new file:
<?php
phpinfo();
?>
If you’re running Apache, save the file within the htdocs directory as phpinfo.php. Note: from now onwards this tutorial will use XAMPP from Apache Friends for development. You can still use Apache, but if you are having any problem configuring it, just uninstall Apache and install XAMPP. XAMPP is easy to install, no manual configuration required, and all components installed in one go (Apache + MySQL + PHP + phpMyAdmin). If you’re running IIS, save the file within C:\inetpub\wwwroot\. Now open a browser and access this file by entering the following URL:http://localhost/phpinfo.php. If all goes well, you should see output similar to that shown in Figure below: The page above contains a lot of information related to your environment, such as: PHP core Configuration info, apache2handler info, Apache Environment info
etc. If you’re attempting to run this script on a Web hosting provider’s server, and you receive an error message stating phpinfo() has been disabled for security reasons, you’ll need to try Testing Your Installation executing another script. Try executing this one instead, which should produce some simple output:
<?php
echo “A simple but effective PHP test!”;
?>
First PHP script Every language has it… the basic “Hello, World!” script. It is a simple script that only displays the words “Hello, World!”. Over the years this has become the traditional phrase to use when writing your first program. According to Wikipedia, it’s mainstream usage spawned from an internal memorandum in 1974 that became incorporated into the book The C Programming Language. It’s actual first known usage was in Kernighan’s 1972 A Tutorial Introduction to the Language B. From this it has grown into somewhat of a tradition in the programming world. So how do I do it in PHP? Well the two simplest ways are using Print or Echo. Syntax: echo (“val”);
<?php
echo “<h1>Welcome to Ebiz Education!</h1>”
?>
Here, as we read that HTML Embeds in the php code,that’s why <h1>and </h1> is used here in the php script.echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it ( whereas print is a function,it returns a value, it does not take multiple parameters). If you’re running Apache, create a folder named test within the htdocs directory and save the file as hello.php in the test directory. Now, open the page in the browser to see the output: http://localhost/test/hello.php if your apache installation is working fine, you should have the following output: Assignment 1) Write a PHP script to display following eBIZ Education Team Welcomes You PHP Rocks
2) Write a PHP script to print your Name, Age and Address
PHP Syntax You cannot view the PHP source code by selecting “View source” in the browser – you will only see the output from the PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser. Now that you are aware of how PHP scripts are executed, let’s discuss how to actually write your first PHP script. All PHP scripts are written in what are called code blocks. These blocks can be embedded into HTML, if desired, and are generally defined by <?php at the start and ?> at the end. NOTE Although <?php and ?> are generally used,
the following are also valid code-block separators:
<? … ?> Shorthand version of <?php and ?>
<% … %> NOTE Although <?php and ?> are generally used, the following are also valid code-block separators:
<? … ?> Shorthand version of <?php and ?>
<% … %> ASP style
<SCRIPT LANGUAGE=”PHP”>
…
</SCRIPT>
HTML editor compatible syntax Note that some of these code block separators function only when the associated php.ini configuration directive is enabled. Unless there is a specific reason not to, using the default <?php and ?> tags is strongly recommended.ASP style
<SCRIPT LANGUAGE=”PHP”>
…
</SCRIPT>
HTML editor compatible syntax Note that some of these code block separators function only when the associated php.ini configuration directive is enabled. Unless there is a specific reason not to, using the default <?php and ?> tags is strongly recommended.
PHP comments When programming in any language the process of adding comments involves writing notes alongside the code to describe what the code does and how it works. The comments are ignored by the PHP pre-processor when executing a script and are purely for human consumption.
In Short Comments are used as a note of the code for the help of programmer and the web developers who may view want to view source code
Excuses aside, there is much to be gained from included helpful and concise comments with the PHP code that powers your web site. Firstly, you will be amazed at how puzzling a section of code can be even a few months after you have written it. It is not unusual for a developer to revisit some old code they once wrote and express amazement that they actually wrote it. It is important to remember that there is a good chance you will have to continue to maintain your PHP scripts long after they are written. In PHP, we use // or # to make a single-line comment and /* and */ to make a large comment block. PHP Single Line Comments(//,#) Comments that reside on a single line are prefixed with the two forward slash characters in PHP (i.e //). The following example contains a single line comment:
<?php
// This is a single line comment
eg:<?php
echo “This is to be shown”;
//This will Not be shown on the browser.
#This will also not be shown on the browser.
?>
?>
The single line comment can be on a line of its own, or it can be appended to the end of a line of code:
<?php
echo “This is a test line”; // Output a line of text
?>
In the above example the PHP pre-processor will execute the echo statement and then ignore everything after the // single line comment marker. Single line comments are also useful for temporarily highding the lines of code from the execution. For example, the following change to our previous example will cause thePHP pre-processor to ignore the entire echo command during execution:
<?php
// echo “This is a test line”;
?>
PHP Multi-line Comments Multi-line comments are wrapped in /* and */ delimiters. The /* marks the start of the comment block and the */ marks the end. The following example demonstrates the use of multi-line commenting in PHP:
<?php
/*
This a multi-line block
of comments and this would not be displaed on browser.
*/
?>
Multi-line comments are useful when you have notes you want to make in the code that will take up more than one line. The ability to mark blocks of lines as comments avoids the necessity of placing the single line comment marker at the start of each comment line. Another useful application of multi-line comments is to comment out blocks of PHP code temporarily. It is quite common to have written some PHP script and then wonder if you can re-write it so that it is perhaps more efficient or reliable. In this situation you can comment out the old script fragment so that it is no longer executed and write some new code. If it turns out your new code is worse than the original (which happens from time to time) you can simply remove the new code and uncomment the old to bring it back into the execution flow.
| PHP Operators | ||||||||||||||||||||||||||||||||
| There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports.The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.The most common PHP operators are assignment operators, arithmetic operators, combined operators, comparison operators, and logical operators. Each type is discussed separately below. | ||||||||||||||||||||||||||||||||
| Arithmetic Operators | ||||||||||||||||||||||||||||||||
| The basic assignment operator in PHP is “=”. This means that the operand to the left of “=” gets set to the value to the right of “=”. | ||||||||||||||||||||||||||||||||
| Arithmetic Operators | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| Assignment Operators | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| Comparison Operators | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| Logical Operators | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| PHP Unary Operators | ||||||||||||||||||||||||||||||||
| The following table outlines the various forms of pre and post increment and decrement operators, together with examples that show how the equivalent task would need to be performed without the increment and decrement operators. | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| PHP String Concatenation Operator | ||||||||||||||||||||||||||||||||
| Working Example | ||||||||||||||||||||||||||||||||
| Given below is a PHP script that demonstrates use of some basic PHP operators: | ||||||||||||||||||||||||||||||||
| <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”><HTML>
<HEAD> <TITLE> PHP Operators </TITLE> </HEAD> <BODY> <h2>PHP Operators </h2> <HR> <FIELDSET> <LEGEND> <span style=”background-color: #3399CC; color: Arithmetic Operators Example</span></LEGEND> <pre> <?php #$x,$y,$result; $x=10; $y=20; //addition operator $result=$x+$y; //substraction operator echo “$x + $y =$result”; $result=$x-$y; echo “<br>$x – $y =$result”; //Multiplication operator $result=$x*$y; echo “<br>$x * $y =$result”; //division operator $result=$x/$y; echo “<br>$x / $y =$result”; $result=$x%$y; echo “<br>$x % $y =$result”; ?> </pre> </FIELDSET><BR> <FIELDSET> <LEGEND><span style=”background-color: #3399CC; color: #F7F7F7;font-weight: bold”>A ssignment Operator EXAMPLE </span></LEGEND> <pre> <?php #$x,$y,$result; $x=10; $y=20; //addition operator echo “$x +=$y: “; $x+=$y; echo “$x”; //substraction operator echo “<br>$x -=$y: “; $x-=$y; echo “$x”; //Multiplication operator echo “<br>$x *=$y :”; echo “<br>$x /=$y: “. ($x/=$y); //division operator #$result=$x/$y; ?> </pre> </FIELDSET></BODY> </HTML> |
||||||||||||||||||||||||||||||||
| Type the above code in the editor and save it as operator.php and now open the PHPscript in the browser to view the output: | ||||||||||||||||||||||||||||||||
PHP Execution Operator All of the operators we have looked at so far are similar to those available in other programming and scripting languages. With the execution operator, however, we begin to experience the power of PHP as server side scripting environment. The execution operator allows us to execute a command on the operating system that hosts your web server and PHP module and then capture the output. You can do anything in an execution operator that you could do as if you were sitting at a terminal window on the computer (within the confines of the user account under whichPHP is running). Given this fact, it should not escape your attention that there are potential security risks to this, so this PHP feature should be used with care. The execution operator consists of enclosing the command to be executed in back quotes (`). The following example runs the UNIX/Linux uname and id commands to display information about the operating system and user account on which the web server and PHP module are running.(The least complicated of all three special operators is the execution operator, which is ` – a back tick. Back ticks are used very rarely in normal typing, so you might have trouble finding where yours is – it is almost certainly to the left of your 1 key on your keyboard.) Note: that these command will not work if you are running a Windows based server.
<?php
echo `Hello World!` . ‘<br>’;
echo `id`;
?>
This results in the following output in the browser window: Linux EbizLinuxHome 2.6.9-42.0.10.ELsmp #1 SMP Tue Feb 27 10:11:19 EST 2007 i686 i686 i386 GNU/Linux uid=48(apache) gid=48(apache) groups=48(apache) Sample PHP script:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE>PHP: Executing Server side Command </TITLE>
<META NAME=”Generator” CONTENT=”EditPlus”>
<META NAME=”Author” CONTENT=””>
<META NAME=”Keywords” CONTENT=””>
<META NAME=”Description” CONTENT=””>
</HEAD>
<BODY><H1>Executing Server Side Command </H1>
<?php
$dirToCreate=”testDIR”;
?>
<hr>
<FIELDSET>
<LEGEND><span style=”background-color: #3399CC
; color: #F7F7F7;font-weight: bold”>
Executing Server Side Commands </span></LEGEND>
<pre>
<?php
echo “<br>Before Executing the <i>mkdir</i> commnad”;
echo `ls -la`;
echo “<hr width=75%>”;
echo “<br>After Executing the <i>mkdir</i> commnad”;
echo `mkdir $dirToCreate`;
echo `ls -la`;
echo “</b>”;
?>
</pre>
</FIELDSET>
</BODY>
</HTML>
PHP script above executes some basic Linux commands and list the output in a HTMLformat. Type the above script and save it as serverCommand.php and uploaded it to a Linux based server to view the output: Assignment
1. Write a PHP script to implement all Arithmetic and Assignment operators, display the output along with variable value on the browser.
2. Write a PHP script to implement Unary increment and decrement operators.
3. Write a PHP script to print following series, using Unary increment operator
10
9
8
.
0
4. Write PHP Script to implement following Unix commands:
a. ls –a
b. ls / -la
c. mkdir hello
d. dir /
Variable, Arrays & String PHP Variables Variables are used for storing values, such as numbers or strings , so that they can be used many times in a script. A large part of writing scripts, and programming, involves the handling and manipulation of data. Data have forms, ranging from single characters, words and sentences to integers, floating point numbers and true and false values. In object oriented environments such as PHP, data can also take the form of an object, a self contained module which is capable of encapsulating any number of data values of numerous different types. When working with data values in PHP, we need some convenient way to store these values so that we can easily access them and make reference to them whenever required. This is where PHP variables come in to the use. • Variables are used for storing a values, like text strings, numbers or arrays.
• When a variable is define can be used over and over again in your script
• All variables in PHP start with a $(Doller) sign symbol. Variable type As you’ve seen, variables begin with a dollar sign ($) and are followed by a meaningful name. The variable name cannot begin with a numeric character, but it can contain numbers and the underscore character (_). Additionally, variable names are case-sensitive, meaning that $EBIZ_emp and $ebiz_emp are two different variables. PHP is a Loosely Typed Language In PHP a variable does not need to be declared before being set. $var=10; In the example above, you see that you do not have to tell PHP which data type the variable is. • PHP automatically converts the variable to the correct data type, depending on how they are set.
• In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
• In PHP the variable is declared automatically when you use it. Variable Naming Variable Naming rules in PHP • A variable name must start with a letter or an underscore “_”
• A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
• A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString) Variable Scope The scope is the area in which the variable is declared. In PHP, you set your scope with curly braces (the { and } characters). There are two particular types of scope, the global scope which refers to everything outside functions, and the local scope which refers to everything inside functions.Variables you declare in the global scope cannot be used in the local scope, and variables declared in the local scope cannot be used in the global scope. Creating and Using Variables Assigning a Value to a PHP Variable Values are assigned to variables using the PHP assignment operator. The assigment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assigment operator. Finally the line, as with all PHP code statements, is termininated with a semi-colon (;). Let’s begin by assigning the word “Car” to a variable named Vehicle: $Vehicle = “Car”; We have now declared a variable with the name Vehicle and assigned a string value to it of “Car“. We can similarly declare a variable to contain an integer value: $rainbow_colour = 7; The above assignment creates a variable named rainbow_colour and assigns it a numeric value of 7. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:
<?php
$rainbow_colour = 7; // Set initial values
$Vehicle = “Car”;
$rainbow_colour = 8; // Change the initial values to new values
$Vehicle = “Bus”;
?>
Accessing PHP Variable Values Now that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created. For example, if we want to display the value which we assigned to our rainbow_colour variable we can simply reference it in our echo command: <?php
echo “The colours of rainbow is $rainbow_colour.”;
?> This will cause the following output to appear in the browser: The colours of rainbow is 8. The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example:
<?php
echo “The color of the rainbow is the $rainbow_colourth”;
?>
What we are looking for in this scenario is output as follows: The color of rainbow is the 8th. Unfortunately PHP will see the th on the end of the $rainbow_colour variable name as being part of the name. It will then try to output the value of a variable called $rainbow_colourth, which does not exist. This result in nothing being displayed for this variable: The colour of the rainbow Fortunately we can get around this issue by placing braces ({ and }) around the variable name to distinguish the name from any other trailing characters:
<?php
echo “The color of the rainbow is the ${rainbow_colour}th”;
?>
To give us the desired output: The color of the rainbow is 8th. Changing the Type of a PHP Variable Loosely typed languages such as PHP (and JavaScript), allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:
<?php
$myNumber = 6; // variable is of integer type
$myNumber = six; // variable has now changed to string type
?>
The process of dynamically changing the type of a variable is known as automatic type conversion.
PHP Variables Variables are used for storing values, such as numbers or strings , so that they can be used many times in a script. A large part of writing scripts, and programming, involves the handling and manipulation of data. Data have forms, ranging from single characters, words and sentences to integers, floating point numbers and true and false values. In object oriented environments such as PHP, data can also take the form of an object, a self contained module which is capable of encapsulating any number of data values of numerous different types. When working with data values in PHP, we need some convenient way to store these values so that we can easily access them and make reference to them whenever required. This is where PHP variables come in to the use. • Variables are used for storing a values, like text strings, numbers or arrays.
• When a variable is define can be used over and over again in your script
• All variables in PHP start with a $(Doller) sign symbol. Variable type As you’ve seen, variables begin with a dollar sign ($) and are followed by a meaningful name. The variable name cannot begin with a numeric character, but it can contain numbers and the underscore character (_). Additionally, variable names are case-sensitive, meaning that $EBIZ_emp and $ebiz_emp are two different variables. PHP is a Loosely Typed Language In PHP a variable does not need to be declared before being set. $var=10; In the example above, you see that you do not have to tell PHP which data type the variable is. • PHP automatically converts the variable to the correct data type, depending on how they are set.
• In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
• In PHP the variable is declared automatically when you use it. Variable Naming Variable Naming rules in PHP • A variable name must start with a letter or an underscore “_”
• A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
• A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString) Variable Scope The scope is the area in which the variable is declared. In PHP, you set your scope with curly braces (the { and } characters). There are two particular types of scope, the global scope which refers to everything outside functions, and the local scope which refers to everything inside functions.Variables you declare in the global scope cannot be used in the local scope, and variables declared in the local scope cannot be used in the global scope. Creating and Using Variables Assigning a Value to a PHP Variable Values are assigned to variables using the PHP assignment operator. The assigment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assigment operator. Finally the line, as with all PHP code statements, is termininated with a semi-colon (;). Let’s begin by assigning the word “Car” to a variable named Vehicle: $Vehicle = “Car”; We have now declared a variable with the name Vehicle and assigned a string value to it of “Car“. We can similarly declare a variable to contain an integer value: $rainbow_colour = 7; The above assignment creates a variable named rainbow_colour and assigns it a numeric value of 7. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:
<?php
$rainbow_colour = 7; // Set initial values
$Vehicle = “Car”;
$rainbow_colour = 8; // Change the initial values to new values
$Vehicle = “Bus”;
?>
Accessing PHP Variable Values Now that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created. For example, if we want to display the value which we assigned to our rainbow_colour variable we can simply reference it in our echo command: <?php
echo “The colours of rainbow is $rainbow_colour.”;
?> This will cause the following output to appear in the browser: The colours of rainbow is 8. The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example:
<?php
echo “The color of the rainbow is the $rainbow_colourth”;
?>
What we are looking for in this scenario is output as follows: The color of rainbow is the 8th. Unfortunately PHP will see the th on the end of the $rainbow_colour variable name as being part of the name. It will then try to output the value of a variable called $rainbow_colourth, which does not exist. This result in nothing being displayed for this variable: The colour of the rainbow Fortunately we can get around this issue by placing braces ({ and }) around the variable name to distinguish the name from any other trailing characters:
<?php
echo “The color of the rainbow is the ${rainbow_colour}th”;
?>
To give us the desired output: The color of the rainbow is 8th. Changing the Type of a PHP Variable Loosely typed languages such as PHP (and JavaScript), allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:
<?php
$myNumber = 6; // variable is of integer type
$myNumber = six; // variable has now changed to string type
?>
The process of dynamically changing the type of a variable is known as automatic type conversion.
| PHP Arrays | |||
| An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP’s arrays are actually maps (each key is mapped to a value). | |||
| PHP Arrays provide a way to group together many variables such that they can be referenced and manipulated using a single variable. An array is, in many ways, a self-contained list of variables. | |||
| Once an array has been created items can be added, removed and modified, sorted and much more. The items in an array can be of any variable type, and an array can contain any mixture of data types – it is not necessary to have each element in the array of the same type. | |||
| What is an array? | |||
| When working with PHP, sooner or later, you might want to create many similar variables. | |||
| Arrays are special data types. Despite of other normal variables an array can store more than one value. Let’s suppose you want to store basic colors in your PHP script. You can construct a small list from them like this: Color list: * red * green * blue * black * white It is quite hard, boring, and bad idea to store each color in a separate variable. It would be very nice to have the above representation almost as it is in PHP. And here comes array into play. The array type exists exactly for such purposes. So let’s see how to create an array to store our color list. | |||
| There are three different kind of arrays: | |||
| • Numeric array – An array with a numeric ID key • Associative array – An array where each ID key is associated with a value • Multidimensional array – An array containing one or more arrays |
|||
| Creating a PHP Array | |||
| Arrays are created using the array() function. The array() function takes zero or more arguments and returns the new array which is assigned to a variable using the assigment operator (=). If arguments are provided they are used to initialize the array with data. | |||
| PHP arrays grow and shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages. | |||
| We can create an empty array as follows: | |||
| <?php$citylist = array();
?> |
|||
| Alternatively, we can create an array pre-initialized with values by providing the values as arguments to the array() function: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
?> |
|||
| Accessing Elements in a PHP Array | |||
| The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remember that the index is zero based so the first element is element 0): | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo $citylist[1]; ?> |
|||
| The above echo command will output the value in index postion 1 of the array, in this case Output will be: | |||
| Delhi | |||
| Manipulating Array | |||
| Changing, Adding and Removing PHP Array Elements | |||
| An array element can be changed by assigning a new value to it using the appropriate index key. | |||
| For example, to change the first element of an array: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo “<br> Before changing the Array, element [0] : “.$citylist[0]; $citylist[0]= “Faridabad”; echo “<br> After changing the Array , element [0] : “.$citylist[0]; ?> |
|||
| Output: | |||
| A new item can be added to the end of an array using the array_push() function. Push one or more elements onto the end of array | |||
| Syntax: | |||
| int array_push ( array array, mixed var [, mixed …] ) | |||
| array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. This function takes two arguments, the first being the name of the array and the second the value to be added: | |||
| Example: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo “Before changing the Array<pre>”; print_r($citylist); array_push($citylist, “Gurgaon”); echo “</pre><br> After changing the Array<br><pre>”; print_r($citylist); echo “</pre>”; ?> |
|||
| Output: | |||
| The first element of the array can be removed of the array using the array_shift() function, shifts the first value of the array off and returns it, shortening the array by one element and moving everything down.. | |||
| Syntax: | |||
| mixed array_shift ( array ) | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo “Before Removing the element [0] from array”; echo “<pre>”; print_r($citylist); echo “</pre>”; array_shift($citylist);// Add Gurgaon to start of array echo “After Removing the element [0] from array”; echo “<pre>”; print_r($citylist); echo “</pre>”; ?> |
|||
| Output: | |||
| Before Removing the element [0] from arrayArray
( [0] => Noida [1] => Delhi [2] => Raipur [3] => Ambikapur [4] => Bhagalpur ) After Removing the element [0] from array Array ( [0] => Delhi [1] => Raipur [2] => Ambikapur [3] => Bhagalpur ) |
|||
| The last item added to an array can be removed from the array using the array_pop() function. | |||
| Syntax: | |||
| mixed array_pop ( array array ) | |||
| The following example removes the last element added: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo “Original Array”; echo “<pre>”; print_r($citylist); echo “</pre>”; array_push($citylist, “Jaipur”); // Add Jaipur to end of array echo “After Adding an element to the array”; echo “<pre>”; print_r($citylist); echo “</pre>”; array_pop($citylist); // Remove Jaipur from the end of the array echo “After Removing an element from array”; echo “<pre>”; print_r($citylist); echo “</pre>”; ?> |
|||
| Output: | |||
| Try it yourself! | |||
| An element can be added to the start of the array by using array_unshift() function: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
echo “Before Removing the element [0] from array”; echo “<pre>”; print_r($citylist); echo “</pre>”; array_shift($citylist);// Add Gurgaon to start of array echo “After Removing the element [0] from array”; echo “<pre>”; print_r($citylist); echo “</pre>”; array_unshift($citylist,”Mumbai”) ; echo “After Adding Mumbai to the start of the array”; echo “<pre>”; print_r($citylist); echo “</pre>”; ?> |
|||
| Output: | |||
| Original ArrayArray
( [0] => Noida [1] => Delhi [2] => Raipur [3] => Ambikapur [4] => Bhagalpur ) After Removing the element [0] from array Array ( [0] => Delhi [1] => Raipur [2] => Ambikapur [3] => Bhagalpur ) After Adding Mumbai to the start of the array Array ( [0] => Mumbai [1] => Delhi [2] => Raipur [3] => Ambikapur [4] => Bhagalpur ) |
|||
| Looping through PHP Array Elements | |||
| It is often necessary to loop through each element of an array to either read or change the values contained therein. There are a number of ways that this can be done. | |||
| One such mechanism is to use the foreach loop. The foreach loop works much like a for or while loop and allows you to iterate through each array element. There are two ways to use foreach. The first assigns the value of the current element to a specified variable which can then be accessed in the body of the loop. | |||
| The syntax for this is: | |||
| foreach ($arrayName as $variable) | |||
| For example: | |||
| <?php$citylist = array(“Noida”, “Delhi”, “Raipur”, “Ambikapur”, “Bhagalpur”);
foreach ($citylist as $city) { echo “$city <br>”; } ?> |
|||
| Will result in the following output: | |||
| Noida Delhi Raipur Ambikapur Bhagalpur |
|||
| For associative arrays the foreach keyword allows you to iterate through both the keys and the values using the following syntax: | |||
| foreach ($arrayName as $variable) | |||
| For example: | |||
| <?php$employees = array(’empName’=> ‘Sanjay Singh’, ’empAddr’=>’1 The Street’, ‘accountNumber’=>’123456789’); echo “<pre>Employee Name foreach ($employees as $key=>$value) { echo ” $key = $value<br>”; } </pre> ?> |
|||
| Output: | |||
| Try it yourself | |||
|
|
|||
Explode and Implode The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence, which contains name of 5 persons, you could ask explode to use the sentence’s commas “,” as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence “Ram, Ravish, Rajeev, Rakesh, Ramesh” would look like this after explode got done with it: Explode is a PHP function which let as divide a string into smaller pieces,explode is used to break up a string into chunks, it acts on a string, and returns an array.Ram
Ravish
Rajeev
Rakesh
Ramesh The explode() function breaks a string into an array. Syntax array explode(separator,string,limit)
| Parameter | Description | Required/Optional |
| separator | Specifies where to break the string | Required. |
| string | The string to split. | Required. |
| limit | Indicates t he maximum number of array elements to return | Optional |
For example to break a string $str, separated by , the syntax would be: explode (“,”,$str); Example:
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
<title>PHP Tutorial: Working with String</title>
</head>
<body>
<?php
$str=”Ram,Ravish,Rajeev,Rakesh,Ramesh”;
$arr=explode(“,”,$str);
?>
<pre>
<?php
echo “Original String :”.$str.”<br>”;
echo “Exploded Array\n<br>”;
print_r($arr);
?>
</pre>
</body>
</html>
When executed the above script will display following output: You can also use foreach loop to print the content of array. Implode The implode works exactly opposite of explode function. The PHP function implode operates on an array and is known as the “undo” function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string. The implode function accepts to arguments: separator and the array Syntax: implode(separator,array)
| Parameter | Description |
| separator | Optional. Specifies what to put between the array elements. Default is “” (an empty string) |
| array | Required. The array to join to a string |
Example:
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
<title>PHP Tutorial: Working with String</title>
</head>
<body>
<?php
$arr=array(“Ram”,”Ravish”,”Rajeev”,”Rakesh”,”Ramesh”);
$str=implode(“,”,$arr);
?>
<pre>
<?php
echo $str;
?>
</pre>
</body>
</html>
On execution above script produces the following output: Assignment 1. Convert the following String to Array ”Hello, World!; Welcome, to eBIZ Education; Thanks for visiting” first convert the string to Array by using “;” as separator, then using “,” as separator and finally using space “ ”
2. Convert the following Array to String: $my_arr1=array(“Mika”, “Mona”, “Mitali”, “Madhu”, “Megha”, “Meghna”);
| PHP Flow control and looping | |||
| IF-ELSE | |||
| The PHP If Statement | |||
| The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out “Happy New Year!” at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occurring every year on January 1st. | |||
| This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML. | |||
| If Statement Example | |||
| IF (conditional statement) {
} |
|||
| The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement. | |||
| PHP Code: | |||
| <?php
$my_name = "phpguy"; if ( $my_name == "phpguy" ) { echo "Your name is phpguy! } echo “Welcome to eBIZ Education!”; ?> |
|||
| Display: | |||
| Your name is phpguy! Welcome to eBIZ Education! |
|||
| Did you get that we were comparing the variable $my_name with “phpguy” to see if they were equal? In PHP you use the double equal sign (==) to compare values. In addition, notice that because the if statement turned out to be true, the code segment was executed, printing out “Your name is phpguy!”. | |||
| Let’s go a bit more in-depth into this example to iron out the details. | |||
| • We first set the variable $my_name equal to “phpguy”.
• We next used a PHP if statement to check if the value contained in the variable $my_name was equal to “phpguy” • The comparison between $my_name and “phpguy” was done with a double equal sign “==”, not a single equals”=”! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal. • Translated into english the PHP statement ( $my_name == “phpguy” ) is ( $my_name is equal to “phpguy” ). • $my_name is indeed equal to “phpguy” so the echo statement is executed. |
|||
| A False If Statement | |||
| Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to: | |||
| PHP Code: | |||
| <?php
$my_name = "LAMPGuy"; if ( $my_name == "phpguy" ) { echo "Your name is phpguy! } echo “Welcome to eBIZ Education!”; ?> |
|||
| Display: | |||
| Welcome to eBIZ Education! | |||
| Here the variable contained the value “LAMPGuy”, which is not equal to “phpguy”. The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal! | |||
| IF.. ELSE statement | |||
| IF..ELSE is used in PHP to provide conditional judgements. | |||
| The basic syntax is as follows: | |||
| IF (conditional statement) {
} ELSE { } |
|||
| Let’s see an example. Assuming we have the following piece of code: | |||
| $num = 7;IF ($num > 5) {
print “Number is greater than 5”; } ELSE { print “Number is less than 5”; } |
|||
| The output of the above code is: | |||
| Number is greater than 5 | |||
| This is because the condition, ($num > 5), is true. Therefore, the code in the bracket after IF is executed. | |||
|
|
|||
| Switch-case | |||
| The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. SWITCH is used in PHP to replace nested IF..ELSE loops, and is similar to the CASE command in other computer languages. | |||
| With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation! | |||
| The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time. | |||
| Syntax: | |||
| switch (expression){
case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } |
|||
| Example: | |||
| <?php$day=1;
switch($day) { case 1: echo “<today is <b>Monday</b>”; break; case 2: echo “Today is <b>Tuesday</b>”; break; default: echo “<b>Invalid Day Number “.$day.”</b>”; } ?> |
|||
| Type the above code and save it as switch-case.php and open the page in browser to view the output. | |||
|
|
|||
PHP Loops It is generally accepted that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowledge that computers really don’t do anything unless someone programs them to tell them what to do. Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met. This is where for, while and do … while loops are of use. Note: if you have any kind of programming experience, you won’t have any problem with PHP either. Loops and Conditional statements are same in PHP as they are found in other programming languages, such as C/C++/Java/ any other. For loop Suppose you wanted to add a number to itself ten times. One way to do this might be to write the following PHP script:
<?php
$var = 10;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
?>
Whilst this is somewhat ungainly and time consuming to type, it does work. What would happen, however, if there was a requirement to perform this task 100 times or even 10,000 times. Writing a script to perform this as above would be prohibitively time consuming. This is exactly the situation the for loop is intended to handle. The syntax of a PHP for loop is as follows:
for ( ”initializer”; ”conditional expression”; ”loop expression” )
{
// PHP statements to be executed go here
}
The initializer typically initializes a counter variable. Traditionally the variable $i is used for this purpose. For example: $i = 0 which sets the counter to be the value $i and sets it to zero. The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 1000 times:
$i < 1000
Finally, the loop expression specifies the action to perform on the counter variable.
For example to increment by 1: $i++
Bringing this all together we can create a for loop to perform the task outlined in the earlier in this section:
<?php
$j = 10;
for ($i=0; $i<10; $i++)
{
$j += $j;
}
echo $j;
?>
Output: 10240 As with the if statement, the enclosing braces are optional if a single line of script is to be executed, but their use is strongly recommended. While loop The PHP for loop described previously works well when you know in advance how many times a particular task needs to be repeated in a script. Clearly, there will frequently be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this PHP, provides the while loop. Essentially, the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is defined follows:
<?php
while (”condition”)
{
// PHP statements go here
}
?>
where condition is an expression that will return either true or false and the // PHPstatements go here comment represents the PHP to be executed while the expression is true. For example:
<?php
$mycount=0;
$j=1;
while ( $myCount < 100 )
{
$myCount = $myCount + $j;
echo “<br>”.$myCount;
}
?>
Output:
Try it yourself In the above example the while expression will evaluate whether $myCount is less than 100. If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks. If $myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of $myCount. This process repeats until $myCount is greater than 100, at which point the loop exits. Do-while loop You can think of the do … while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do .. while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need. The syntax for the do … while loop is as follows:
<?php
do
{
”PHP statements”
} while (”conditional expression”)
?>
In the do … while example below the loop will continue until $i equals 0:
<?php
$i = 10;
do
{
$i–;
} while ($i > 0);
?>
Foreach loop The foreach statement is used to loop through arrays.
For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop, you’ll be looking at the next element. Syntax: foreach (array as value)
{
code to be executed;
} Example The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$city=array(“Noida”, “Ambikapur”, “Banglore”);
echo “<h3>Foreach Demo</h3><hr width= \”80%\”>”;
$num=0;
foreach ($city as $value)
{
$num+=1;
echo “City $num: ” . $value . “<br />”;
}
echo “<hr width=\”80%\”>”;
?>
</body>
</html>
Type the above code and save it as foreach.php and open the script in browser to view the output. Assignment: 1. Write a PHP script to print a countdown (10,9.. ..1).
2. Write a PHP Script to print Square of all numbers from 1-10 using loop.
3. Write a PHP script to print Square of all even numbers between 1-20.
| PHP Functions | |||
| PHP Functions | |||
| In the world of programming and scripting there are two ways to write code. One way is to write long, sprawling and monolithic sections of script. Another is to break the scripts up into tidy, self contained modules that can be re-used without having to re-invent the same code over and over again. | |||
| Obviously the latter is highly preferable to the former, and the fundamental building block of this approach to writing PHP scripts is the function. | |||
| Similar to other programming languages, such as C/C++/Java/JavaScript/etc., PHPprovides a way for programmers to define functions, which can then be called elsewhere in the program. | |||
| A function is a block of code that can be executed whenever we need it. A function is just a name we give to a block of code that can be executed when needed | |||
| Functions are basically named scripts that can be called upon from any other script to perform a specifc task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called. | |||
| PHP functions exist it two forms, functions that are provided with PHP to make your life as a web develeper easier, and those that you as a web developer create yourself. | |||
|
|
|||
Creating and using simple functions The first step in creating a PHP function is provide a name by which you will reference the function. Naming conventions for PHP functions are the same as those for variables in that they must begin with a letter or an underscore and must be devoid of any kind of white space or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions. PHP functions are created using the function keyword followed by the name and, finally, a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces. The following example function simply outputs a string when it is called:
<?php
function sayHello()
{
print “Hello”;
}
?>
<hr>
<center><h3>PHP Function Demo</h3></center>
<hr>
<?php
sayHello();
?>
Save the above script as simplefunction.php and open the page in browser to view the output.
Passing Parameters to a Functions Parameters (or arguments as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function. A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition. Those variables can then be accessed from within the function body as follows:
<HTML>
<HEAD>
<TITLE>PHP Function: Passing Parameter
</TITLE></HEAD>
<BODY>
<?php
function sum ($val1, $val2)
{
$result=$val1+$val2;
echo $result;
}
?>
<hr>
<CENTER><H3>PHP Function: Passing Parameter</H3></CENTER>
<hr>
<p>Sum of 21 and 79 =<?php sum(21,79);?></p>
</BODY>
</HTML>
Type the above script and save it as function-parameter.php and open the page in the browser to view the output. In the above example the sum () function accepts two parameters as arguments, adds them together and returns the result.
Returning values from function A single value may be returned from a PHP function to the script from which it was called. The returned value can be any variable type of your choice. Besides being able to pass functions information, you can also have them return a value. However, a function can only return one thing, although that thing can be any integer, float, array, string, etc. that you choose! How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function. Something like: • $myVar = somefunction();
Let’s demonstrate this returning of a value by using a simple function that returns the sum of two integers. The return keyword is used to return the value:
<HTML>
<HEAD>
<TITLE>PHP Function: Returning Values
</TITLE></HEAD>
<BODY>
<?php
function sum ($val1, $val2)
{
$result=$val1+$val2;
return $result;
}
?>
<hr>
<CENTER><H3>PHP Function: Returning Values</H3></CENTER>
<hr>
<p>Sum of 21 and 79 =<?php echo ” “.sum(21,79);?></p>
</BODY>
</HTML>
The above example returns the value of 100 to the calling script.
| Built-in Functions | |||
| Like any other programming language, PHP offers several built-in function for day-to-day use in your coding. Most of these functions are very helpful in achieving your programming goals and are well documented. | |||
| Some (not even most) usage of built-in functions are as mentioned below: | |||
| • Converting a string of letters to uppercase and lowercase• Displaying and using the date and time
• Initializing and closing a database connection • Declaring and using an array • Handling files • Accessing data in forms • Filesystem Functions • Function to open FTP connections • Email related functions • Mathematical Functions • MySQL specific functions • URL Functions |
|||
| For complete list of built-in PHP functions please visit | |||
| http://us2.php.net/quickref.php . | |||
|
|
|||
File inclusion functions include function INCLUDE is used in PHP to append the code from an external file into the current file. The syntax for INCLUDE is INCLUDE (“external_file_name”); This is a convenient feature for a large website. Often, we may want to change an element of the website that is consistent across the entire site, yet we don’t want to go through the trouble of updating every single file. In this case, we can simply useINCLUDE in every file to call the same external file, and then all we need to change is the content in that one external file. Let’s look at a simple example. Assuming we have the following three files: main.php
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>PHP Include</title>
</head>
<body>
<table width=”100%” border=”0″ cellspacing=”3″ cellpadding=”0″>
<tr>
<td width=”18%”> </td>
<td width=”72%”> </td>
<td width=”10%” rowspan=”2″> </td>
</tr>
<tr>
<td rowspan=”2″><?php
include (“menu.php”);
?>
</td>
<td><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR></td>
</tr>
<tr>
<?php
#Footer
include (“footer.php”);
?>
<td> </td>
</tr>
</table>
</body>
</html>
2. menu.php
<?php
#External PHP Menu
?>
<table width=”100%” border=”0″ cellspacing=”3″ cellpadding=”0″>
<tr>
<td><A HREF=”http://www.ebizelindia.com”>eBIZ.com Home</A></td>
</tr>
<tr>
<td><A HREF=”http://education.ebizelindia.com”>eBIZ Education</A></td>
</tr>
<tr>
<td><A HREF=”http://mail.ebizelindia.com”>Mail</A></td>
</tr>
<tr>
<td><A HREF=”mailto:support@ebizelindia.com”>Contact US</A></td>
</tr>
</table>
3. Footer.php <td style=”background-color:#0099FF; text-align:center”>
<p style=” font-family:Verdana, Arial, Helvetica, sans-serif; color:#ffccFF; size:14; font-weight:700″>© eBIZ.com Pvt. Ltd.</p></td> Upon executing main.php, we’ll get the following output: This is because, to the web server, it sees these three scripts as single script. require function Both include & require constructs are identical in every way except how they handle failure. include() produces a Warning on the other hand require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page and use include otherwise. Syntax: require (“external_file”); We can use require in our previous example in place of include or vice versa. Now, suppose we are using require instead of include to include menu.php and we misspelled its name as meno.php, then it will produce the following error:
<?php
require (“meno.php”);
?>
include_once and require_once functions include_once The behavior of include_once is similar to the include () statement, that is, include_once() statement includes and evaluates the specified file during the execution of the script. The difference being that if the code from a file has already been included,include_once will not be included again. As the name suggests, it will be included just once. require_once The require_once() statement includes and evaluates the specified file during the execution of the script. The only difference between require & require_once is that if the code from a file has already been included, it will not be included again. Assignment 1. Create a Multi file [at least 5(1 main 4 sub)] PHP script and use all file inclusion functions to include them to main script.
2. Write a PHP script to print a countdown (10,9.. ..1) using function.
3. Write a PHP Script to print Square of all numbers from 1-10 using loop using function.
4. Write a PHP function to calculate and return sum of all even numbers between 1-50.
Remember function should not print the output by itself, rather it should return a value.
5. Create a function hello which accepts name as argument and print “Hello XYZ”, where XYZ is the value of the argument passed to the function.
ntroduction While PHP 4 was the first version to offer Object-Oriented Programming (OOP)capabilities, many considered the feature to be poorly designed and more an afterthought than anything else. PHP 5 resolves many of the version 4 OOPinconsistencies, not to mention greatly enhances the language’s object-oriented capabilities. While you’re still free to program using a procedural methodology, those of you with object oriented backgrounds will certainly feel much more at home creating fully object-driven PHP applications. In this article I’ll introduce many of these new and improved features. In addition, for those of you somewhat new to the subject, this article will also offer a bit of instruction regarding those concepts key to truly understanding OOP. While for many languages object orientation is simply a matter of course, it took several years before such features were incorporated into PHP. Yet the early forays into adding object-oriented features to the language were considered by many to be a poor attempt at best. Although the very basic premises of object-oriented programming (OOP) were offered in version 4, several deficiencies existed, including the following: • An unusual object-referencing methodology
• No means for setting the scope (public, private, protected, abstract) of fields and methods
• No standard principle for naming constructors
• Absence of object destructors
• Lack of an object-cloning feature
• No support for interfaces Thankfully, version 5 eliminated all of the abovementioned encumbrances, offering significant improvements over the original implementation, as well as a bevy of new OOP features. This chapter and the following aim to introduce these new features and enhanced functionality.
The Benefits of OOP The birth of object-oriented programming represented a major paradigm shift in development strategy, refocusing attention on an application’s data rather than its logic. To put it another way, OOP shifts the focus from a program’s procedural events toward the real-life entities it ultimately models. The result is an application that closely resembles the world around us. This section examines three of OOP’s foundational concepts:
Encapsulation,
Inheritance,
and
Polymorphism Together, these three ideals form the basis for the most powerful programming model yet devised. Note: For detailed information on OOP please read our C++ tutorial athttp://education.ebizelindia.com PHP provides extensive support for developing object-oriented web applications. The area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of this Tutorial. Instead we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to PHP development. An object-oriented programming system (OOPS) consists of objects. The object determines both the state and the behavior of the corresponding element.
Why has object-oriented programming gone from being “something to think about” to being a de-facto standard in the way software is developed today? OOA/OOD/OOP is good for: * Analyzing user requirements * Designing software * Constructing software o Reusability (reusable components) o Reliability o Robustness o Extensibility o Maintainability * Reducing large problems to smaller, more manageable problems
Why OO PHP5? For now let’s just say that OOP is about creating relatively small objects with specific functions that interact with each other to form a complete application. Typically, the main advantages of OOP are: * Reusability of code:
a well designed object has only one specific function and is therefore completely independent of the environment it is placed in and thus can be reused easily. * Clearer structure of code:
Again a well designed object has only one specific function which means that all the code supporting that function is located in one place which increases maintainability. * Easy to maintain:
While using Classes for small projects in your PHP script may seem cumbersome due to extra lines of code that is required, but when you work on a large project or as your project grows in term of size, pages or functionality, using OO approach becomes a necessity. A major disadvantage of OOP is that it requires more lines of code and is therefore more time consuming to produce. In PHP we as developers are left with a choice. Typically, anyone who started out with PHP without any (OO) programming background will have started with learning procedural coding. Most tutorials on the web only cover procedural coding and quite honestly, the old fashioned way is just easier to use in many situations (for instance in small applications, or when you just start out with PHP).
Difference between PHP4 & PHP5 In general when a new software version appears everybody hurries to update it especially if it is for free. PHP 5 has just appeared and it seems that there are people who use the PHP 4 version and others who use the PHP 5 one. You probably know that PHP 5 is destined for OOP, but it appears that habitual programming can be used too. Moreover, OOP is used in PHP4 as well, with the difference that in PHP5 things are a little more evaluated. This means that in PHP4 safety modes for classes (public, private) are not accepted. InPHP4 the objects are a kind of structures which accept objects and functions as well, according to OOP. In PHP4 they are useful as well. If you are used to working with PHP4 you can use PHP5 with no problems because the differences are not significant and the changes were made so that programmers would not be confused. An example would be class builders which, in PHP4 were functions within the classes bearing the same name as the class. In PHP5 it is firstly checked if there is a function (method) __construct (). If it does not exist, check if there is a function (method) which has the same name as the class. This means that even if you are not aware of the latest news in the domain of PHP5, your scripts will function without any problem. But it is strongly recommend to migrate to PHP5 (if you are using PHP4) or to start withPHP5 if you are new to PHP, because PHP has discontinued the support of PHP4 and it will not release any patches or security updates for PHP4. Since PHP has withdrawn support for PHP4 web servers will discontinue support of PHP4 sooner or later, so the sooner you change the better for you. Differences Between PHP 4 and 5 Language Features PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types. The foreach construct now supports by-reference declaration of the value element. A number of new functions, particularly for string and array manipulation, has also been added to the core platform. Objects For all intents and purposes, all objects in PHP 5 are passed by reference. This means that assigning an object to a variable will not create a copy of the former, but simply creates another reference to it. Constants, as well as static methods and properties, can now be defined within the scope of a class. Class methods and properties now feature visibility, and can be declared as public, private or protected. Classes and methods can also be declared as final to prevent further inheritance. Since all objects are assigned by reference, you now need a specialized mechanism to copy objects. This is provided by the clone construct and the __clone() magic method. PHP 5 features unified constructors and destructors—all constructors should now be named __construct(), and the new __destruct() magic method has been added for object destruction. With the addition of interfaces and abstract classes, PHP developers now have far greater control over how they implement their object-oriented code. Interfaces can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint. Class definitions can now be loaded on demand by using the __autoload() function. MagicMethods A multitude of new “magic” methods has been introduced in PHP 5: __get() and __set() are called when accessing or assigning an undefined object property, while __call() is executed when calling a non-existent method of a class. __isset() is called when passing an undefined property to the isset() construct. • __unset() is called when passing an undefined property to unset().
• __toString() is called when trying to directly echo or print() an object.
• __set_state() is inserted dynamically by var_export() to allow for reinitialization on execution of var_export()’s output. Selected New Extensions • SimpleXML allows easy access to XML data using object and array notation. • PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the form of the libxml2-based DOM and XSL extensions. • The PHP Data Objects (PDO) extension provides a unified database access extension that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer—except for prepared queries, it does nothing to abstract the actual database code (SQL), itself. • The hash extension is a new replacement for the GPLed libmhash; it was added to thePHP core starting with version 5.1.2. It can produce hashes using many algorithms, including the familiar MD5 and SHA1, as well as some more secure (albeit slower) algorithms, such as snefru. • The Standard PHP Library (SPL) provides numerous interfaces that enhance the way classes interact with the PHP language, including the new Iterator interfaces. • The new Reflection extension allows for runtime introspection of executing PHP code. ErrorManagement Classes now support exceptions; the new set_exception_handler() functionallows you to define a script-wide exception handler. • The E_STRICT error reporting level has been added to the language to emit notices when legacy or deprecated code is encountered.
Classes and Objects in PHP5 What is an Object? An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application. Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members. An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. What is a Class? Much as a blueprint or architect’s drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be. How is an Object Created from a Class? The process of creating an object from the class ‘blueprint’ is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated using the new keyword. For example, to create an instance of a class called employee_details we would write: $emp = new employee_details(); In the above example we now have an object called $emp of type employee_details. What is sub-classing? It is possible to build classes that are derived from other classes, extending the functionality of the parent class to make it specific to a particular requirement. For example you might have a vehicle class which contains the attributes common to all vehicles, and a subclass called car which inherits all the generic vehicle attributes but adds some its own car specific methods and properties. Defining a PHP Class Before an object can be instantiated we first need to define the class ‘blueprint’ for the object. Classes are defined using the class, keyword followed by braces which will be used to enclose the body of the class: <?php
class employee_details
{ //variables, methods and other class elements }
?> We have now defined a class. Note: the structure of class in PHP is almost same to the classes found in other Object Oriented Programming languages such as Java/C++ etc.
Creating and Using Classes in PHP5 Defining a PHP Class Before an object can be instantiated we first need to define the class ‘blueprint’ for the object. Classes are defined using the class keyword followed by braces which will be used to enclose the body of the class:
<?php
class employee_details {
}
?>
We have now defined a class. The next step is add some functionality to the class. PHP Class Constructors and Destructors The next step in creating a class is to define what should happen when an object is first instantiated using the class, and also when that object is later destroyed. These actions are defined in the constructor and destructor methods of the class. The constructor and destructor are really just functions that get called when the object is created and destroyed and are defined in the class body using the function keyword. This needs to be prefixed with the public qualifier. This means the method is accessible to code outside of the object. The default names for the constructor and destructor are __construct and __destruct respectively. Both methods can take arguments to be used in initializing the object. These are declared in the same way arguments are defined in any function (see PHP Functions for details). We can now extend our employee_details class to include a constructor and destructor:
<?php
class employee_details{
public function __construct($emp_id,$emp_name,$addr)
{
echo “Constructor Called with the following values<br>”;
echo “Employee ID = “.$emp_id.”<br>E
mployee Name = “.$emp_name.”<br>Address = “.$addr;
}
public function __distruct(){}
}
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> PHP Tutorial: Working with Classes </TITLE>
<META NAME=”Generator” CONTENT=”jNote-iT”>
</HEAD>
<BODY>
<?php
$emp=new employee_details(“EMP0012″,”Aman Singh”,”B-320,
Sector 44, Rohni”);
?>
</BODY>
</HTML>
When the example is loaded into a browser we should get the following output: Creating Members in a PHP Class Class members are essentially variables and methods embedded into the class. Members can be public or private and static or variable. Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). Members declared as static are immutable, in that once defined they cannot be changed (much like constants). Members and functions are prefixed with public, private and static when declared in the class. The default is public non-static. We can now extend out employee_details class to add member variables to hold the account name and number passed into the constructor. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as private. We will also add to our constructor to assign the passed arguments to our new members. When doing so we need to use the $this variable to tell PHP we are setting variables in the current class:
<?php
class employee_details{
private $emp_id;
private $emp_name;
private $addr;
public function __construct($emp_id,$emp_name,$addr)
{
$this->emp_id=$emp_id;
$this->emp_name=$emp_name;
$this->addr=$addr;
echo “Constructor Called with following values:”;
echo “<br>Employee ID : “.$this->emp_id;
echo “<br>Employee Name : “.$this->emp_name;
echo “<br>Address : “.$this->addr;
}
public function __distruct(){}
}
?>
<!DOCTYPE HTML PUBLIC
“-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME=”Generator” CONTENT=”jNote-iT”>
</HEAD>
<BODY>
<?php
$emp=new employee_details(“EMP0012”,
“Aman Singh”,”B-320, Sector 44, Rohni”);
?>
</BODY>
</HTML>
The next task is to define methods that will give us access to our data. Defining and Calling Methods We define our own methods in much the same way as we declared the constructor and destructor methods with exception that we get to choose the names. We declare methods inside PHP classes in the fashion we declare methods outside, the only difference being that, we may specify an access specifier like public, private etc. To demonstrate this we will add to our class to provide methods to get and set the Employee id, name and address: Source code for Employee.class.php
<?php
class employee_details{
private $emp_id;
private $emp_name;
private $addr;
function __construct($emp_id,$emp_name,$addr)
{
$this->emp_id=$emp_id;
$this->emp_name=$emp_name;
$this->addr=$addr;
}
//Setter Methods of employee details class
public function setEmpID($emp_id)
{
$this->emp_id=$emp_id;
}
public function setEmpName($emp_name)
{
$this->emp_name=$emp_name;
}
public function setEmpAddr($addr)
{
$this->addr=$addr;
}
//getter Methods of employee details class
public function getEmpID()
{
return $this->emp_id;
}
public function getEmpName()
{
return $this->emp_name;
}
public function getEmpAddr()
{
return $this->addr;
}
public function display_details()
{
echo “<br>Employee ID : “.$this->emp_id;
echo “<br>Employee Name : “.$this->emp_name;
echo “<br>Address : “.$this->addr;
}
}
?>
Save the above script as employee.class.php Now that we have defined our getter and setter method to get and set the employee values we can call the methods. This is done by specifying the name of the object on which the methods are being called. This is followed by ‘->’, and then the name of the method we are calling (including the parentheses containing any arguments required):
$emp2=new employee_details(“”,””,””);
//Using setter metter to set the employee details
$emp2->setEmpID(“EMP0032”);
$emp2->setEmpName(“Neelam Rai”);
$emp2->setEmpAddr(“C-216/2,
Barakhamba Road, New Delhi”);
Complete Source code of employee_class.php
<?php
require (“employee.class.php”);
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME=”Generator” CONTENT=”jNote-iT”>
</HEAD>
<BODY>
<?php
$emp1=new employee_details(“EMP0012”,
“Aman Singh”,”B-320, Sector 44, Rohni”);
$emp2=new employee_details(“”,””,””);
//Using setter metter to set the employee details
$emp2->setEmpID(“EMP0032”);
$emp2->setEmpName(“Neelam Rai”);
$emp2->setEmpAddr(“C-216/2,
Barakhamba Road, New Delhi”);
#Displaying Details of Employee 1
echo “<h3>Details of Employee 1</h3>”;
$emp1->display_details();
#Displaying details of Employee 2
echo “<h3>Details of Employee 1</h3>”;
$emp2->display_details();
echo “<br><b> Name of Employee 2 is :
“.$emp2->getEmpName().”</b>”;
?>
</BODY>
</HTML>
The above example sets the account name and number when instantiating the object. It then the getEmpName (to verify the change), thereby producing the following output: Getting Information about a PHP Object There are number of ways to find out information about classes. An array of classes to which your script has access can be obtained using the get_declared_classes() function. The class_exists() function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function. It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists. The method_exists() function, when passed an object pointer and method name as arguments, will return a true or false value indicating the existence of the method. Inheritance and sub classing in PHP5 Once a class has been defined it is possible to create a new class derived from it that extends the functionality of the original class. The parent class is called the superclass and the child the subclass. The whole process is referred to as ‘subclassing. A subclass of a class can be defined using the extends keyword when declaring the subclass. For example we might choose to create a subclass of our employee_details class called tech_employee which defines an interest bearing type of employee:
<?php
require (“employee.class.php”);
class tech_employee extends employee_details
{
private $dept;//Variable to store Department of the Employee
private $team_id;//Variable to store Team ID of the employee
private $prj_name;//Variable to store name
of the Project employee is currently working on
private $prj_role; // Variable t
o store Role of the employee in the project
//other tech_employee
specific processing logic, methods etc
}
The important point to note here is that tech_employee inherits all the members and methods of employee_details and adds a new member(s) (such as team id[$team_id], project name[$prj_name], etc.). We can extend the class further by adding a new method to return other tech employee specific details: Source code of tech_employee.class.php
<?php
require (“employee.class.php”);
class tech_employee extends employee_details
{
private $dept;//Variable to store Department of the Employee
private $team_id;//Variable to store Team ID of the employee
private $prj_name; // Variable to store name o
f the Project employee is currently working on
private $prj_role; // Variable to s
tore Role of the employee in the project
public function __construct($emp_id, $e
mp_name,$addr,$dept,$team_id,$prj_name,$prj_role){
echo “Calling Parent Constructor”;
parent::__construct($emp_id,$emp_name,$addr);
//Calling Parent Class Constructor with required Parameter
$this->dept=$dept;
$this->team_id=$team_id;
$this->prj_name=$prj_name;
$this->prj_role=$prj_role;
}
public function setDept($dept){
$this->dept=$dept;
}
public function setTeam_id($team_id){
$this->team_id=$team_id;
}
public function setPrjName($prj_name){
$this->prj_name=$prj_name;
}
public function PrjRole($prj_role){
$this->prj_role=$prj_role;
}
function getDept(){
return $this->dept;
}
function getTeamId(){
return $this->team_id;
}
function getPrjName(){
return $this->prj_name;
}
function getPrjRole(){
return $this->prj_role;
}
public function display_details(){
parent::display_details(); //calling parent’s display method
#echo “<pre>”;
echo “<br>Employee Department: <b>”.$this->dept.”</b>”;
echo “<br>Team ID :
<b>”.$this->team_id.”</b>”;
echo “<br>Current Project
: <b>”.$this->prj_name.”</b>”;
echo “<br>Role in th
e Current Project:<b>”.$this->prj_role.”</b>”;
}
}
?>
In PHP parent keyword along with :: (scope resolution) operator is used to access parent class methods and properties. Source code of extended_employee.php
<?php
require (“tech_employee.class.php”);
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME=”Generator” CONTENT=”jNote-iT”>
</HEAD>
<BODY>
<?php
$emp3=new tech_employee(“TECH0031″,”Ravish Kumar”,”D-410, S
ector 19, Noida”,”TECH-PHP”,”PHP03″,”EBIZ EDUCATION”,”PHP Developer”);
echo “<h3>Details of Employee 1[TECH EMPLOYEE]</h3>”;
echo “<pre>”;
$emp3->display_details();
echo “</pre>”;
?>
</BODY>
</HTML>
When this page is executed it produces the following output: Assignment
1. Create a PHP class Simple_class and implement “Hello World!” using hello function in Simple_class
2. In the above Class create another function helloTo, which accepts an argument e.g. name and display “Hello :)”.name.
3. Create a class Simple_calculator and implement Add & Subtract operation using member functions. Both functions should accept two arguments and return the result.
4. Create a class Adv_calculator which extends the Simple_calculator and contain three member function multi(), modulo() & division() besides the parent class methods. Call all 5 functions using object of Adv_calculaor.
5. Write a PHP Script to print a list of classes the script has access of. 6. Write PHP Script to check whether a method exists or not.
| Working with Directories | |||
| Working with Directories | |||
| PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and list the contents of a directory. | |||
| Creating Directories in PHP | |||
| A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as yourPHP script, simply provide the directory name. To create directory in a different directory specify the full path when calling mkdir(). | |||
| A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable): | |||
| <?php$result = mkdir (“test”, “0777”)or die (“Failed to create Directory”);
if($result) echo “directory created successfully”; ?> |
|||
| Deleting a Directory | |||
| Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted. | |||
| Finding and Changing the CWD (current working directory) | |||
| Do you expect a web application to be able to perform all of its file related tasks in a single directory? The answer is NO, it is possible but it will create a mess. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP stript. | |||
| The current working directory can be identified using the getCwd() function: | |||
| <html><head><title>PHP Tutorial- Working with Directories</title>
</head> <body> <?php $cwd=getCwd(); echo “Current Working Directory is <b>”.$cwd.”</b>”; ?> </body> </html> |
|||
| save the above script as getCWdir.php and open the page in browser. If your script is fine then you should get the output given below: | |||
| The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory: | |||
| <html><head><title>PHP Tutorial- Working with Directories</title>
</head> <body> <?php $cwd=getCwd(); echo “Current Working Directory is <b>”.$cwd.”</b>”; chdir (“/e_drive”); $cwd=getCwd(); echo “After Changing the Directory, Current Working Directory is <b>”.$cwd.”</b>”; ?> </body> </html> |
|||
| Save the file as chdir.php and open the open the PHP script in browser to view the output: | |||
| Listing Files in a Directory | |||
| The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically. | |||
| If the argument is omitted or set to 0 the list is sorted alphabetically: | |||
| <html><head><title>PHP Tutorial- Working with Directories</title> </head> <body> <?php $cwd=getCwd(); echo “Current Working Directory is <b>”.$cwd.”</b>”; chdir (“/var”); $cwd=getCwd(); echo “<br/>After Changing the Directory, $array = scandir(“.”, 1); print_r($array); ?> </body> |
|||
| Save the file and open the page in browser to view the output. | |||
| Output:Try it your self. | |||
|
|
|||
Creating, Copying, moving and Deleting
File Writing data to a File The fwrite() function outputs the contents of a string variable to the specified resource. fwrite syntax: int fwrite(resource handle, string string [, int length]) If the optional length parameter is provided, fwrite() will stop writing when length characters have been written. Otherwise, writing will stop when the end of the string is found. Consider this example:
<?php
// Data we’d like to write to the info.txt file
$data = “Sanjay Sing|sanjay.kumar@ebizelindia.com”;
// Open info.txt for writing
$my_file = fopen(“/home/www/data/info.txt”, “at”);
// Write the data
fwrite($my_file, $data);
// Close the handle
fclose($my_file);
?<
Output: Try it yourself Moving, Copying and Deleting Files with PHP Files can be copied using the copy() function, renamed using the rename() function and deleted using the unlink() function. Copying and Deleting Files To copy a file, the copy() function is used. bool copy(string source_file,string destination_file) The copy() function will return true if the file was correctly copied, or false if there was an error.
<?php
class File_Options{
private $file1;
private $file2;
Private $msg;
function __construct(){
$this-<msg=NULL;
}
public function doCopy($file, $copyto){
if (!(copy($file,$copyto))) {
return $msg;
}
else {
return “<b<File $file successfully copied to $copyto</b<“;
}
}
public function doDel($file){
}
public function doRen($oldName,$newName){
}
}
?<
<HTML<
<HEAD<
<TITLE< PHP Tutorial: Working with Files </TITLE<
<META NAME=”Generator” CONTENT=”jNote-iT”<
</HEAD<
<BODY<
<?php
$file_opt=new File_Options();
$msg=$file_opt-<doCopy(“test.txt”,”test1.txt”);
if (!$msg){
echo “<b<Unable to Copy File to the specified location</b<“;
}
else
echo $msg;
?<
</BODY<
</HTML<
Assuming that you have a file named test.txt, a successful run of this script should copy the file test1.txt from its current location to your specified location. The rename() function is very similar in context to the copy() function: Syntax:
bool rename(string old_file,string new_file) Considering the name of the functions so far, it may come as a surprise that the function to delete is called unlink(): Syntax:
bool unlink(string filename) Both the rename() and unlink() functions return true upon successful completion, or false if the operation did not complete successfully. Assignment:
1. In the above script, there are two dummy functions, implement delete and rename operations using the function.
2. In the above function, use validation so that the file user is trying to operate is operated only if it exists.
3. Write a PHP script to display contents of a file to user.
Creating Simple HTML form HTML Forms What makes the Web so interesting and useful is its ability to disseminate information as well as collect it, primarily through an HTML-based form. These forms are used to encourage site feedback, facilitate forum conversations, collect mailing addresses for online orders, and much more. But coding the HTML form is only part of what’s required to effectively accept user input; a server-side component must be ready to process the input. Note: This is an simplified example to educate you how to use PHP to process HTML form information. This chapter does not describe forms in details or in simple words this isn’t a HTML form tutorial. In this chapter we will just tell you that how to obtain and process the information that your site user has entered in the form. For HTML tutorial, please visit out XHTML/HTML tutorial at http://education.ebizelindia.com. Creating a Simple HTML Form In this example, we will create a simple form, which will accept user input and when user click on submit button sends the information to the server side PHP script to process the information. This example is divided in two parts: 1. Client side HTML form [simpleform.php]
2. Server side form processing script [simpleform.php] Source code simpleform.php
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″ />
<title>PHP Tutorial: Working with Forms</title>
</head>
<body><form name=”simple” action=”simpleform.php” method=”get”>
<table width=”200″ border=”1″ cellpadding=”1″>
<tr>
<th scope=”row”>Name</th>
<td><input name=”name” type=”text” id=”name” accesskey=”n” /></td>
</tr>
<tr>
<th valign=”top” scope=”row”>Address</th>
<td><textarea name=”address” cols=”40″
rows=”5″ id=”address” style=”background-color:#34FFDD”></textarea></td>
</tr>
<tr>
<th scope=”row”>
<input type=”reset” name=”Reset” value=”Reset”
style=”background-color:#0066CC; border:
thin dotted solid #003333; cursor:wait; size:16; color:#FFFFFF” /></th>
<td><input name=”Submit” type=”submit” id=”Submit”
style=”background-color:#0066CC; border: thin dotted solid #003333;
cursor:hand; width:150px; size:16; color:#FFFFFF” value=”Submit” /></td>
</tr>
</table></form>
</body>
</html>
The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the “simpleform.php” file. The above page should look like the figure given below:
The server side script: source of simpleform.php
<html >
<head>
<title>Hello <?php echo $_GET[“name”];?></title>
</head>
<body>
<hr />
<center><h3>Hello User </h3></center>
You have entered the following information:
<p>Your Name <b><?php echo $_GET[“name”];?></b>
<br />
Your Address <address><?php echo $_GET[“address”];?></address>
</p>
</body>
</html>
Now open the simpleform.php in browser, fill the form and press submit the form to view the output. Your output should be like one given below:
As you can see, we have used the following syntax to retrieve the value that we have entered in the from. There are two common methods for passing data from one script to another: 1. GET and 2. POST. Syntax to access value of a form field: if the method is GET: $_GET[“form_field_name”];
if the method is POST $_POST
[“form_field_name”]; In the above example GET method is used to make the example verbose. You can use any method as per your choice and requirement. But, GET method is not recommended for that contains sensitive information such as Login form, form that accepts credit card information, etc and form that accepts lengthy data. Although GET is the default, you’ll typically want to use POST because it’s capable of handling considerably more data, an important behavior when you’re using forms to insert and modify large blocks of text. If you use POST, any posted data sent to a PHPscript must be referenced using the $_POST syntax. For example, suppose the form contains a text-field value named email that looks like this: <input type=”text” id=”email” name=”email” size=”20″ maxlength=”40″ /> Once this form is submitted, you can reference that text-field value like so: $_POST[’email’] Of course, for sake of convenience, you can first assign this value to another variable, like so: $email = $_POST[’email’]; But following the best practice of never presuming user input will be safe, you should filter it through one of the several functions capable of sanitizing data, such as htmlentities(), like so: $email = htmlentities($_POST[’email’]); The htmlentities() function converts strings consisting of characters capable of maliciously modifying an HTML page should the user-submitted data be later published to a Web site, such as a Web forum.
More Complex Form In this example we will create a self submitting form, which accept user input process the information and display the output, and all in one page. Step-by-Step description:
<body>
<?php
$name=$_POST[“name”];
$email=$_POST[“email”];
$mobile=$_POST[“mobile”];
$addr=$_POST[“address”];
$own=$_POST[“own”];
$state=$_POST[“state”];
$sex=$_POST[“sex”];
$feedback=$_POST[“feedback”];
$owns=array();
if (!isset($_POST[‘submit’])) { //if the form is not submitted we will display the form itself. Otherwise display the contents of the form. ?> In the section we have declared variables to store the values of form fields. In the last line of the above declaration we have used isset() function to check if the form has been submitted. If user has submitted the form, then it will jump directly to else part. The else part
<?php
}
else
{
?>
<h3> Dear <?php echo $name;?>, thank
you very much for your valuable Feedback</h3>
<hr />
You have entered following information :<br />
<?php
echo “<pre>”;
echo “Name <b>”.$name.”</b><br />”;
echo “Contact No”.$mobile.”<br />”;?>
“EMail Address ” <a href=”mailto:
<?php echo $email;?>”> <?php echo $email;?></a>
Your Have <b><?php foreach ($own as $x=>$val){
#if (!$x==”none”)
echo “<br>”.$val;
}
?>
</b>
<?php echo “Your address is “.$address .” “.$state;
echo “<br /> And You are a $sex “;
?>
<b>eBIZ Education thanks you for
your valuable suggestion and feedback. </b>
<?php
}
?>
In the else part we are just printing the value entered by user. As you can see above, this part will only execute if the has submitted the form. The complete Code… Click here to view the code [Link the feedback.php.txt]
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type”
content=”text/html; charset=windows-1252″ />
<title>EBIZ EDUCATION FEEDBACK</title>
<style type=”text/css”>
<!–
body {
background-color: #0099CC;
margin-left: 0px;
margin-top: 0px;
}
–>
.red{
color:#FF0000;
font-style:italic;
}
.fields
{
background-color:#34FFDD;
color:#333366
}
.feedback{
background-color:#006699;
color:#FFFFFF;
font-weight:bold;
}
</style>
</head>
<body>
<?php
$name=$_POST[“name”];
$email=$_POST[“email”];
$mobile=$_POST[“mobile”];
$addr=$_POST[“address”];
$own=$_POST[“own”];
$state=$_POST[“state”];
$sex=$_POST[“sex”];
$feedback=$_POST[“feedback”];
$owns=array();
if (!isset($_POST[‘submit’])) {
?>
<hr />
<h3> Welcome to eBIZ Education Feedback Page </h3>
<hr />
<span><b>* </b> fields are mandatory </span>
<form action=”<?php echo $PHP_SELF;?>” method=”POST”
enctype=”application/x-www-form-urlencoded”
name=”feedback” target=”_self” dir=”ltr” lang=”en”>
<table width=”70%” border=”0″ cellspacing=”0″ cellpadding=”1″>
<tr>
<td width=”30%”>Name</td>
<td width=”70%” colspan=”2″>
<input name=”name” type=”text” size=”30″ />
<span><b>* </b></span></td>
</tr>
<tr>
<td valign=”top”>email ID </td>
<td colspan=”2″><input name=”email”
type=”text” size=”35″ maxlength=”100″ />
<span><b>* </b></span></td>
</tr>
<tr>
<td valign=”top”>Mobile no </td>
<td colspan=”2″><input name=”mobile” type=”text”
class=”fields” size=”25″ maxlength=”13″ /></td>
</tr>
<tr>
<td valign=”top”>Address </td>
<td colspan=”2″><textarea name=”address”
cols=”40″ rows=”5″ class=”fields”></textarea></td>
</tr>
<tr>
<td valign=”top”>State</td>
<td colspan=”2″><select name=”state” >
<option>Please Select State</option>
<option value=”A.P.”>A.P.</option>
<option value=”A.S.”>A.S.</option>
<option value=”B.R.”>B.R.</option>
<option value=”C.G.”>C.G.</option>
<option value=”U.P.”>U.P.</option>
<option value=”D.L.”>Delhi</option>
<option value=”Other”>Other</option>
</select></td>
</tr>
<tr>
<td>Gender </td>
<td><label>
<input name=”sex” type=”radio” value=”Male” accesskey=”M” />
Male</label></td>
<td><label>
<input name=”sex” type=”radio” value=”Female” accesskey=”F” />
Female</label></td>
</tr>
<tr>
<td>Which of Following do you own ?</td>
<td colspan=”2″><table width=”100%” border=”0″
cellspacing=”0″ cellpadding=”1″>
<tr>
<td><input type=”checkbox” name=”own[]” value=”car”/>Car</td>
<td><input type=”checkbox” name=”own[]”
value=”computer”/>Computer </td>
</tr>
<tr>
<td><input type=”checkbox” name=”own[]” value=”mobile”/>Mobile</td>
<td><input type=”checkbox” name=”own[]” value=”none”/>None</td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td colspan=”2″> </td>
</tr>
<tr>
<td valign=”top”>Feedback
<span><b>* </b></span></td>
<td colspan=”2″ valign=”top”>
<textarea name=”feedback” cols=”45″ rows=”10″ class=”feedback”>
</textarea></td>
</tr>
<tr>
<td><input name=”reset” type=”reset”
value=”Clear Form” /></td>
<td colspan=”2″><input name=”submit”
type=”submit” value=”Submit Form” /></td>
</tr>
</table>
</form>
<?php
}
else
{
?>
<h3> Dear <?php echo $name;?>, thank you
very much for your valuable Feedback</h3>
<hr />
You have entered following information :<br />
<?php
echo “<pre>”;
echo “Name <b>”.$name.”</b><br />”;
echo “Contact No”.$mobile.”<br />”;?>
“EMail Address ” <a href=”mailto:<?php echo $email;?>”>
<?php echo $email;?></a>
Your Have <b><?php foreach ($own as $x=>$val){
#if (!$x==”none”)
echo “<br>”.$val;
}
?>
</b>
<?php echo “Your address is “.$addr .” “.$state;
echo “<br /> And You are a $sex “;
?>
<b>eBIZ Education thanks you for
your valuable suggestion and feedback. </b>
<?php
}
?>
<br />
<hr />
</body>
</html>
save the file as feedback.php and open the script to view the output. The page should look like the one given below:
When User Fills the form and submit it, user will get the following screen. Click here to view the Form.
Introduction What is Database? A database is a structured collection of records or data that is stored in a computer system. The structure is achieved by organizing the data according to a database model. The model in most common use today is the relational model. Other models such as the hierarchical A database is an organized collection of data that is useful to us. The data inside in a database can be modified, deleted or new data can be added. They are stored in the form of records as shown in the table below: The above table shows a single record. The columns-Associate_TID, Associate_name, Age ,Commission are the fields or attributes, while the row containing the corresponding the values-900678432, Smith, 28, 25000 is a single record. There can be a number of records in a table and number of tables in a database. The tables in a database are related to each other through one/more attributes/fields. A Database is diagrammatically shown below. It consists of two tables-Associate andAsso_INFO. While Associate stores information regarding an Associate TID, dept and salary, the table Associate_INFO stores TID, name and date of join of the Associate. The common link between the tables is established by the field Asociate-TID. Why use MySQL? If you’re looking for a free or inexpensive database management system, several are available from which to choose: MySQL, PostgreSQL, one of the free-but-unsupported engines from commercial vendors, and so forth. When you compare MySQL with other database systems, think about what’s most important to you: Performance, support, features (SQL conformance, extensions, and so forth), licensing conditions and restrictions, and price all are factors to take into account. Given these considerations, MySQL has many attractive features to offer: • Speed:
MySQL is fast. The developers contend that MySQL is about the fastest database you can get.
• Ease of use:
MySQL is a high-performance but relatively simple database system and is much less complex to set up and administer than larger systems.
• Query language support.
MySQL understands SQL, the language of choice for all modern database systems.
• Capability
Many clients can connect to the server at the same time. Clients can use multiple databases simultaneously. You can access MySQL interactively using several interfaces that let you enter queries and view the results:
command-line clients, Web browsers, or X Window System clients. In addition, a variety of programming interfaces are available for languages such as C, Perl, Java, PHP, and Python.
• Connectivity and security:
MySQL is fully networked, and databases can be accessed from anywhere on the Internet, so you can share your data with anyone, anywhere.
• Portability:
MySQL runs on many varieties of UNIX, as well as on other non-UNIX systems, such as Windows and OS/2. MySQL runs on hardware from home PCs to high-end servers.
• Small size:
MySQL has a modest distribution size, especially compared to the huge disk space footprint of certain commercial database systems.
• Availability and cost MySQL is an Open Source project, freely available under the terms of the GNU General Public License (GPL). This means that MySQL is free for most in-house uses. (If you want to sell MySQL or services that require it, that is a different situation and you should contact MySQL AB.)
• Open distribution:
MySQL is easy to obtain; just use your Web browser. If you don’t understand how something works or are curious about an algorithm, you can get the source code and poke around in it. If you don’t like how something works, you can change it. If you think you’ve found a bug, report it; the developers listen.
• MySQL is a relational database management system:
A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility.
The SQL part of “MySQL” stands for “Structured Query Language. SQL is the most common standardized language used to access databases and is defined by theANSI/ISO SQL Standard. The SQL standard has been evolving since 1986 and several versions exist.
Creating a Connection Before you can access and work with data in a database, you must create a connection to the database. In PHP, mysql_connect() function is used to connect to database . Syntax ofmysql_connect: $con=mysql_connect(“localhost/ip”, “user_name”, “password”); MySQL localhost If you’ve been around the internet a while, you’ll know that IP addresses are used as identifiers for computers and web servers. In this example of a connection script, we assume that the MySQL service is running on the same machine as the script. When the PHP script and MySQL are on the same machine, you can use localhost as the address you wish to connect to. localhost is a shortcut to just have the machine connect to itself. If your MySQL service is running at a separate location you will need to insert the IP address or URL in place of localhost. Please contact your web host for more details if localhost does not work. Example: Source code of mysql_connect.php
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE>PHP Tutorial: Working with MySQL</TITLE>
</HEAD>
<BODY>
<hr>
<?php
$con=mysql_connect(“localhost”,”root”,””) ;
if(!$con)
die (“<b>Unable to Connect to MySQL “.mysql_error().”</b>”);
else
echo “<b>Connection Created Successfully.</b>”;
mysql_close($con)or die(mysql_error());
?>
<hr>
</BODY>
</HTML>
The above example attempts to connect to MySQL database. If connection is established then print the success message like the one below Otherwise displays the mysql error.
| Retrieving Database and Table list | |||
| Now that you’ve successfully used PHP to make a connection to MySQL, it’s time to familiarize yourself with some of the built-in MySQL-related functions. In this section, you use the following functions: | |||
| • mysql_list_dbs()— Used to list the databases on a MySQL server.Syntax: resource mysql_list_dbs ( [resource link_identifier ] ) | |||
| mysql_list_dbs() will return a result pointer containing the databases available from the current mysql daemon. | |||
| • mysql_num_rows()— Returns the number of rows in a result set. | |||
| Syntax: int mysql_num_rows ( resource result ) mysql_num_rows() returns the number of rows in a result set. |
|||
| • mysql_tablename()— Despite its name, can extract the name of a table or a database from a result. | |||
| Syntax: string mysql_tablename ( resource result, int i ) |
|||
| Getting database list | |||
| <?php//PHP Code to retrieve the list of databases in MySQL.
class dbUtils{ private $list_db; private $total_db; private $list_of_dbs; public function __construct(){ } public function connect(){ $con=mysql_connect(“localhost”,”root”,””); if(!$con) return NULL; else return $con; } public function listDB() { $con=$this->connect(); if(!$con) $this->list_db=”<b>Unable t else { #echo “<b>Connection Created Successfully.</b>”; $total_db=mysql_list_dbs($con)or die(mysql_error()); $i=0; $list_of_dbs=”<ul type=\”disc\”>”; if($total_db) { for($i;$i<mysql_num_rows($total_db);$i++) { $db_list[$i]=mysql_tablename($total_db,$i); $list_of_dbs.=”<li>$db_list[$i]</li>”; } } $list_of_dbs.=”</ul>”; mysql_close($con)or die(mysql_error()); return $list_of_dbs; } } } ?> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”> <?php $dbutil=new dbUtils(); ?> <HTML> <HEAD> <TITLE>PHP Tutorial: Working with MySQL</TITLE> </HEAD> <BODY> <hr> <h3>List of Databases on localhost</h3> <hr> <FIELDSET> <LEGEND>Databases</LEGEND> <?php echo $dbutil->listDB(); ?> </FIELDSET> </BODY> </HTML> |
|||
| Description: After connecting to database we have created a variable to hold the result of the mysql_list_dbs() function. |
|||
| $total_db=mysql_list_dbs($con)or die(mysql_error()); | |||
| After declaring all necessary variables begin a for loop. This loop will continue for as long as the value of $i is less than the number of rows in the $total_db result value: | |||
| for($i;$i<mysql_num_rows($total_db);$i++) { | |||
| Once you’re within the for loop, get the name of the database reflected in the current row of the result: | |||
| $db_list[$i]=mysql_tablename($total_db,$i); $list_of_dbs.=”<li>$db_list[$i]</li>”; |
|||
| Close the for loop, the bulleted list, and your PHP block: | |||
| }$db_list .= “</ul>”;
?> |
|||
| Save the above script and open the page in browser to view the output. | |||
| Output: | |||
| Output may vary from system to system depending upon how much you have played with your MySQL server, but it should look like the one below: | |||
| Getting Table list | |||
| To retrieve the list of tables we have just added 1 more for loop inside the main for loop. This for loop retrieve list of tables of each database and add it to the list. | |||
| <?php//PHP Code to retrieve the list of databases in MySQL.
$con=mysql_connect(“localhost”,”root”,””) ; $list_db; if(!$con) die (“<b>Unable to Connect to MySQL “.mysql_error().”</b>”); else { #echo “<b>Connection Created Successfully.</b>”; $total_db=mysql_list_dbs($con)or die(mysql_error()); $i=0; $list_of_dbs=”<ul type=\”disc\”>”; if($total_db) { //Main loop to retireve the l for($i;$i<mysql_num_rows($total_db);$i++) { $db_list[$i]=mysql_tablename($total_db,$i); $list_of_dbs.=”<li>$db_list[$i]”; $tables=mysql_list_tables($db_list[$i]); $list_of_tables=”<ul>”; $i1=0; if($tables) { //For Loop to retireve list of tables in current database for ($i1;$i1<mysql_num_rows($tables);$i1++) { $table_list[$i1]=mysql_tablename($tables,$i1); $list_of_tables.=”<li>$table_list[$i1]</li>”; } $list_of_tables.=”</ul>”; $list_of_dbs.=”$list_of_tables </li>”; } } } $list_of_dbs.=”</ul>”; mysql_close($con)or die(mysql_error()); } ?> <!DOCTYPE HTML PUBLIC <HTML> <HEAD> <TITLE>PHP Tutorial: Working with MySQL</TITLE> </HEAD> <BODY> <hr> <h3>List of Databases on localhost</h3> <hr> <FIELDSET> <LEGEND>Databases</LEGEND> <?php echo $list_of_dbs; ?> </FIELDSET> </BODY> </HTML> |
|||
| Output: Try it yourself | |||
|
|
|||
Creating Databases and Tables Creating Databases PHP Script to create database
<?php
class dbUtils{
private $flag;
private $sql;//=”create database “;
private $msg;//=””;*/
#function createDB
public function __construct(){
$this->flag=0;
$this->sql=””;
$this->msg=””;
}
public function connect(){
$con=@mysql_connect(“localhost”,”root”,””);
if(!$con)
return NULL;
else
return $con;
}
function createDB($db_to_create)
{
$msg=””;
$flag=$this->flag;
if((!$db_to_create)|| ($db_to_create==””))
$flag=-1;
if(isset($_POST[“submit”])&& ($flag >=0)){
$sql=”create database “.$db_to_create;
$con=$this->connect();
if($con){
$result=mysql_query($sql,$con);
if($result)
{
$msg.=”Database <b>$db_to_create</b> create successfully.”;
$flag=0;
//return $msg;
}
elseif(!$result)
{
$msg.=”Unable to create database $db_to_create “;
$msg.=mysql_error();
$flag=-1;
//return $msg;
}
if($flag<0)
$msg.=”\n<br>Unable to create database <b>
$db_to_create</b>\n<br /> Please Enter a
valid database name to create”;
mysql_close($con);
//echo $msg;
return $msg;
} else{
$msg=”Unable to connect to database”;
return $msg;
}
}
}
}
?>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script>
function validateForm()
{
var db=document.form1.db_name
if((db.value==””)||(db.value.length==0))
{
alert(“Please enter Name of the database to create”)
db.focus()
return false
}
return true
}
</script>
<meta http-equiv=”Content-Type”
content=”text/html; charset=iso-8859-1″ />
<title>PHP Tutorial: Working with MySQL</title>
</head>
<body>
<form action=”<?php echo $PHP_SELF;?>
” method=”post” name=”form1″ onSubmit=”return validateForm();”>
Enter database name to create
<input type=”text” name=”db_name” maxlength=”10″ size=”20″>
<br>
<input name=”submit”
type=”submit” value=”Create Database”>
</form>
<hr>
<?php
if(isset($_POST[“submit”]))
{
?>
<div style=”border:thin #FF0000
solid; width:80%; height:auto”>
<?php
$db=$_POST[“db_name”];
$dbutil=new dbUtils();
echo $dbutil->createDB($db);
echo “</div>”;
}
?>
</body>
</html>
How the above example works? 1. Create a variable and store the database name user has entered in the form.
$db_to_create=$_POST[“db_name”];
2. Create an object of dbUtils class
$dbutil=new dbUtils();
3. Call the createDB function of dbUtils class and pass
$db_to_create $dbutil->createDB($db_to_create);
4. in the createDB function of dbUtils class, check if the database name is blank.
5. Create a variable to hold the query to issue, which will create the new database:
$sql = “CREATE database “.$db_to_create;
6. Add the connection information just as you have been doing:
$con = $this->connect();
7. Check connection is established with database or not
if($con){
7. Issue the query, using the mysql_query() function.
$result = mysqlquery($sql, $con);
8. Check if result is initialized and return the result.
if($result){
Note:
The concept of $PHP_SELF variable and isset() function
has been described in the previous chapter. Output: Click here to view the source code. Creating Tables In this example we are going to use a web based interface to create tables. The interface gives you a list of available databases, a Text field to enter name of table and a Text area to enter table structure in SQL format. Our interface will look like the one below: This example is a multi file PHP script and it is divided in to parts: 1. dblist.php [Click here to view the complete source code] PHP script to retrieve list of database and print it in desired format
<?php
$list_of_dbs=””;
function getDBList($element_type, $param1)
{
$con=mysql_connect(“localhost”,”root”,””) or die(“Unable to Connect”);
$total_db=mysql_list_dbs($con)or die(mysql_error());
$i=0;
if($total_db)
{
//Main loop to retireve the list of databases on the MySQL server
for($i;$i<mysql_num_rows($total_db);$i++)
{
$db_list[$i]= mysql_tablename($total_db,$i);
$list_of_dbs.=”<$element_type $param1=\”$db_list[$i]\”
>$db_list[$i]</$element>”;
}
}
mysql_close($con) or die(mysql_error());
return $list_of_dbs;
}
?>
2. create_table.php [Click here to view the complete source code] Main PHP script, this one is similar to previous example, except that we are issuing a Create Table command, instead of Create Database command.
<?php
require(“listdb.php”);
$db=$_POST[“db_name”];
$command=$_POST[“table_command”];
$table_name=$_POST[“tbl_name”];
$con=mysql_connect(“localhost”,”root”,””) or die();
$flag=0;
$sql=”create table “;
$msg=””;
if((!$db)|| ($db==””)||(strlen($command)
<=5)||($command==””)||(strlen
($table_name)<=0)||($table_name==””))
$flag=-1;
if(isset($_POST[“submit”])&& ($flag >=0)){
$sql.=$table_name;
$sql.=$command;
if($con)
{
mysql_select_db($db, $con);
#echo $sql;
$result=mysql_query($sql,$con);
if($result)
{
$msg.=”Table <b>$table_name</b
> create successfully.”;
$flag=0;
}
elseif(!$result)
{
$msg.=”Unable to create table $table_name “;
$msg.=mysql_error();
$flag=-1;
}
if($flag<0)
$msg.=”\n<br>Unable to create table <b>
$table_name</b>\n<br />
Please Enter a valid database name to create”;
mysql_close($con);
}
}
?>
In the Table name field enter test_tbl field and enter the following SQL command in the Command Text area
(
Id int not null auto_increment primary key,
name varchar(50),
address varchar(50),
email varchar(100)
)
Output: Try it yourself. Note: in the coming subsections of this chapter this table (test_tbl) will be used for reference, so make sure you have created the above table.
Using MySQL DML command When data is put into a MySQL table it is referred to as inserting data. When inserting data it is important to remember the exact names and types of the table’s columns. If you try to place a 500 word essay into a column that only accepts integers of size three, you will end up with a nasty error! Note: As stated in the previous sub-section, we are going to use the table created in the previous sub-section for examples coming in this chapter. Inserting records Now that you have created your table, let’s put some data into that table! Here is thePHP/MySQL code for inserting data into the table we created in the previous lesson [since we have the interface ready we can create the table anytime and I assume that you’ve already created one].
<?php
class dbUtils{
private $flag;
private $sql;//=”create database “;
private $msg;//=””;*/
#function createDB
public function __construct(){
$this->flag=0;
$this->sql=””;
$this->msg=””;
}
public function connect(){
$con=@mysql_connect(“localhost”,”root”,””);
if(!$con)
return NULL;
else
return $con;
}
public function createDB($db_to_create){
}
public function createTable($db_to_use,$tbl_name,$command){
}
public function insert_record($db_to_use, $command){
$con;
$msg1=”Result=”;
#echo $db_to_use.$command;
if(!$db_to_use||!$command) {
return “Either Database name of Command is empty”;
}
else{
$con=$this->connect();
if($con){
mysql_select_db($db_to_use);
$result=mysql_query($command,$con) or die(mysql_error());
if(!$result)
return “<b> Unable to insert records i
n the specified table”.mysql_error().”</b>”;
else
return “<b>Record(s) updated successfully</b>”;
}
else
{
return ” Unable to connect to DB”;
}
}
}
public function update_record($db_to_use, $commnad){
}
public function delete_record($db_to_use, $commnad){
}
}
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorial : Workign with MySQL[Insert Record] </TITLE>
</HEAD>
<BODY>
<TABLE border=”1″ style=”border: 1px solid blue;”>
<form name=”insert” action=”<?php $PHP_SELF;?>” method=”post”>
<TR>
<TD>Enter Database to Use</td>
<TD><INPUT TYPE=”text” NAME=”db_name” size=”20″ maxlength=”20″></td>
</tR>
<TR>
<TD>Enter Table Name</td>
<TD><INPUT TYPE=”” NAME=”tbl” size=”30″ maxlength=”30″></td>
</tR>
<TR>
<TD>Enter Name</td>
<TD><INPUT TYPE=”text” NAME=”name” size=”30″ maxlength=”30″></td>
</tR>
<TR>
<TD>Enter Address</td>
<TD><textarea cols=”20″ rows=”4″ name=”address”></textarea></td>
</tR>
<TR>
<TD>Enter Email Address</td>
<TD><INPUT TYPE=”text” NAME=”email” size=”50″ maxlength=”90″></td>
</tR>
<TR>
<TD><INPUT TYPE=”Submit” NAME=”submit” value=”Insert Record”></td>
<TD><INPUT TYPE=”Reset” NAME=”Reset” value=”Reset”></td>
</tR>
</form>
</TABLE>
<?php
if(isset($_POST[“submit”])){
?>
<div style=”border:thin #FF0000 solid; width:80%; height:auto”>
<?php
$db=$_POST[“db_name”];
$tbl=trim($_POST[“tbl”]);
$name=$_POST[“name”];
$addr=$_POST[“address”];
$email=$_POST[“email”];
if($db&&$tbl) {
$sql=”insert into “.$tbl.” values
(‘null’,'”.$name.”‘,'”.$addr.”‘,'”.$email.”‘);”;
$dbutil=new dbUtils();
$msg2=$dbutil->insert_record($db,$sql);
if($msg2)
echo $msg2;
else
echo “Unable to insert record i
nto $tbl an error has occured “.$msg2;
}
else{
echo “Please enter Valid Database and/or table name to process”;
}
?>
</div>
<?php
}
?>
</BODY>
</HTML>
About Script should produce the following HTML form After you fill data in the form and click on Insert record button it should display the following output Explanation of the above script: 1. In the above script, at first we check if the form has been submitted
<?php
if(isset($_POST[“submit”])){
?>
2. If the form has been submitted then we retrieve the form field values and construct the query
$db=$_POST[“db_name”]; //Retrieve the database name
$tbl=trim($_POST[“tbl”]);// retrieve table name from form
$name=$_POST[“name”];//Retrieve the Name from form
$addr=$_POST[“address”];//Retrieve the Address from form
$email=$_POST[“email”];//Retrieve the email id from form
if($db&&$tbl){
$sql=”insert into “.$tbl.” values (‘null’,'”.$name.”‘,'”.$addr.”‘,'”.$email.”‘);”;
3. Now, we create an object of dbUtils class $dbutil=new dbUtils(); 4. Call the insert_record function of dbUtils class $msg2=$dbutil->insert_record($db,$sql); 5. In the insert_record function change the database to use user specified database and execute the query to insert the record into the database table, besides other required rituals
mysql_select_db($db_to_use);
$result=mysql_query($command,$con) or die(mysql_error());
if(!$result)
return “<b> Unable to insert records i
n the specified table”.mysql_error().”</b>”;
else
return “<b>Record(s) updated successfully</b>”;
Updating Records Following PHP script update the name of the user whose id is 2:
<html>
<head>
<title>PHP Tutorial :Working with MySQL</title>
</head><body>
<?php
$command=”update test_tbl set name=’Neeraj Bhardwaj’ where id=2;”;
$con=mysql_connect(“localhost”,”root”,””) or die();
mysql_select_db(“test”, $con) or die(mysql_error());
#echo $sql;
$result=mysql_query($command,$con)or die (mysql_error());
if($result)
{
echo “Record Updated Successfully <br>.”;
}
?>
</body>
</html>
This example is like the previous example, except that we are updating the record(s), and we’ve used update command instead of insert command. Deleting Records
<html>
<head>
<title>PHP Tutorial :Working with MySQL</title>
</head><body>
<?php
$command=”delete from test_tbl where id=2;”;
$con=mysql_connect(“localhost”,”root”,””) or die();
mysql_select_db(“test”, $con) or die(mysql_error());
#echo $sql;
$result=mysql_query($command,$con)or die (mysql_error());
if($result)
{
echo “Record Deleted Successfully <br>.”;
}
?>
</body>
</html>
Above PHP script delete a record from table test_tbl whose id is 2. All three examples above are same except the SQL command used. As you can see it is quite easy to play with MySQL using PHP. Of course, you can use HTML forms to perform these operations. By doing so you can perform SQL operations dynamically.
| Error Handling | |||
| Error handling in PHP is a fairly straightforward process. PHP will simply send to the browser (or standard output if executing a script from the command line).* an error message containing relative information to the error such as the filename of the script, the specific line in the file that caused the error, * a (sometimes) helpful message describing the nature of the error The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser |
|||
| Database functions can fail. There are several possible classes of failure, ranging from critical-the DBMS is inaccessible or a fixed parameter is incorrect to recoverable, such as a password being entered incorrectly by the user. | |||
| The PHP interface functions to MySQL support two error-handling functions for detecting and reporting errors: | |||
| int mysql_errno(resource connection)Returns the error number of the last error on the connection resource string
mysql_error(resource connection) Returns a descriptive string of the last error on the connection resource |
|||
| Example below shows a script illustrated with additional error handling. We have deliberately included an error where the name of the database test is misspelled as “test_tbl”. | |||
| The error handler is a function, showError( ), that-with the database name error-prints a phrase in the format: | |||
| Error 1049 : Unknown database ‘test_tbl’ | |||
| The error message shows both the numeric output of mysql_errorno( ) and the string output of mysql_error( ). The die( ) function outputs the message and then gracefully ends the script. | |||
| Warning: The functions mysql_query( ) and mysql_unbuffered_query( ) return false only on failure; that is, when a query is incorrectly formed and can’t be executed. | |||
| A query that executes but returns no results still returns a result resource handle. However, a successive call to mysql_num_rows( ) reports no rows in the result set. | |||
| The mysql_connect( ) and mysql_pconnect( ) functions don’t set either the error number or error string on failure and so must be handled manually. This routine handling can be implemented with a die( ) function call and an suitable text message, as in Example below. | |||
| Example Querying a database with error handling | |||
| <html><head>
<title>PHP Tutorial: Working With MySQL</title> </head> <body><pre> <?php function showError( ) { die(“Error ” . mysql_errno( ) . ” : ” . mysql_error( )); } // (1) Open a connection to the database if (!($connection = @ mysql_connect(“localhost”, “roor”,””))) die(“Could not connect”); // NOTE : ‘test’ is deliberately misspelt to // cause an error if (!(mysql_select_db(“test”, $connection))) showError( ); // (2) Execute a query on the test through the connection if (!($result = @ mysql_query (“SELECT * FROM test_tbl”, $connection))) showError( ); // (3) While there are still rows in the result set, // fetch the current row into the array $row while ($row = mysql_fetch_row($result)) { // (4) Print out each element in $row, that is, // print the values of the attributes for ($i=0; $i<mysql_num_fields($result); $i++) echo $row[$i] . ” “; // Print a carriage return to neaten the output echo “\n”; } // (5) Close the database connection if (!mysql_close($connection)) showError( ); ?> </pre> </body> </html> |
|||
| The MySQL error-handling functions should be used with the @ operator that suppresses default output of error messages by the PHP script engine. Omitting the @ operator produces messages that contain both the custom error message and the default error message produced by PHP. Consider an example where the string localhost is misspelled, and the @ operator is omitted: | |||
| if (!($connection = mysql_connect(“localhos”, “root”,:””) )) die(“Could not connect”);Warning: MySQL Connection Failed:
Unknown MySQL Server Host ‘localhos’ (0) in error-handling.php on line 42 Could not connect |
|||
| TIPS: Don’t forget to add an @ operator as the prefix to any function call that is handled manually with a custom error handler. The @ operator prevents PHP from issuing its own internal error message. | |||
| Assignment: | |||
| 1. In the sub-section MySQL DML command of this chapter, there are two dummy functions [update_record, delete_record] to implement update and delete operations respectively. Implement SQL Update and delete commands using the functions. | |||
| 2. Write a PHP function to return list of databases as a drop-down list, i.e. | |||
| 3. Write a PHP script to generate the following output: | |||
| in the above script, there is a drop down list that contain name of all databases in MySQL. | |||
| This Example work like this, when user select database name from drop-down list, enter desired table name in the text box and press Show Records button it should display the record in show format. | |||
| 4. Implement simple login using PHP-MySQL, the login page should look like, the one given below: | |||
| Create All necessary tables in MySQL and use JavaScript to ensure that form is not submitted when any of both fields are empty. Display appropriate Login Success/Login Failed message. | |||
|
|
|||
| What is a Cookie? | |||
| Cookies are pieces of text that are sent to a user’s web browser. Cookies can help you create shopping carts, user communities, and personalized sites. It’s not recommended that you store sensitive data in a cookie, but you can store a unique identification string that will match a user with data held securely in a database. | |||
| Take the shopping example. Suppose you assign an identification variable to a user so that you can track what he does when he visits your site. First, the user logs in, and you send a cookie with variables designed to say, “This is Ruchita, and Ruchita is allowed to be here.” | |||
| While Ruchita is surfing around your site, you can say, “Hello, Ruchita!” on each and every page. If Ruchita clicks through your catalog and chooses 14 items to buy, you can keep track of these items and display them all in a bunch when Ruchita goes to the checkout area. | |||
| A cookie is a text-only string that gets entered into the memory of your browser. This value of a variable that a website sets. Web cookies, tracking cookies or just cookies, are parcels of text sent by a server to a Web client (usually a browser) and then sent back unchanged by the client each time it accesses that server. HTTP cookies are used for authenticating, session tracking (state maintenance), and maintaining specific information about users, such as site preferences or the contents of their electronic shopping carts. The term “cookie” is derived from “magic cookie,” a well-known concept in UNIX computing which inspired both the idea and the name of HTTP cookies. | |||
|
|
|||
Creating and Using Cookie Cookies are created in PHP using the setcookie() function. setcookie() takes a number of arguments. The first argument is the name of the cookie (the name part of the name/value pair described earlier). The second is the value part of the name/value pair. The third argument is the optional expiration date of the cookie. The fourth argument specifies the active path for the cookie. The fifth argument is the domain setting and the sixth is the security setting (0 specifies HTTP and HTTPS and 1 specifies HTTPS only). Creating Cookie in PHP Based on the above information we can create a cookie using the following PHP: <?php
setcookie(‘username’, ‘Ruchita’, time() + 4800);
echo ‘Cookie has been set<br>’;
?> The above example creates a cookie on the computer system of anyone who loads the page (assuming they have cookies enabled in their browser) containing the name value pair userName=Ruchita’. The cookie will expire 4800 seconds from the time it is created. Reading a Cookie in PHP Given that you’ve gone to the trouble of writing a cookie it stands to reason you’ll probably want to read it back at some point. This is achieved by accessing the$_COOKIE array. The $_COOKIE array is an associative array whereby the name of the cookie provides the index into the array to extract the corresponding value of the name/value pair (for details of PHP arrays read the PHP Arrays chapter of this tutorial). For example we can obtain the value of our userName cookie as follows: <?php
echo ‘Reading cookie<br>’;
echo ‘userName = ‘ . $_COOKIE[‘userName’];
?> The above script should generate the following output: Cookie has been set Reading cookie userName = Ruchita Deleting a Cookie Cookies are deleted by calling the setcookie() function with the cookie name, a null for the value and an expiration date in the past. Once again the time() function can be used to calculate an expired date: <?php
setcookie (‘userName’, ”, time() – 4800);
?> Note that if you specified domain and/or path arguments when you created the cookie you must also specify them when you delete the cookie.
| What is a PHP Session? | |||
| What is a PHP Session? | |||
| PHP Sessions allow web pages to be treated as a group, allowing variables to be shared between different pages. One of the weaknesses of cookies is that the cookie is stored on the user’s computer (and by user we mean the person with the browser visiting your web site). This provides the user the ability to access, view and modify that cookie for potentially nefarious purposes. | |||
| PHP sessions, on the other hand, store only an ID cookie on the user’s system which is used to reference the session file on the server. As such, the user has no access to the content of the session file, thereby providing a secure alternative to cookies. | |||
| PHP sessions also work when the user has disabled the browser’s cookie support. In this situation it includes the session ID information in the web page URLs. | |||
| PHP Session Variables | |||
| When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state. | |||
| A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. | |||
|
|
|||
Handling File Upload A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads. PHP – File Upload: HTML Form Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our XHTML Tutorial’s Form lesson for a more in-depth look at forms. HTML Code:
<form enctype=”multipart/form-data”
action=”<?php echo $PHP_SELF;?>” method=”POST”>
<input type=”hidden”
name=”MAX_FILE_SIZE” value=”100000″ />
Choose a file to upload:
<input name=”uploadedfile” type=”file” /><br />
<input type=”submit”
value=”Upload File” name=”submit” />
</form>
Here is a brief description of the important parts of the above code: • enctype=”multipart/form-data” – Necessary for our to-be-created PHP file to function properly.
• action=”uploader.php” – The name of our PHP page that will be created, shortly.
• method=”POST” – Informs the browser that we want to send information to the server using POST.
• input type=”hidden” name=”MA… – Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
• input name=”uploadedfile” – uploadedfile is how we will access the file in our PHPscript. Save that form code into a file and call it upload.php. If you view it in a browser it should look like this: The complete example: simple-upload.php
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> PHP Tutorial: Working with File Upload </TITLE>
<META NAME=”Generator” CONTENT=”jNote-iT”>
</HEAD>
<BODY>
<form name= “file_upload_form”
enctype=”multipart/form-data” action=”<?php echo $PHP_SELF;?>” method=”POST”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”100000″ />
Choose a file to upload: <input name=”uploadedfile” type=”file” /><br />
<input type=”submit” value=”Upload File” name=”submit” />
</form>
<?php
if (isset($_POST[‘submit’]))
{
echo “<hr><hr>”;
$filedir=”c:/upload/”;// of on Linux [/var/www/upload] etc
$upload_file=$filedir.basenam
e($_FILES[‘uploadedfile’][‘name’]) or die (“Unable to retrieve the file.”);
$tmp=$_FILES[‘uploadedfile’][‘tempname’];
echo “<pre><b>”;
if (move_uploaded_file($_FILES[‘uploadedfile’][‘tempname’],$upload_file))
{
echo “\nFile “.$_FILES[‘uploadedfile’][‘name’].” uploaded successfully”;
}
else
echo “Unable to upload file<b>”.$tmp.”</b>”;
}
?>
</BODY>
</HTML>
When executed the above script should display following output: Uploaded file in the upload directory:
| PHP E-mail | |||
| The Mail () Function | |||
| Many websites offer a way for you to send them an email from a simple form on their site. Providing the form as opposed to simply listing your email address not only looks nicer but also serves two purposes. | |||
| 1. First, the form lets the website owner decide what information it is important to collect and prompts the users to fill in the answers to each of their questions. This way the user doesn’t forget to include important information. | |||
| 2. Second, if you list your email directly on your site it can be picked up by bots designed to ‘farm’ email addresses. What that means for you is SPAM. Nobody likes to have their inbox flooded with SPAM, and using a form can help prevent that. | |||
| The mail function is phrased as: mail (to, subject, body, headers) | |||
| An example is: | |||
| mail ( “user123@ebizelindia.com”, “Thanks for your Feedback”, “eBIZ Education thanks you for your valuable feedback”, ” feedback@ebizelindia.com ” ) | |||
| Creating the email form: | |||
| Source code for email.php | |||
| <html xmlns=”http://www.w3.org/1999/xhtml”><head>
<meta http-equiv=”Content-Type” <title>PHP Tutorial: Sending Email</title> <script language = “Javascript” function emailcheck(email) { var at=”@” var dot=”.” var lat=email.indexOf(at) var lstr=email.length var ldot=email.indexOf(dot) if (email.indexOf(at)==-1){ alert(“Invalid E-mail ID”) return false } if (email.indexOf(at)==-1 || em alert(“Invalid E-mail ID”) return false } if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 alert(“Invalid E-mail ID”) return false } if (email.indexOf(at,(lat+1))!=-1){ alert(“Invalid E-mail ID”) return false } if (email.substring(lat-1,lat)==dot alert(“Invalid E-mail ID”) return false } if (email.indexOf(dot,(lat+2))==-1){ alert(“Invalid E-mail ID”) return false } if (email.indexOf(” “)!=-1){ alert(“Invalid E-mail ID”) return false } return true } function validateForm(){ var to=document.emailform.to var message=document.emailform.message if ((to.value==null)||(to.value==””)){ alert(“Please Enter your Email ID”) to.focus() return false } if (emailcheck(to.value)==false){ to.value=”” to.focus() return false } if((message.value.length<10)|| (message.value==””)) { alert(“Your message should contain atleast 10 character”) return false } return true } –></script> <style type=”text/css”> <!– body { margin-left: 0px; margin-top: 0px; } .style1{ background:#0099FF scroll; color:#FFFFFF; font-weight:bold } –> </style></head> <body> <form name=”emailform” method=”post” <table width=”75%” border=”0″ cellspacing=”3″ cellpadding=”0″> <tr> <th width=”12%” align=”left” scope=”row”>TO:</th> <td width=”88%”><input type=”text” name=”to” /></td> </tr> <tr> <th align=”left” scope=”row”>Subject</th> <td><input type=”text” name=”subject” /></td> </tr> <tr> <th align=”left” scope=”row”>Message:</th> <td><textarea name=”message” cols=”40″ </tr> <tr> <th scope=”row”><input name=”submit” <td><input name=”reset” type=”reset” </tr> </table> </form> </body></html> |
|||
| The above form should look like the one shown below: | |||
| The server side PHP script: | |||
| send-email.php | |||
| <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”><html xmlns=”http://www.w3.org/1999/xhtml”> <head> <meta http-equiv=”Content-Type” <title><?php echo $msg;?></title> </head> <body> <?php $msg=””; $send_to=$_POST[‘to’]; $from=$_POST[‘from’]; $subject=$_POST[‘subject’]; $msg=$_POST[‘message’]; $headers = ‘From: $from’ . “\r\n” . ‘Reply-To: $from’ . “\r\n” . ‘X-Mailer: PHP/’ . phpversion(); mail($send_to,$subject,$msg,$headers); echo “Message Sent successfully to ?> </body> </html> |
|||
| The $headers parameter in the above script is optional, you can also skip it, e.g. | |||
| mail(($send_to,$subject,$msg) | |||
| NOTE: | |||
| In order to execute this PHP script successfully and send emails through it, SMTPshould be configured and other mail options should be configured in the php.ini | |||
|
|
|||
| Date | |||
| While PHP’s date() function may seem to have an overwhelming amount of options available, isn’t it always better to have more choices than not enough? With PHP’s date function you format timestamps, so they are more human readable. | |||
| The PHP date() function formats a timestamp to a more readable date and time. | |||
| Syntax | |||
| date(format,timestamp) | |||
| PHP Date – The Timestamp | |||
| The date function always formats a timestamp, whether you supply one or not. What’s a timestamp? Good question! | |||
| • Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize. | |||
| PHP Date – What Time Is It? | |||
| The date function uses letters of the alphabet to represent various parts of a typical date and time format. The letters we will be using in our first example are: | |||
| • d: The day of the month. The type of output you can expect is 01 through 31.• m: The current month, as a number. You can expect 01 through 12.
• y: The current year in two digits ##. You can expect 00 through 99 |
|||
| We’ll tell you the rest of the options later, but for now let’s use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP. | |||
| However, other characters like a slash “/” can be inserted between the letters to add additional formatting. We have opted to use the slash in our example. | |||
| PHP Code: | |||
| <?phpecho date(“m/d/y”);
?> |
|||
| If the 2010 Winter Olympics were just finishing up, you would see something like: | |||
| Display: | |||
| Be sure to test this out on your own PHP enabled server, it’s really great to see the instant results available with PHP date! | |||
| PHP Date – Supplying a Timestamp | |||
| As our first example shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional. | |||
| This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime. The mktime() function returns the Unix timestamp for a specified date. | |||
| Syntax | |||
| mktime(hour,minute,second,month,day,year,is_dst) | |||
| Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.• mktime(hour, minute, second, month, day, year, daylight savings time) | |||
| PHP Code: | |||
| <?phpecho “Today is :” .date(‘m/d/y’).”\n<br>Time in [MM/DD/YY]”; $tomorrow=mktime (0,0,0,date(“m”),date(“d”)+1,date(“y”)); echo “<br />Tomorrow is :” ?> |
|||
| Notice that we used one letter at a time with the function date to get the month, day and year. For example the date(“m”) will return the month’s number 01-12. | |||
| If we were to run our new script just after the 2010 Winter Olympics our display would look like: | |||
| Display: | |||
| PHP Date – Reference | |||
| Now that you know the basics of using PHP’s date function, you can easily plug in any of the following letters to format your timestamp to meet your needs. | |||
| Important Full Date and Time: | |||
| • r: Displays the full date, time and timezone offset. It is equivalent to manually entering date(“D, d M Y H:i:s O”) | |||
| Time: | |||
| • a: am or pm depending on the time • A: AM or PM depending on the time• g: Hour without leading zeroes. Values are 1 through 12.
• G: Hour in 24-hour format without leading zeroes. Values are 0 through 23. • h: Hour with leading zeroes. Values 01 through 12. • H: Hour in 24-hour format with leading zeroes. Values 00 through 23. • i: Minute with leading zeroes. Values 00 through 59. • s: Seconds with leading zeroes. Values 00 through 59. |
|||
| Day: | |||
| • d: Day of the month with leading zeroes. Values are 01 through 31. • j: Day of the month without leading zeroes. Values 1 through 31 • D: Day of the week abbreviations. Sun through Sat • l: Day of the week. Values Sunday through Saturday • w: Day of the week without leading zeroes. Values 0 through 6. • z: Day of the year without leading zeroes. Values 0 through 365. |
|||
| Month: | |||
| • m: Month number with leading zeroes. Values 01 through 12 • n: Month number without leading zeroes. Values 1 through 12 • M: Abbreviation for the month. Values Jan through Dec • F: Normal month representation. Values January through December. • t: The number of days in the month. Values 28 through 31. |
|||
| Year: | |||
| • L: 1 if it’s a leap year and 0 if it isn’t. • Y: A four digit year format • y: A two digit year format. Values 00 through 99. |
|||
| Other Formatting: | |||
| • U: The number of seconds since the Unix Epoch (January 1, 1970)• O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours | |||
| We suggest that you take a few minutes to create several timestamps using PHP’smktime function and just try out all these different letters to get your feet wet withPHP’s date function. | |||
|
|
|||
PHP XML In spite of the growing popularity of XML for storing and exchanging data of nearly any kind imaginable, XML is not well suited to act as a direct replacement for some of its defined subsets or sublanguages, like HTML. This is because XML defines only a standard for structuring data XML itself fails (indeed, by design) to provide any standard for how XML data in the general case should be rendered or displayed to the user. Such concerns, particularly in the case of the World Wide Web and the documents that it contains, are the domain of XML-compliant document type definitions such as Hypertext Markup Language (HTML) or Extensible Hypertext Markup Language (XHTML). Displaying and rendering standards like XHTML govern the ways in which the data and tags that form the structure of compliant XML documents are actually rendered onscreen for readers or World Wide Web users. Parsing XML data with SimpleXML What is SimpleXML? When people ask me “What is SimpleXML?” I often quip, “XML is the solution to all your problems; SimpleXML ensures it isn’t the root of your problems!” [Andres P. Ferrando] SimpleXML is new in PHP 5. It is an easy way of getting an element’s attributes and text, if you know the XML document’s layout. Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element. SimpleXML converts the XML document into an object, like this: • Elements – Are converted to single attributes of the SimpleXMLElement object. When there’s more than one element on one level, they’re placed inside an array • Attributes – Are accessed using associative arrays, where an index corresponds to the attribute name • Element Data – Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found SimpleXML is fast and easy to use when performing basic tasks like: • Reading XML files
• Extracting data from XML strings
• Editing text nodes or attributes However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM. Note: SimpleXML Parser is available only with PHP 5 and above. Example: simpleXML.php When using SimpleXML parser to parse XML files, simplexml_load_file(file_path) method is used to load the XML file. $emp=simplexml_load_file(“employee.xml”) or die(“Unable to Load XML file”); The example given below loads the XML file employee.xml and displays the data of theXML file in Table format:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type”
content=”text/html; charset=iso-8859-1″ />
<title>
<?php echo “PHP Tutorial: Working With SimpleXML Parser”;?></title>
</head>
<body>
<?php
$emp=simplexml_load_file(“employee.xml”)
or die(“Unable to Load XML file”);
$tbl=<<<TBL
<table border=”1″ cellspacing=”1″>
<tr bgcolor=”blue”>
<td> Employee ID</td>
<td> Name </td>
<td> Age</td>
<td> Department </td>
<td> Designation</td>
<td> Phone No</td>
<td> Address</td>
</tr>
TBL;
echo $tbl;
if($emp)
{
foreach($emp->employee as $ebiz)
{
foreach($ebiz->employee_details as $employee_details)
{
echo “<tr> \n<td>”.$employee_details->emp_id.”</td>\n”;
echo “<td>”.$employee_details->fname.”
“.$employee_details->lname.”</td>\n”;
echo “<td>”.$employee_details->age.”</td>\n”;
echo “<td>”.$employee_details->department.”</td>\n”;
echo “<td>”.$employee_details->designation.”</td>\n”;
echo “<td>”.$employee_details->phone.”</td>\n”;
echo “<td>”.$employee_details->address.”</td>\n”;
}
}
}
?>
</body>
</html>
Click here to view the XML file Output:
PHP Filter A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker. Why we need to use a Filter? Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). By using filters you can be sure your application gets the correct input type. You should always filter all external data! Input filtering is one of the most important application security issues. What is external data? • Input data from a form
• Cookies
• Web services data
• Server variables
• Database query results Using Server-side validation with PHP filters Following example demonstrate you how we can use PHP filters to validate and filter user input. This example is same to the example given in chapter 11.2 [PHP email] example, but instead of using JavaScript to validate user input on client side, this example validates the user input with the help of PHP filters and other PHP Built-in functions. You can use a combination of both. Using a combination of both Client-side & Server-side can be helpful when Client browser doesn’t have JavaScript enabled or it does not support JavaScript.
<?php
$msg=””;
$send_to=$_POST[‘to’];
$from=$_POST[‘from’];
$subject=$_POST[‘subject’];
$msg=$_POST[‘message’];
$headers = ‘From: $from’ . “\r\n” .
‘Reply-To: $from’ . “\r\n” .
‘X-Mailer: PHP/’ . phpversion();
$to_row=”valid”;
$from_row=”valid”;
$msg_row=”valid”;
$flag=0;
if ((strlen($subject)<=0)||(!$subject))
{
$subject=”No Subject Given”;
}
if (strlen($msg)<=0)
{
global $msg_row;
$msg_row=”invalid”;
global $flag;
$flag=-1;
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>PHP Tutorial: Working With Filter</title>
<style type=”text/css”>
<!–
body {
margin-left: 0px;
margin-top: 0px;
}
.style1{
background:#0099FF scroll; color:#FFFFFF; font-weight:bold
}
.invalid{
background-color:#FF0000;
color:#FFFFFF;
}
.valid
{
background-color:#FFFFFF;
color:#FF0000;
}
–>
</style></head>
<body>
<?php
if(isset($_POST[‘submit’]))
{
if(!filter_input(INPUT_POST,”send_to”,FILTER_VALIDATE_EMAIL))
{
global $to_row;
$to_row=”invalid”;
global $flag;
$flag=-1;
}
else
{
global $to_row;
$to_row=”valid”;
global $flag;
$flag=1;
}
if(!filter_input(INPUT_POST,”from”,FILTER_VALIDATE_EMAIL))
{
global $from_row;
$from_row=”invalid”;
global $flag;
$flag=-1;
}
else
{
global $from_row;
$from_row=”valid”;
global $flag;
$flag=1;
}
if($flag>0)
{
send();
}
}
?>
<form name=”emailform” method=”post”
onsubmit=”return validateForm()”
action=”<?php echo $PHP_SELF;?>”>
<table width=”75%” border=”0″ cellspacing=”0″ cellpadding=”0″>
<?php
if($flag<0)
{
?>
<tr style=”background-color:#CC6600;
color:#FFFFFF; font-weight:bold;
text-align:center”>
<td colspan=”2″>Please Re-Enter the Highlighted fields. </td>
</tr>
<?php
}
?>
<tr class=”<?php echo $to_row;?>”>
<td>TO</td>
<td><input type=”text” name=”to”
value=”<?php echo $send_to;?>” />*</td>
<tr>
<th align=”left” scope=”row”>From</th>
<td><input type=”text” name=”from” value=”<?php echo $from;?>” />
*</td>
</tr>
<tr>
<th align=”left” scope=”row”>Subject</th>
<td><input type=”text” name=”subject” value=”<?php echo $subject;?>”/></td>
</tr>
<tr>
<th align=”left” scope=”row”>Message:</th>
<td valign=”top”>
<textarea name=”message” cols=”40″ rows=”5″ class=”style1″ id=”message”>
<?php echo $msg;?></textarea>
*</td>
</tr>
<tr>
<th scope=”row”><input name=”submit”
type=”submit” value=”Send Email” /></th>
<td><input name=”reset” type=”reset” value=”Clear Form” /></td>
</tr>
</table>
</form>
</body>
</html>
<?php
function send()
{
global $send_to;
global $subject;
global $msg;
global $headers;
@mail($send_to,$subject,$msg,$headers
) or die(“Unable to Send EMAIL <br /> Please check your php.ini”);
echo “Message Sent successfully
to <a href=\”mailto:$send_to\”>$send_to</a>”;
}
?>
The above example usage built-in PHP function filter_input to filter user input. Syntax of filter_input filter_input ( int $type , string $variable_name [, int $filter [, mixed $options ]] ) $type can have any one of the following values: One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, Output: On submitting the form in this state Assignment 1. Write a PHP Script to upload images and then display the uploaded image.
| Download Links | ||
| In this section we will provide you download links for all necessary software, required for learning and development. | ||
| Apache Download | ||
| Download Apache from: [http://httpd.apache.org/download.cgi] | ||
| MySQL Download | ||
| Download MySQL from MySQL website [http://dev.mysql.com/downloads/mysql/] | ||
| PHP Download | ||
| Download PHP from: http://www.php.net/downloads.php | ||
| Windows Apache+ MySQL +PHP bundles | ||
| XAMPP | ||
| Download XAMPP form Apache Friends website [http://www.apachefriends.org/en/xampp-windows.php] |
||
| WAMP | ||
| Download WAMP from WAMPServer website [http://www.wampserver.com/en/download.php] | ||
| PHPTriad | ||
| http://sourceforge.net/projects/phptriad/ | ||
| EasyPHP | ||
| http://sourceforge.net/project/showfiles.php?group_id=14045 | ||
|
|
||
