Learning PHP & MySQL the Easy Way
Creating Database-Driven Dynamic Websites by
Antonio E. Refre. Ph.D.
PREFACE The content of this book was developed with the assumption that the userlearner has just a basic understanding of computer programming not beyond web authoring using HTML. Those who do not have the basic understanding of HTML will be provided references that can be learned without much difficulty. DrRefre’s School on the Web (http://www.teachlearn-online.net/aersow/) is one free web reference that can be used as a starter.
THE PRINCIPLES OF LEARNING USED IN THIS BOOK We are going to apply the principles of Constructivism (i.e. building new knowledge upon acquired knowledge) and Constructionism (i.e. learning by doing – experiential learning). In addition, we believe in the following statement: “You can do it. Everyone can, with the right kind of help.” We will provide you with tutorial-style content and Sample Program Capsule containing easy-to-use, real, and open programming environments in which to try as a foundation for building the Project dynamic website. Of course, besides you, the most important part of your learning is your Instructor/tutor, who coaches you with feedback, motivation, and encouragement throughout. You will be learning by doing as you go through this book. In the process you will be able to build new knowledge upon the knowledge you acquired. It is a common knowledge that skills are developed through practice. Also, practice makes perfect. As you practice, you commit mistakes. You keep on building up in your mind the lessons learned from such mistakes. When you try again, you improve your skill by applying these lessons-learned. Taking advice from others who have experienced such mistakes will make you reach your learning goal the faster way. With the power of the Internet and the Web, coaching or taking advice can be obtained from online resources.
Learning Skills through Practice and Coaching The Internet and the Web have enabled coaching anywhere and anytime. The author takes cognizance of this innovation that in case you need further help, visit DrRefre’s Books website: http://www.teachlearn-online.net/aerbooks/. The foregoing simple pedagogical technique that is often times applied in making project studies in school is applied in this book. Thus, the learning proceeds as the project gets accomplished. The project that will be taken up is building a community portal with different services to the members. The model used is the Alumni Portal that the author developed for the Tarlac High School Class 1957 Alumni. What will be learned from reworking this portal hands-on will be sufficient enough to build similar web applications like Intranets, Virtual Learning Environment Systems (Virtual Classrooms), and all sorts of Collaboration and Messaging Portals. This book can be used in the last year of secondary education by selecting some lessons in chapters 01, 02, and 03 that can already build a simple dynamic website. In college (tertiary and postgraduate), this book can be a very good companion in courses involving web applications development. For those who are or would like to become a Web Portal Developer, this book will surely be a very profitable reference.
TABLE OF CONTENTS CHAPTER 1 Getting Started Overview Chapter Review Exercises CHAPTER 2 PHP Tutorial Overview Chapter Review Exercises CHAPTER 3 PHP with MySQL Tutorial Overview Chapter Review Exercises CHAPTER 4 The Design Layout of the Community Portal and the Database Structure Overview Chapter Review Exercises CHAPTER 5 Online Membership Application Overview Chapter Review Exercises CHAPTER 6 Member Exclusive Page Overview Chapter Review Exercises CHAPTER 7 Uploading and Downloading Files (documents and images) for Sharing Overview Chapter Review Exercises Overall Summary, Conclusion, and Recommendation GLOSSARY – PHP and MySQL Statements and Functions Used in this Book BIBLIOGRAPHY – Reference Tutorial Websites
APPENDIX I WINDOWS INSTALLATION OF WEB SERVER USING WampServer APPENDIX II HOW TO GET FREE WEBHOSTING
CHAPTER 1 – GETTING STARTED OVERVIEW To get started with our learning PHP&MySQL the easy way, we will get a free Webhosting provider like the awardspace.com. All the files and database of the Sample Program Capsule are going to be uploaded to the Web server of this provider. You will do this with a step-by-step guide to make things easy even for a novice. PRE-REQUISITES Inasmuch as the primary objective of this book is to teach you how to create a database-driven dynamic website using PHP&MySQL, you need the basic foundations in (surf the Web and you will see a lot of free reference resources): 1. Web programming (browser technology, plug-ins, cookies) 2. Developing a Webpage using HTML (Hypertext Markup Language), CSS (Cascading Style Sheet), and Javascript 3. Understanding server-side scripting language using PHP 4. Understanding database using MySQL In addition to the foregoing foundations, we are going to use a Linux platform for hosting your project. Instead of setting up your own in your computer, we will avail of the free web hosting service (e.g. awardspace.com). The free web hosting will relieve us of the installation intricacies of the necessary elements and facilities. Thus, while we are in the process of building the Website, we can see on real-time and real-world the progress of the development of our Website.
Web Programming Related to what we wish to create in this book, a basic understanding of clientserver computing is necessary. Whenever you access the Internet to get into your email (e.g. http://www.yahoo.com/), your computer (a desktop, a laptop, or mobile phone) becomes the client of the Yahoo’s email server. Access is facilitated by a browser program (e.g. Internet Explorer or Mozilla Firefox). Inside this program are subprograms that allow you to open some proprietary programs like Flash movies. If getting into the Website you chose requires logging in, the “cookies” program captures the login information and the temporarily-stored information are used to authenticate the access to the other web pages that require such. This is the Web programming foundation needed in this book.
Developing a Webpage using HTML, CSS, and Javascript To get detailed instructions on how to develop a Webpage using HTML and Javascript, visit DrRefre’s School on the Web: http://www.teachlearnonline.net/aersow/ and get into the Online Teaching and Learning SeminarWorkshop (OLTLSW). HyperText Markup Language (HTML) is the predominant markup language for web pages. It simply provides a means to describe the structure of text-based information in a document — by denoting certain text as links, headings, paragraphs, lists, and so on — and to supplement that text with interactive forms, embedded images, and other objects. HTML is written in the form of tags, surrounded by angle brackets. HTML can also describe, to some degree, the appearance and semantics of a document, and can include embedded scripting language code which can affect the behavior of web browsers and other HTML processors. Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML. CSS is designed primarily to enable the separation of document content (written in HTML or a similar markup language) from document presentation, including elements such as the colors, fonts, and layout. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content (such as by allowing for table-less web design). JavaScript is a scripting language most often used for client-side web development. JavaScript was influenced by many languages and was designed to have a similar look to Java, but is easier for non-programmers to work with. The language is best known for its use in websites (as client-side JavaScript), but is also used to enable scripting access to objects embedded in other applications. Despite the name, JavaScript is essentially unrelated to the Java programming language, though both have a common debt to C syntax, and JavaScript copies many Java names and naming conventions. The language was renamed from LiveScript in a co-marketing deal between Netscape and Sun in exchange for Netscape bundling Sun's Java runtime with their browser, which was dominant at the time. "JavaScript" is a trademark of Sun Microsystems. It
was used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.
Understanding server-side scripting language using PHP PHP (a recursive acronym for PHP: Hypertext Preprocessor) was written as a set of Common Gateway Interface (CGI) binaries in the C programming language by the Danish/Greenlandic programmer Rasmus Lerdorf in 1994, to replace a small set of Perl scripts he had been using to maintain his personal homepage. PHP is a computer scripting language originally designed for producing dynamic web pages. PHP can be used from a command line interface or in standalone graphical applications. The most recent version of PHP is 5.2.5, released on 8 November 2007. It is considered to be free software by the Free Software Foundation. A PHP tutorial is given in Chapter 02 wherein the syntax of PHP is explained with examples.
Understanding database using MySQL database A computer database is a structured collection of records or data that is stored in a computer system. Typically, for a given database, there is a structural description of the type of facts held in that database: this description is known as a schema. The schema describes the objects that are represented in the database, and the relationships among them. There are a number of different ways of organizing a schema, that is, of modeling the database structure: these are known as database models (or data models). The model in most common use today is the relational model. Databases are designed to offer an organized mechanism for storing, managing and retrieving information. They do so through the use of tables. If you are familiar with spreadsheets like Microsoft Excel, you are probably already accustomed to storing data in tabular form. It is not much of a stretch to make the leap from spreadsheets to databases. Just like Excel tables, database tables consist of columns and rows. Each column contains a different type of attribute and each row corresponds to a single record. For example, imagine that we were building a database table that contained names and telephone numbers. We’d probably set up columns named “FirstName”, “LastName” and “TelephoneNumber.” Then we would simply start
adding rows underneath those columns that contained the data we are planning to store. If we were building a table of contact information for our business that has 50 employees, we would wind up with a table that contains 50 rows. At this point, you’re probably asking yourself an obvious question – if a database is so much like a spreadsheet, why can I not just use a spreadsheet? Databases are actually much more powerful than spreadsheets in the way you are able to manipulate data. Here are just a few of the actions that you can perform on a database that would be difficult if not impossible to perform on a spreadsheet: • • • •
Retrieve all records that match certain criteria Update records in bulk Cross-reference records in different tables Perform complex aggregate calculations
A database is an application that can store and retrieve data very rapidly. The relational bit refers to how the data is stored in the database and how it is organized. When we talk about database, we mean a relational database, in fact an RDBMS - Relational Database Management System. In a relational database, all data is stored in tables. These have the same structure repeated in each row (like a spreadsheet) and it is the relations between the tables that make it a "relational" table. List of Commercial Databases Oracle IBM DB 2 Microsoft SQL Server Ingres. The first commercial RDBMS. List of Free/Open Source Databases MySQL PostgresSQL SQLite Strictly these are not relational databases but RDBMS. They provide security, encryption, user’s access and can process SQL queries. What is the Table of a Database?
Think of it as being like a rectangular spreadsheet made up of rows and columns. Each column specifies the type of data stored (numbers, strings or binary data - such as images). Unlike a spreadsheet where the user is free to have different data on each row, in a database table, every row can only contain the types of data that were specified. In order for you to understand further what a database is, let us illustrate this using the analogy with a telephone book or the filing system of a library. You can think of a database as an electronic filing system. Traditional databases are organized into Records containing Fields. Each field contains specific information. A telephone book is an example of a database.
The library catalogue is a database, which contains records of all resources held by the library, but does not describe detailed information about book chapters or articles in journals. Each record consists of fields such as author, title, publisher, item location, call number, description, bibliography and subject. The library subscribes to Subject Databases available via the Internet to support research and teaching. These Databases allow you to find articles in journals, magazines and newspapers. They can also contain references to book reviews, conference proceedings, reports, book chapters and other publications. These databases can contain a mixture of record types including full text, abstracts or citations. There are many different types of library databases. The description of the records contained in a database will often determine its type. The most common types are: Bibliographic databases
Full-text databases Numeric databases Image databases Audio/Video databases Mixed databases (a combination of any or all types of information) To access information in a database, you use the database’s search facility. This is sometimes called search engine or search screen or interface. Although some databases look different, they all have certain features in common. Understanding these common features will allow you to apply general principles to your searching regardless of which database you use. The common features of databases may include: Text box to type in a search term Basic and advanced searching options Combining terms using connectors Limiting search options by field e.g. date, language, publication type An index of subject headings or a thesaurus A results display A search history display Online help Ability to Mark or Choose Records so you can compile your own list of results Ability to Print, Save and Email results The layout of records generated by a database search will vary according to the database being searched, but the fields they contain will be similar. Fields in a typical bibliographic database record will include: Title of article Author of article Publication date Title of Journal (sometimes named Source or Citation) Article Language Abstract Descriptors or Subject Headings Publication Type However, not all databases contain journal articles. The results and field names from databases containing other types of information will reflect the information contained in them. Consult the database HELP menu for more information about results and fields.
What are the Different Ways of Storing Data in a Database? There are two ways: 1. Via a Database Server.
2. Via a Database File
Using a Database File is the older method, more suited to desktop applications; e.g. Microsoft Access, though that is being phased out in favor of Microsoft SQL Server. SQLite is an excellent public domain database written in C that holds data in one file. A Database Server is a server application running locally or on a networked PC. Most of the big databases are server based. These take more administration but are usually faster and more robust. How does an Application Communicate with Database Servers? Generally these require the following details. IP or Domain name of the server. If it is the on the same PC as you, use 127.0.0.1 or localhost as the dns name. Server Port For MySQL this is usually 3306, 1433 for Microsoft SQL Server. User Name and Password Name of the Database There are many client applications that can talk to a database server. Microsoft SQL Server has Enterprise Manager to create databases, set security, run maintenance jobs, queries and of course design and modify database tables. What is SQL? SQL is short for Structured Query Language and is a simple language that provides instructions for building and modifying the structure of databases and for modifying the data stored in the tables. The main commands used to modify and retrieve data are: Select - Fetches data. Insert - Inserts one or more rows of data. Update - Modifies existing row(s) of data Delete - Deletes rows of data. What are SQL tables?
A database can be made up of many tables, and a table in a database is made up of intersecting columns and rows that form a grid. A good way to think about this is to imagine a checker board. Along the top row of the checkerboard there are labels for the data you wish to store, for example Name, Age, Gender, Eye Color, etc. In all the rows below, information is stored. Each row is one entry (all the data in a single row, belongs to the same person in this case) and each column contains a specific type of data as indicated by its label. Here is something to help you visualize a table:
A SQL table is made of intersecting rows and columns As we go along in the setting up of the database for our project, you will get a better understanding on how these tables look like. Chapter 03 will discuss the setting up of the database. l/ "my S-Q-L" or sometimes "my sequel") is a MySQL (pronounced /ma skju multithreaded, multi-user SQL database management system (DBMS) which has, according to MySQL AB, more than 10 million installations. The basic program runs as a server providing multi-user access to a number of databases. MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, which holds the copyright to most of the codebase. The project's source code is available under terms of the GNU General Public License, as well as under a variety of proprietary agreements.
MySQL is popular for web applications and acts as the database component of the LAMP, MAMP, and WAMP platforms (Linux/Mac/Windows-Apache-MySQLPHP/Perl/Python), and for open-source bug tracking tools like Bugzilla. Its popularity for use with web applications is closely tied to the popularity of PHP and Ruby on Rails, which are often combined with MySQL. PHP and MySQL are essential components for running popular content management systems such as Joomla!, WordPress, Google, Ebay and Drupal. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database. Basic understanding of the syntax of MySQL is given in Chapter 03 PHP with MySQL Tutorial.
Sample Program Capsule To get started right away, let us practice on how to use PHP and MySQL in developing a dynamic website through a sample website that we will call the “My Personal Address Book.� The Homepage (http://aerefre.awardspace.info/) of this website is as shown in the following:
Chapter 2 and Chapter 3 consider this in a very detailed manner and at a level of treatment intended for the last year of high school studies. The PHP and MySQL reference websites are http://www.php.net/ (where you can see the PHP syntax and functions) and http://dev.mysql.com/doc/ (where MySQL Reference Manual can be obtained from), respectively. The Development Platform The Linux platform is our choice. To free us from installation intricacies, we will use the free web hosting service of http://www.awardspace.com/ (if you would like to go into the complex way of installing your Web server in your desktop computer, the procedure on how to do the installation is found in the Appendix). In this way, we immediately immerse ourselves in the learning process. An important advantage of this strategy is that we can proceed in our development tasks anywhere we are and at anytime…24/7 as long as we have an Internet access. The Sample Program Capsule: “My Personal Address Book” is already hosted by the foregoing-mentioned free web hosting service. The address is: http://aerefre.awardspace.info/. Setting Up the Development Platform How to Get the Free Web Hosting Service:
1. Go to http://www.awardspace.com/
2. Click the Try Now button of the Easy Starter Hosting Plan 3. Click the Sign Up Now button.
4. Fill up the form choosing the free subdomain; then, click Next button.
5. Click NEXT and proceed accordingly Get from your email inbox the relevant information sent to you by the awardspace.com after having done your order. This bunch of information is needed to use your web hosting service; especially, your username and password to get into the cPanel.
How to get into the cPanel of your website and set up your database Before proceeding to the following steps, download the addrbook.zip from http://www.teachlearn-online.net/aerbooks/. Setting up the subdomain and database for the Sample Program Capsule – My Personal Address Book: (Note: The following steps are for awardspace.com; other free web hosting provider may have different steps) 1. Follow the instructions given to you in the email to get into the cPanel.
2. Go to http://cp5.awardspace.com/ and you will see the following page:
Enter your given username and password and if accepted, you will get into the Homepage of the cPanel: Click the Website Manager and you will see the following page:
3. Click the Subdomain Manager and you will see the following page:
then, enter the your username to get into the cPanel and choose awardspace.info; then click Add Subdomain button 4. From the left of the screen, click the MySQL Manager from the Website Manager options and create a new database named addrbook. (Database name includes your user name and must not be more than 16 characters long.)
Thereafter, use the same password you used in the cPanel.
Take note of the following created info: DB Host, DB Name and DB User. 5. Go back to the cPanel Website Manager at the left panel. Click the phpMyAdmin.
Enter your username_database and password and you get into your MySQL database:
6. Click the database you see on the left panel; then, create the table contacts and the table admin (for the field name, field type, and field length, refer from the unzipped addrbook.zip. Unzip the downloaded addrbook.zip file and look for the SQL file and open it using Wordpad. Create the table contacts and one by one put in the eleven (11) fields. Before saving the database, choose latin1_general_ci for the collation type. 7. In the username_addbook database, create another table named admin insert three (3) fields namely userid: with data admin01, username: (your username chosen for the cPanel login); and password: (your password chosen for the cPanel login). After having successfully accomplished the foregoing steps, you have now your development platform ready for your “My Personal Address Book” Website. How to upload the files (PHP files, mages, folders) into the web server root directory: /www Files for the Sample Program Capsule “My Personal Address Book”: 1. If you have not done it yet, download from http://www.teachlearnonline.net/aerbooks/ the file addrbook.zip. Unzip this to your hard disk directory named addrbook (create it if it is not yet existing). 2. Go back to cPanel Website Manager. a. Click the File Manager in the Files section. Disable the directory protection.
b. Click on your subdomain folder to open
c. Scroll to the bottom of the resulting page. You are about to create the folders cms, images, and scripts. Follow the succeeding instructions. d. Click the cms folder to open it; then, create the images folder e. Click this images folder to open it f. Click Browse button and select the files from your hard disk directory addrbook\cms\images you wish to upload; proceed accordingly until you have uploaded all the files. g. Go up one level to cms directory. Click Browse button and select the files from your hard disk directory addrbook\cms you wish to upload; proceed accordingly until you have uploaded all the files. h. Go up one level to subdomain directory. Click images folder to open it. Click Browse button and select the files from your hard disk directory addrbook\images you wish to upload; proceed accordingly until you have uploaded all the files. i. Go up one level to subdomain directory. Click scripts folder to open it. Click Browse button and select the files from your hard disk directory addrbook\scripts you wish to upload; proceed accordingly until you have uploaded all the files. j. Go up one level to subdomain directory. Click Browse button and select the files from your hard disk directory addrbook you wish to upload; proceed accordingly until you have uploaded all the files. 3. You may also upload the files using a FTP client (see below).
THE FTP CLIENT To upload your files faster to your web server, use the free FTP client FileZilla. Get it from http://filezilla-project.org/download.php?type=client. Install it to your computer and configure it to point to your host website with username and password given to you by awardspace.com.
THE TEXT EDITOR We will use a free PHP Text Editor: Arisesoft Winsyntax. You can download it from http://www.winsyntax.com/. CHAPTER REVIEW To get started in our learning how to create database-driven dynamic website using PHP&MySQL, we have to set up our development platform. We use a free web hosting service from awardspace.com that provides all the necessary elements and facilities we need in our hands-on website development activities. We look for all the tools we need from the Web and get those that are free. Although these tools are free, they are very good for our purpose. Then, we prepare our web server to accept files and data for our Sample Program Capsule: The “My Personal Address Book” Website. We visit the PHP and MySQL websites to see what are the references available. Thus, we can move on now to Chapter 02 PHP Tutorial.
EXERCISES Familiarize yourselves on the operation of the cPanel of your chosen web hosting service. If you encounter difficulties and your instructor/tutor cannot help you, email Dr. Refre: aerefre@gmail.com. For additional exercises, go to the DrRefre’s Books: http://www.teachlearn-online.net/aerbooks/ .
CHAPTER 2 – PHP TUTORIAL OVERVIEW PHP stands as the recursive acronym for PHP: Hypertext Preprocessor and is a server-side language. This means that the script is run on your web server, not on the user's browser, so you do not need to worry about compatibility issues. PHP is relatively new (compared to languages such as Perl (CGI) and Java) but is quickly becoming one of the most popular scripting languages on the Internet. To know more about PHP and its syntax, visit http://www.php.net/. You may be wondering why we choose PHP over other languages such as Perl or even why we should learn a scripting language at all. Let us talk about learning scripting languages first. Learning a scripting language, or even understanding one, can open up huge new possibilities for your website. Although you can download pre-made scripts from sites like Hotscripts.com, these will often contain advertising for the author or will not do exactly what you want. With an understanding of a scripting language you can easily edit these scripts to do what you want, or even create your own scripts. Using scripts on your website allows you to add many new 'interactive' features like feedback forms, guestbooks, message boards, counters and even more advanced features like portal systems, content management, advertising managers etc. With these sort of things on your website you will find that it gives a more professional image. As well as this, anyone wanting to work in the site development industry will find that it is much easier to get a job if they know a scripting language. As mentioned earlier, PHP is a server-side scripting language. This means that, although your users will not need to install new software, your web host will need to have PHP set up on their server. We will use the free web server of http://www.awardspace.com/ which supports PHP and MySQL. Writing PHP on your computer is actually very simple. You do not need any special software, except for a text editor (like Notepad in Windows). A free PHP editor can be obtained from http://www.winsyntax.com/.
Opening and Ending PHP Tags To open a block of PHP code in a page you can use one of these four sets of opening and closing tags
Opening Tag
Closing Tag
<?
?>
<?php
?>
<%
%>
<script language="php"> </script> The first pair (<? and ?>) is called short tags. You should avoid using short tags in your application especially if it is meant to be distributed on other servers. This is because short tags are not always supported. Short tags are only available if explicitly enabled setting the short_open_tag value to On in the PHP configuration file php.ini. So, for all PHP code in this book we will use the second pair, <?php and ?>. All the examples shown here demonstrate how PHP scripts are embedded in the HTML. Now, for the first example create a file and name it hello.php (you can use NotePad or your favorite text editor: Winsyntax) and upload it into your web serverâ&#x20AC;&#x2122;s subdomain directory (see Chapter 01). Another way of uploading is using FTP (get the free FileZilla client). Example 1: hello.php <html> <head> <title>My First PHP Page</title> </head> <body> <?php echo "<p>Hello World, How Are You Today?</p>"; ?> </body> </html>
Overall, you have a simple HTML page with a single PHP section in bold. When the server encounters the <?php symbol, it knows to evaluate the commands that follow, rather than simply send them out to the browser. It keeps following instructions until the end of the section, as indicated by the ?> symbol.
In this case, you have just one command, echo, which tells the server to output the indicated text. That means that if you save the page and call it with your browser, the browser receives: <html> <head> <title>My First PHP Page</title> </head> <body> <p>Hello World, How Are You Today?</p> </body> </html>
To view in browser the result, type in the address of your browser this: http://(yourgivendomain)/hello.php. You may see this also by going to http://aerefre.awardspace.info/hello.php. You will be using the foregoing steps in viewing in browser the PHP code of all the examples in this chapter. The example above shows how to insert PHP code into an HTML file. It also shows the echo statement used to output a string. See that the echo statement ends with a semicolon. Every command in PHP must end with a semicolon. If you forget to use semicolon or use colon instead after a command you will get an error message like this: Parse error: parse error, unexpected ':', c:\Apache\htdocs\examples\get.php on line 7
expecting
','
or
';'
in
Using Comments Comment is a part of your PHP code that will not be translated by the PHP engine. You can use it to write documentation of your PHP script describing what the code should do. A comment can span only for one line or span multiple lines. PHP support three kinds of comment tags : 1. // This is a one line comment 2. # This is a Unix shell-style comment. It's also a one line comment 3. /* ..... */ Use this multi line comment if you need to.
Example 2 : comments.php
<?php echo "First line <br>"; // You won't see me in the output // I'm a one liner comment /* Same thing, you won't see this in the output file */ echo "The above comment spans two lines <br>"; # Hi i'm a Unix shell-style comment # Too bad you can't see me echo "View the source of this file, you'll see no comments here <br>"; ?>
PHP Variables A variable is a placeholder for data. You can assign a value to it, and from then on, any time PHP encounters your variable, it will use the value instead. Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive, so $myvar is different from $myVar. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Example : <?php $myvar = "Hello"; // valid $yourVar_is-123 = "World"; // valid $123ImHere = "Something"; // invalid, starts with number ?>
Variable Scope The scope of a variable is the context within which it is defined. Basically you can not access a variable which is defined in different scope. The script below will not produce any output because the function Test() declares no $a variable. The echo statement looks for a local version of the $a
variable, and it has not been assigned a value within this scope. Depending on error-reporting value in php.ini the script below will print nothing or issue an error message. Example 3 : scope.php
<?php $a = 1; // $a is a global variable function Test() { echo $a; // try to print $a, but $a is not defined here } Test(); ?>
Note that } is a curly bracket. The open and close curly brackets enclose the executable statement. If you want your global variable (variable defined outside functions) to be available in function scope you need to use the $global keyword. The code example below shows how to use the $global keyword. Example 4: global.php <?php $a = 1; // $a is defined in global scope ... $b = 2; // $b too function Sum() { global $a, $b; // now $a and $b are available in Sum() $b = $a + $b; } Sum(); echo $b; ?>
PHP Superglobals Superglobals are variables that are available anywhere in the program code. They are :
$_SERVER Variables set by the web server or otherwise directly related to the execution environment of the current script. One useful variable is $_SERVER['REMOTE_ADDR'] which you can use to know your website visitor's IP address Example 5: ip.php <?php echo “Your computer IP is <br>”; echo $_SERVER['REMOTE_ADDR']; ?>
$_GET Variables provided to the script via HTTP GET. You can supply GET variables into a PHP script by appending the script's URL like this : http://www.php-mysqltutorial.com/../examples/get.php?name=php&friend=mysql or set the a form method as method="get" Example 6: get.php <?php echo "My name is {$_GET['name']} <br>"; echo "My friend's name is {$_GET['friend']}"; ?>
Note that we put $_GET['name'] and $_GET['friend'] in curly brackets. It is necessary to use these curly brackets when you're trying to place the value of an array into a string. You can also split the string like this : echo "My name is " . {$_GET['name']} . "<br>";
but it is easier to put the curly brackets. $_POST Variables provided to the script via HTTP POST. These comes from a form which set method="post" $_COOKIE Variables provided to the script via HTTP cookies.
$_FILES Variables provided to the script via HTTP post file uploads. $_ENV Variables provided to the script via the environment. $_REQUEST Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. Use the appropriate $_POST or $_GET from your script instead of using $_REQUEST so that you will always know that a variable comes from POST or GET. $GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. You usually will not need the last three superglobals in your script.
Variable Types PHP supports eight primitive types. Four scalar types: boolean : expresses truth value, TRUE or FALSE. Any non zero values and non empty string are also counted as TRUE. integer : round numbers (-5, 0, 123, 555, ...) float : floating-point number or 'double' (0.9283838, 23.0, ...) string : "Hello World", 'PHP and MySQL, etc Two compound types: array object And finally two special types: resource ( one example is the return value of mysql_connect() function) NULL
In PHP an array can have numeric key, associative key or both. The value of an array can be of any type. To create an array use the array() language construct like this. Example 7: array.php <?php $numbers = array(1, 2, 3, 4, 5, 6); $age = array('mom' => 45, 'pop' => 50, 'bro' => 25); $mixed = array('hello' => 'World', 2 => "It's two"); echo "numbers[4] = {$numbers[4]} <br>"; echo "My mom's age is {$age['mom']} <br>"; echo "mixed['hello'] = {$mixed['hello']} <br>"; echo "mixed[2] = {$mixed[2]}"; ?>
When working with arrays there is one function we often used. The print_r() function. Given an array this function will print the values in a format that shows keys and elements Example 8: printr.php <?php $myarray = array(1, 2, 3, 4, 5); $myarray[5] = array("Hi", "Hello", "Konnichiwa", "Apa Kabar"); echo '<pre>'; print_r($myarray); echo '</pre>'; ?>
Do not forget to print the preformatting tag <pre> and </pre> before and after calling print_r(). If you don't use them, then you'll have to view the page source to see a result in correct format.
Type Juggling In PHP you don't need to explicitly specify a type for variables. A variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. Example : <?php $myvar = "0"; // $myvar is string (ASCII 48) $myvar += 2; // $myvar is now an integer (2) $myvar = $foo + 1.3; // $myvar is now a float (3.3) $myvar = 5 + "10 Piglets"; // $foo is integer (15) ?>
Type Casting To cast a variable write the name of the desired type in parentheses before the variable, which is to be cast. Example 9: casting.php <?php $abc = 10; // $abc is an integer $xyz = (boolean) $abc; // $xyz is a boolean echo "abc is $abc and xyz is $xyz <br>"; ?>
The casts allowed are: (int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object Playing with Strings Strings are probably what you will use most in your PHP code. From concatenating, looking for patterns, trim, chop etc. So, it is a good idea to take a better look at this creature. We will also take a peek at some string functions that you might find useful for everyday coding.
Creating a String To declare a string in PHP you can use double quotes ( " ) or single quotes ( ' ). There are some differences you need to know about using these two. If you are using double-quoted strings variables will be expanded ( processed ). Special characters such as line feed ( \n ) and carriage return ( \r ) are expanded too. However, with single-quoted strings none of those things happen. Take a look at the example below to see what we mean. Note that browsers do not print newline characters ( \r and \n ) so when you open string.php take a look at the source and you will see the effect of these newline characters. Example 10: string.php <?php $fruit = 'jamblang'; echo "My favorite fruit is $fruit <br>"; echo 'I lied, actually I hate â&#x20AC;&#x2DC;.$fruit.â&#x20AC;&#x2122;<br>'; echo "\r\n My first line \r\n and my second line <br>\r\n"; echo ' Though I use \r\n this string is still on one line <br>'; ?>
String Concatenation To concatenate two strings you need the dot ( . ) operator so in case you have a long string and for the sake of readability you have to cut it into two you can do it just like the example below. Actually if you need to write a long string and you want to write it to multiple lines, you do not need to concatenate the strings. You can do it just like the second example below where $quote2 is split into three lines. Example 11: concat.php <?php $quote1 = "Never insult Dumbledore " . "in front of me!"; $quote2 = "Nami, you are my nakama!";
echo $quote1 . "<br>"; echo $quote2; ?>
String Functions substr($string, $start, $end) : get a chunk of $string <?php // print '12' echo substr('123456789', 0, 2); // print '56789' echo substr('123456789', 4); // print '89' echo substr('123456789', -2); // print '456' echo substr('123456789', 3, -4); ?>
str_repeat($string, $n) : repeat $string $n times For example if you want to print a series of ten asteriks ( * ) you can do it with a for loop like this : <?php for ($i = 0; $i < 10; $i++) { echo '*'; } ?>
Or you can go the easy way and do it like this : <?php echo str_repeat('*', 10); ?>
strrchr($string, $char) : find the last occurence of the character $char in $string For example: you want to get the file extension from a file name. You can use this function in conjunction with substr()
<?php $ext = substr(strrchr($filename, '.'), 1); ?>
What the above code do is get a chunk of $filename starting from the last dot in $filename then get the substring of it starting from the second character ( index 1 ). To make things clearer suppose $filename is 'tutorial.php'. Using strrchr('tutorial.php', '.') yield '.php' and after substr('.php', 1) we get the file extension; 'php' trim($string) : remove extra spaces at the beginning and end of $string <?php // print 'abc def' echo trim(' abc def ?>
');
addslashes($string) : adding backslashes before characters that need to be quoted in $string This function is usually used on form values before being used for database queries. You will see this function used a lot in this tutorial, so there's no need to present an example here. explode($separator, $string) : Split $string by $separator This function is commonly used to extract values in a string which are separated by a certain separator string. For example, suppose we have some information stored as comma separated values. To extract each value we can do it like shown below <?php // extract information from comma separated values $csv = 'Uzumaki Naruto,15,Konoha Village'; $info = explode(',', $csv); ?>
Now, $info is an array with three values : Array ( [0] => Uzumaki Naruto [1] => 15
[2] => Konoha Village )
We can further process this array like displaying them in a table, etc. implode($string, $array) : Join the values of $array using $string This one does the opposite than the previous function. For example to reverse back the $info array into a string we can do it like shown below : <?php $info = array('Uzumaki Naruto', 15, 'Konoha Village'); $csv = implode(',', $info); ?>
Another example: Pretend we have an array containing some values and we want to print them in an ordered list. We can use the implode() like this : <?php // print ordered list of names in array $names = array('Uchiha Sasuke', 'Haruno Sakura', 'Uzumaki Naruto', 'Kakashi'); echo '<ol><li>' . implode('</li><li>', $names) . '</li></ol>'; ?>
The result of that code is like an ordered list just like shown below 1. Uchiha Sasuke 2. Haruno Sakura 3. Uzumaki Naruto 4. Kakashi By the way, we did write the above php code to print that list instead of writing the list directly number_format($number): display a number with grouped thousands When displaying numbers it is usually more readable if the numbers is properly formatted like 1,234,567 instead of 1234567. Using this function is very simple like shown below: <?php // display 15,120,777 echo number_format(15120777); ?>
Control Structures The next examples will show you how to use control structures in PHP. We will not go through all but just the ones that we will use in the code examples in this site. The control structures are • • • •
if else while for
If Else The if statement evaluates the truth value of it's argument. If the argument evaluates as TRUE, the code following the if statement will be executed. And if the argument evaluate as FALSE and there is an else statement then the code following the else statement will be executed. Example 12: visitor-info.php <?php $ip = $_SERVER['REMOTE_ADDR']; $agent = $_SERVER['HTTP_USER_AGENT']; if(strpos($agent, 'Opera') !== false) $agent = 'Opera'; else if(strpos($agent, "MSIE") !== false) $agent = 'Internet Explorer'; echo "Your computer IP is $ip and you are using $agent"; ?>
The strpos() function returns the numeric position of the first occurrence of its second argument ('Opera') in the first argument ($agent). If the string 'Opera' is found inside $agent, the function returns the position of the string. Otherwise, it returns FALSE. When you're using Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT'] would be something like: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) and if you're using Opera the value the value may look like this :
Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.0 [en] So if you use Opera the strpos() function will return value would be 61. Since 61 !== false then the first if statement will be evaluated as true and the value of $agent will be set to the string 'Opera'. Note that we use the !== to specify inequality instead of != The reason for this is because if the string is found in position 0 then the zero will be treated as FALSE, which is not the behavior that we want. While Loop The while() statement is used to execute a piece of code repeatedly as long as the while expression evaluates as true. For example the code below will print the number one to nine. Example 13: while.php <?php $number = 1; while ($number < 10) { echo $number . '<br>'; $number += 1; } ?>
You see that we make the code $number += 1; as bold. We did it simply to remind that even an experienced programmer can sometime forget that a loop will happily continue to run forever as long as the loop expression ( in this case $number < 10 ) evaluates as true. So when you're creating a loop please make sure you already put the code to make sure the loop will end in a timely manner. Break The break statement is used to stop the execution of a loop. As an example the while loop below will stop when $number equals to 6. Example 14: break.php <?php $number = 1;
while ($number < 10) { echo $number . '<br>'; if ($number == 6) { break; } $number += 1; } ?>
You can stop the loop using the break statement. The break statement however will only stop the loop where it is declared. So if you have a cascading while loop and you put a break statement in the inner loop then only the inner loop execution that will be stopped. Example 15: break2.php <?php $floor = 1; while ($floor <= 5) { $room = 1; while ($room < 40) { echo "Floor : $floor, room number : $floor". "$room <br>"; if ($room == 2) { break; } $room += 1; } $floor += 1; echo "<br>"; } ?>
If you run the example you will see that the outer loop, while ($floor <= 5), is executed five times and the inner loop only executed two times for each execution of the outer loop. This is the proof, that the break statement only stops the execution of the inner loop where it is declared. For
The for loop syntax in PHP is similar to C. For example to print 1 to 10 the for loop is like this shown below: <?php for ($i = 1; $i <= 10; $i++) { echo $i . '<br>'; } ?>
A more interesting function is to print this number in a table with alternating colors. Here is the code: Example 16: alternate-colors.php <html> <head><title>Alternate-Colors</head> <body> <table width="200" border="0" cellspacing="1" cellpadding="2"> <tr> <td bgcolor="#CCCCFF">Alternating row colors</td> </tr> <?php for ($i = 1; $i <= 10; $i++) { if ($i % 2) { $color = '#FFFFCC'; } else { $color = '#CCCCCC'; } ?> <tr> <td bgcolor="<?php echo $color; ?>"><?php echo $i; ?></td> </tr> <?php } ?> </table> </body> </html>
This code displays different row colors depending on the value of $i. If $i is not divisible by two it prints yellow otherwise it prints gray colored rows.
Using Function
Real world applications are usually much larger than the examples above. It has been proven that the best way to develop and maintain a large program is to construct it from smaller pieces (functions) each of which is more manageable than the original program. A function may be defined using syntax such as the following: <?php function addition($val1, $val2) { $sum = $val1 + $val2; return $sum; } ?>
Using Default Parameters When calling a function you usually provide the same number of argument as in the declaration. Like in the function above you usually call it like this: $result = addition(5, 10);
But you can actually call a function without providing all the arguments by using default parameters. Example 17: default-param.php <?php function repeat($text, $num = 10) { echo "<ol>\r\n"; for($i = 0; $i < $num; $i++) { echo "<li>$text </li>\r\n"; } echo "</ol>"; } // calling repeat with two arguments repeat("I'm the best", 15); // calling repeat with just one argument repeat("You're the man"); ?>
Function repeat() has two arguments $text and $num. The $num argument has a default value of 10. The first call to repeat() will print the text 15 times because
the value of $num will be 15. But in the second call to repeat () the second parameter is omitted so repeat() will use the default $num value of 10 and so the text is printed ten times.
Returning Values Applications are usually a sequence of functions. The result from one function is then passed to another function for processing and so on. Returning a value from a function is done by using the return statement. Example 18: return.php <?php $myarray = array('php tutorial', 'mysql tutorial', 'apache tutorial', 'java tutorial', 'xml tutorial'); $rows = buildRows($myarray); $table = buildTable($rows); echo $table; function buildRows($array) { $rows = '<tr><td>' . implode('</td></tr><tr><td>', $array) . '</td></tr>'; return $rows; } function buildTable($rows) { $table = "<table cellpadding='1' cellspacing='1' border='1'>$rows</table>";
bgcolor='#FFCC00'
return $table; } ?>
You can return any type from a function. An integer, double, array, object, resource, etc.
Notice that in buildRows() we use the built in function implode(). It joins all elements of $array with the string '</td></tr><tr><td>' between each element. I also use the '.' (dot) operator to concat the strings. You can also write buildRows() function like this shown below: <?php ... function buildRows($array) { $rows = '<tr><td>'; $n = count($array); for($i = 0; $i < $n - 1; $i++) { $rows .= $array[$i] . '</td></tr><tr><td>'; } $rows .= $array[$n - 1] . '</td></tr>'; return $rows; } ... ?>
Of course it is more convenient if you just use implode(). Setting Up a Form Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial we will not go into depth in how to write your form but we will show you three of the main pieces of code you must know: <input type="text" name="thebox" value="Your Name">
Will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique. <textarea name="message"> Please write your message here. </textarea>
Will display a large scrolling text box with the text 'Please write your message here.' as default. Again, the name is defined and should be unique. <input type="submit" value="Submit">
This will create a submit button for your form. You can change what it says on the button by changing the button's value. All the elements for your form must be enclosed in the <form> tags. They are used as follows: <form action="process.php" method="post"> Form elements and formatting etc. </form>
The form's action tells it what script to send its data to (in this case it is process.php). The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark. It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser's address bar.
Getting the Form Information The next step is to get the data the form has submitted into your script so that you can do something with it. To get a variable which has been sent to a script using the POST method you use the following code: $variablename=$_POST['variable'];
which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename. This should be done for each variable you wish to use from your form (or URL).
Creating the Form to Mail Script We will show you how to use what you have learnt so far in this part to create a system which will e-mail a user's comments to you. Firstly, create this form for your HTML page:
<form action="mail.php" method="post"> Your Name: <input type="text" name="name"><br> E-mail: <input type="text" name = "email"><br><br> Comments<br> <textarea name="comments"></textarea><br><br> <input type="submit" value="Submit"> </form>
This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script: <?php function checkOK($field) { if (eregi("\r",$field) || eregi("\n",$field)){ die("Invalid Input!"); } } $name=$_POST['name']; checkOK($name); $email=$_POST['email']; checkOK($email); $comments=$_POST['comments']; checkOK($comments); $to="aerefre@yahoo.com"; $message="$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email"; if(mail($to,"Comments From Your Site",$message,"From: $email\n")) { echo "Thanks for your comments."; } else { echo "There was a problem sending the mail. Please check that you filled in the form correctly."; } ?>
Remember to replace aerefre@yahoo.com with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your comments form. The first part of that script may look a bit strange: function checkOK($field) { if (eregi("\r",$field) || eregi("\n",$field)){ die("Invalid Input!"); } }
You do not really need to worry about what this is doing, but basically, it stops spammers from using your form to send their spam messages by checking special characters are not present in the input which can be used to trick the computer into sending messages to other addresses. It is a function which checks for these characters, and if they are found, stops running the script. The lines: checkOK($name);
etc. run this check on each input to ensure it is valid.
The Mail Command Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows: mail($to,$subject,$body,$headers);
In this example we have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail. The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mail but you can also include other headers like cc and bcc.
Sending an e-Mail Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message: $to = "aerefre1@yahoo.com"; $subject = "PHP Is Great"; $body = "PHP is one of the best scripting languages around"; $headers = "From: teachlea@teachlearn-online.net\n"; mail($to,$subject,$body,$headers); echo "Mail sent to $to";
This code will actually do two things. Firstly it will send a message to aerefre1@yahoo.com with the subject 'PHP Is Great' and the text: PHP is one of the best scripting languages around and the e-mail will be from teachlea@teachlearn-online.net. It will also output the text: Mail sent to aerefre1@yahoo.com to the browser.
Formatting e-Mail Something you may have noticed from the example is that the From line ended with \n. This is actually a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered. The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.
Mail without Variables The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this: mail("aerefre1@yahoo.com","PHP Is Great","PHP is one of the best scripting languages around","From: teachlea@teachlearn-online.net\n"); But that would make your code slightly harder to read.
Error Control As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail
address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent: if(mail($to,$subject,$body,$headers)) { echo "An e-mail was sent to $to with the subject: $subject"; } else { echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid"; } This code is quite self explanatory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.
CHAPTER REVIEW
We have learned the basic PHP syntax. The examples shown are simple enough to be able to understand the PHP codes used in the discussions in the succeeding chapters. To know more of the PHP syntax, go to the PHP website: http://www.php.net/.
EXERCISES
Create small PHP codes similar to the examples shown in this chapter. Use the text editor Winsyntax in creating them. Give each a name with extension .php. Upload them to your web serverâ&#x20AC;&#x2122;s /www. Have each one of them launched by the browser (e.g. Mozilla Firefox). For additional exercises, go to the DrRefreâ&#x20AC;&#x2122;s Books: http://www.teachlearn-online.net/aerbooks/ .
CHAPTER 3 â&#x20AC;&#x201C; PHP with MySQL Tutorial
OVERVIEW If you would like to collect data via the web, simplify the maintenance of your website, or perhaps enrich the user experience of your site, you might need more than just a web site consisting of static pages. Using a database in conjunction with your web server, you can store similarly structured information (such as customer data, survey responses or contact information) in one place and automatically produce numerous web pages onthe-fly such as an employee directory or a web-based service request application. You can easily reuse certain data in different places (e.g. have a listing of all employees along with separate home pages for each employee) while keeping the maintenance effort low. Once your website needs a redesign you will only have to change one template file rather than a myriad of pages.
What is this Tutorial about? This tutorial explains the basic concepts behind database-driven websites, often also referred to as web applications. Using the popular server-side-language PHP and the database MySQL, we will show how to implement core dynamic features such as collecting data, storing data in a database, searching a database, or validating user inputs. Throughout the tutorial we use the particular example of a web-based personal address book to illustrate the ideas. We use the free web hosting service you got from the suggestion in Chapter 1. This tutorial assumes good knowledge of basic web concepts such as web pages, links, publishing pages to a web server, and HTML (see Chapter 1). Although it would be helpful, it is not assumed that you have prior experience in computer programming beyond hand-coding in HTML.
A Birds-Eye View on Web Applications Web applications are by nature distributed applications. In particular, this means that one part of the application is executed on the web server while another runs on the client computer within a web browser window (see Figure 1).
Figure 1. A web browser requests a document from the web server. The web server parses and executes a PHP script which dynamically assembles the HTML code that is then sent back to the browser which renders the HTML code into a webpage. When the user types in a web address (URL=Uniform Resource Locator) and hits the enter key (or clicks on a link or chooses a bookmark), the web browser sends this address in a so-called HTTP request (HyperText Transfer Protocol) to the web server. If the web server receives a request for a static HTML file (typically indicated by a file name ending in .html or .htm) it merely locates the corresponding file on its hard drive and sends it back to the computer that had requested it. If the web server receives a request for dynamic files (often indicated by .php, .asp, .cfm, .jsp etc.), it does a little bit more before sending a response to the web browser.
The Web Browserâ&#x20AC;&#x2122;s Job The web browser is responsible for displaying the layout described by the HTML file it has received (this process is called "page rendering"). Once the web page is rendered on the screen the user can interact with it - click on links, fill in forms
etc. Since HTML alone provides only a crude level of interactivity (namely links, form elements, buttons and image maps), JavaScript was developed. JavaScript is a programming language which gives the web designer a number of options for creating sophisticated user interfaces (e.g., input validation, popup windows, and cascading menus). JavaScript code is often contained within an HTML file enclosed by the <script> tag. JavaScript is always executed by the web browser. The web server is fully ignorant about JavaScript (well, there is something like server-side JavaScript but let's not talk about it); it just serves up any HTML, JavaScript or pictures that have been requested without analyzing or executing any code. To further avoid confusion: Beyond its name, JavaScript has very little in common with Java, which is a programming language that is often used for programs (java servlets, java server pages) running on the web server as well as for highly-interactive (but sometimes slow and crash-prone) java applets running on the client computer. Therefore, when creating a mental map of web technologies, you better place JavaScript and Java in opposite corners.
The Web Servers Job So far, we have only discussed how a web server handles requests for static files (HTML pages, images, etc.). However, if we want to construct our web pages from data contained within a database, the web server will have to do some more work. If the web server receives a request for a dynamic file (indicated by a file ending .php and some others) the web server will locate the file on its hard drive and interpret (a.k.a. parse) and execute its contents. PHP is a programming language for creating dynamic web pages and is always executed on the web server (as opposed to the web browser on the client computer). Typically PHP commands output certain HTML code depending on user input or data read from a database etc. This resulting HTML code is then sent back to the web browser for rendering. This is best seen through a sample dynamic website we are going to work on in this tutorial.
The â&#x20AC;&#x153;MY PERSONAL ADDRESS BOOKâ&#x20AC;? Website As we go along in a step-by-step manner in building a simple Web-based Personal Address Book., we will learn more in detail the syntax of PHP as it works with the syntax of MySQL. Step 1 Getting Started Step 2 Setting Up the Web Server and Database Step 3 Connecting to the Database and Querying it Step 4 Listing Contacts
Step 5 Adding Contacts Step 6 Editing Contacts Step 7 Deleting Contacts Step 8 Putting All Together
Step 1 Getting Started Go to http://aerefre.awardspace.info/ and you will see the following Web page:
Figure 2. The Website: http://aerefre.awardspace.info/ The corresponding page source is the index.html. Open this html file using the Winsyntax text editor or on your browser, just click on the View Menu -> Source. The following shows an excerpt where the My Address Book Content Management System link is explicitly shown: ---------<div class="navigation"> <h2>My Address Book</h2> <ul>
<li><a href="cms/index.php" target="_blank">Content Management System</a></li> <li>&nbsp;</li> </ul> <img border="0" alt="ICT" src="images/technology.jpg"> <img border="0" alt="Keyboard" src="images/keyboard01.gif"> <p align="center"><img border="0" src="images/gears.gif" width="93" height="70"> Powered by Me </div> ------------Figure 3. An excerpt from index.html Take particular note of <li><a href="cms/index.php" target="_blank">Content Management System</a></li>. When you click the link, a new browser page is launched showing the index.php in the cms folder as illustrated in the following:
Figure 4. The rendered HTML of http://aerefre.awardspace.info/cms/index.php An excerpt from this index.php and the login.php show what page will be launched by the browser if the login is successful: <tr> <td width="100%" bgcolor="#F3F3F3"> <FORM ENCTYPE="multipart/form-data" METHOD="POST"
ACTION="login.php"> <table border="0" width="100%" cellspacing="0" cellpadding="8"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"> Please provide User Name and Password nformation to access the CMS. </font></td> </tr> <tr> <td width="100%"><font color="#000000" face="Verdana" size="1"><b>&nbsp;</b></font></td> </tr> <tr> <td width="100%"> <font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"> <b>User Name</b> </font></td> </tr> <tr> <td width="100%"><input type="text" name="cm_usrnam" size="21"></td> </tr> <tr> <td width="100%"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <tr> <td width="100%"><b><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">Password</font></b></td> </tr> <tr> <td width="100%"><input type="password" name="cm_usrpas" size="21"></td> </tr>
<tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <?php if ($vAccess == 'invalid') { print "<td width='100%'><p align='center'><b><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>Invalid User!</font></b></td>"; } else { print "<td width='100%'><p align='center'><b><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>&nbsp;</font></b></td>"; } ?> </tr> </table> </td> </tr> <tr> <td width="100%"> <p align="center"><input type="submit" value="Submit" name="B1">&nbsp; <input type="reset" value="Reset" name="B2"> </td> </tr> </table> </td> </tr> </table> </FORM> </td> </tr> Figure 5. an excerpt from index.php:
<?php session_start(); session_register("cm_user"); session_register("cm_passwd"); session_register("cm_usridno"); session_register("cm_userrights"); session_register("TodayDate"); session_register("cm_LastName"); session_register("cm_FirstName"); session_register("cm_MiddleName"); session_register("cm_UserName"); session_register("cm_UserPic"); session_register("cm_postdate"); session_register("PlDate"); session_register("PlDateTime"); session_register("ForumDate"); session_register("timeadjust"); session_register("vAccess"); $hourdiff = "15.5"; // hours difference between server time and local time $timeadjust = ($hourdiff * 60 * 60); // time adjustment $melbdate = date("Y-m-d h:i a",time() + $timeadjust); // displays common time with am pm $PlDateTime = date("Y-m-d H:i:s",time() + $timeadjust); // displays military time $TodayDate = date("l, j F Y",time() + $timeadjust); $dr_postdate = date("l, j F Y h:i a",time() + $timeadjust); $PlDate = date("Ymd",time() + $timeadjust); $ForumDate = date("j F Y h:i a",time() + $timeadjust); require "common.inc.php"; require "functions.php"; $cm_user = $cm_usrnam; $cm_passwd = $cm_usrpas; if (authenticateUser($cm_usrnam, $cm_usrpas)) {
require "db_connect.php"; $sql1 = "SELECT userid, username, password FROM admin WHERE username = '$cm_user' AND password = '$cm_passwd'"; $result1 = mysql_query($sql1) or die("Couldn't execute login query2."); $num = mysql_num_rows($result1); while($e_row = mysql_fetch_row($result1)) { $cm_usridno = $e_row[0]; } $vAccess = "success"; header("Location:main.php"); exit(); } else { $vAccess = "invalid"; header("Location:index.php"); exit(); } ?> Figure 6. The login.php If the login is successful, the browser will launch the page corresponding to main.php as in the following:
Figure 7. The rendered HTML of the main.php We used a MySQL database with just two tables. We used simple PHP scripts, HTML, and Javascripts. We applied the well-known principle of â&#x20AC;&#x153;learning by doing.â&#x20AC;? As suggested in Chapter 01, we made use of the platform of the free web hosting from http://www.awardspace.com/ . Step 2 Setting Up the Web Server and Database NOTE: If you have done the setting up of the web server and database in Chapter 01, there is no need of doing it again this time; skip it. As the name suggests, databases store data persistently. A database is a piece of software which often runs on the same physical computer as the web server. In larger installations a database can also run on one or more dedicated machines that communicate with the web server. The web browser never directly communicates with a database but only with the web server, which in turn talks to the database. A PHP script sends or receives data and creates an HTML page containing the results which are sent back to the web browser (see Figure 1).
There are many different database software packages available today. Perhaps, the most popular of them is Microsoft Access. Although Access is a powerful and easy-to-use desktop database it is rather ill-suited for use with web applications (performance and concurrent access are the major issues). In the following we will focus on the use of MySQL, a widely-used open-source database. MySQL is available for free under several different license agreements. Many web hosting services, e.g. awardspace.com, make a working MySQL installation available to their clients, therefore you are often spared the effort of installing the MySQL software yourself. In order to administer the database (set up data structures etc.), you can either use its command-line-based user interface or a more easy-to-use third-party tools such as the freely-available and quite popular phpMyAdmin. As the name suggests, phpMyAdmin is itself a PHPbased web application and also is offered preconfigured by many web hosting services. However, if you have average sysadmin skills, you can install phpMyAdmin yourself within a couple of minutes. Many more MySQL administration tools are available on the market underlining the popularity of this database software. Preparing a MySQL database All of the steps described below can be accomplished by using the phpMyAdmin software. Before you can store any data you need a database. An installation of MySQL can host a large number of individual databases. Most likely your web hosting service has already created a database for you. If not, create one using phpMyAdmin in the cPanel. Most modern databases store data in so-called tables which you can picture as being similar to a spreadsheet. Each table has columns (e.g. id, first name, last name, phone) and rows (e.g. one customer's data). Record is another word for row. Figure 2 shows an example. Basic web applications may get along with using just one table whereas more complex ones may require a multitude. For example you may want to store customer information in one table, supplier information in another, and orders in a third table. In practice the so-called database-schema (layout) can become quite complex.
Figure 8: A sample screenshot from phpMyAdmin listing the table contacts of the My Personal Address Book Website Using a tool such as phpMyAdmin you can create a database schema without having to know much about databases. However, the lingua-franca of databases is SQL (Structured Query Language; often pronounced like "sequel"). This standard allows application developers to communicate with any compliant database without having to learn product-specific features; at least that is the theory. In practice, almost all databases deviate somewhat from this standard (mostly to offer additional features) which can complicate your life as a web application developer. However, if you stick to the basics, things work fine most of the time. SQL defines a syntax for creating tables, inserting, updating, deleting data or querying (a.k.a. selecting) data. Figure 3 shows some simple examples. Note that SQL commands are case-insensitive and also quite indifferent to superfluous spacing and new lines. When defining the field names (firstname, phone etc.) case often does matter. It is strongly recommended that you use the exact same spelling for the database field names as you use for naming the HTML form elements and the PHP variables. Let us get into the habit of using all lowercase, words run-together identifiers (such as "yearofbirth"). There are many other naming schemes; it just matters that you stick to one. CREATE TABLE contacts ( id int NOT NULL auto_increment, firstname char(40) NOT NULL,
lastname char(40) NOT NULL, phone char(20), email char(40), address text, category char(20), yearofbirth int DEFAULT '0', private tinyint DEFAULT '0', PRIMARY KEY (id) ); INSERT INTO contacts (firstname, lastname, phone, email, address, category, yearofbirth, private) VALUES ('Joe', 'Doe', '(991) 983-3134', 'joe@mail.com', '123 Main Street\nBlackburg\nVA 24060', 'business', 1974, 1); UPDATE contacts SET lastname = 'Smith' WHERE id = '2'; DELETE FROM contacts WHERE id=2; SELECT * FROM contacts ORDER BY lastname;
Figure 9: The five most basic SQL commands: create, insert, update, delete, select Instead of using the foregoing scripts in creating a database and its tables, simply use our chosen web host cPanel’s MySQL Manager section to create the database and its tables.You have set up the database and its tables in Chapter 01. Step 3 Connecting to the Database and Querying it The only way a web application can communicate with a database is through code running on the web server (like a PHP script). Before a PHP script can receive or send data from or to a database, it needs to establish a so-called connection. In practice this comes down to just two lines of PHP code you will have to insert once in every script that needs to communicate with the database. Figure 9 shows a typical code which will be used as “require” in all the scripts connecting to the database in this tutorial. As you can see in Figure 9, a variable called $dbname is initialized which later will be used to "represent the database" (I wouldn't worry about the details). Note that the PHP code contains such sensitive information as the database user-ID and password. Make sure that only authorized persons can view your PHP code. Otherwise, you expose your data to a huge security risk. By placing the database connection information in a separate file (db_connect.php), we gain the advantage of having to update only one file in case something changes.
NOTE: All the codes you see in here are found in the addrbook.zip you unzipped in Chapter 01. Open each of the html and PHP files in the text editor winsyntax to see if it compares correctly with the printouts in here. <?php require "common.inc.php"; $connection = mysql_connect($hostname, $username, $password) or die ("Couldn't connect to server."); $db = mysql_select_db($dbname) or die ("Couldn't select database."); ?>
Figure 10: The db_connect.php in the cms folder. This file sets up the database connection <?php // YOUR MYSQL SERVER PARAMETERS $hostname = "fdb2.awardspace.com"; $username = "givenbyhost"; // replace givenbyhost with the username given by 000webhost.com $password = "youcreated"; // replace the password chosen by the user // YOUR MYSQL DATABASE the one you created; e.g. (username)_addrbook $dbname = " givenbyhost "; // replace givenbyhost with the username given by 000webhost.com // TABLES $contact_profile = "contacts"; $contact_admin = "admin" ?> Figure 11: The common.inc.php in the cms folder. This file is inserted into the db_connect.php code.
The foregoing codes are included in all other scripts needing to connect to the database. Figure 12 shows an excerpt of main.php illustrating how a database is queried for information. The first line of PHP code sets up a database connection.
The overall purpose of this PHP script is to list all names in tabular format. The header of the table is defined in regular HTML. The rows showing the individual names are produced by the PHP code which first sends a SQL query to the database, and then iterates over all of the records that have been returned. The variable $result1 holds a reference to all of the returned data. Each returned row of data (or record) has a number associated with it (starting at 0, not 1). Using a while-loop, we fetch one record at a time and put the fieldsâ&#x20AC;&#x2122; values in an array. ---------<tr> <td width="99%"> <table border="0" width="100%" cellspacing="1" cellpadding="4"> <tr> <td width="30%" bgcolor="#000000" colspan="2"> <table border="0" width="100%" cellspacing="0"> <tr> <td width="100%"> <p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt"> Name of Contact</font></b></font> </td> </tr> </table> </td> <td width="7%" bgcolor="#000000" align="center"><p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt">Gender</font></b></font></td> <td width="24%" bgcolor="#000000" align="center"><p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt">EmailAddress</font></b></font></td> <td width="15%" bgcolor="#000000" align="center"><p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt">Phone</font></b></font></td> <td width="13%" bgcolor="#000000" align="center"><p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt">Category</font></b></font></td> <td width="10%" bgcolor="#000000" colspan="2"><p align="center"><font face="Zurich BT,Arial" color="#FFFFFF"><b><font style="font-size: 8pt">Operation</font></b></font></td> </tr> <?php require "common.inc.php"; require "db_connect.php"; $sql_select = "SELECT userid, lastname, firstname, midname, gender, email, phone, category FROM contacts ORDER BY lastname DESC";
$Result = mysql_query($sql_select) or die("Couldn't execute query operation."); $Cnt = 0; $Row = 1; while($Applicant = mysql_fetch_row($Result)) { $MemberID = $Applicant[0]; $MemberLName = $Applicant[1]; $MemberFName = $Applicant[2]; $MemberMName = $Applicant[3]; $MemberGender = $Applicant[4]; $MemberEmail = $Applicant[5]; $MemberPhone = $Applicant[6]; $MemberType = $Applicant[7]; $MemberName = strtoupper($MemberLName).", ".strtoupper($MemberFName)." ".strtoupper(substr($MemberMName,0,1)); $Cnt = $Cnt + 1; if ($Row == 1) { $bkgrnd = "#E1F9FF"; $Row = $Row + 1; } else { $bkgrnd = "#FFFFFF"; $Row = 1; }
print "<tr>"; print "<td width='3%' bgcolor='$bkgrnd'><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>$Cnt.</font></td>"; print "<td width='27%' bgcolor='$bkgrnd'><a href='profile.php?MemberID=$MemberID'><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>$MemberName</font></a></td>"; print "<td width='7%' bgcolor='$bkgrnd' align='center'><font style='fontsize: 8pt' color='#000000' face='Zurich BT,Arial'>$MemberGender</font></td>"; print "<td width='24%' bgcolor='$bkgrnd' align='center'><p align='center'><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>$MemberEmail</font></td>"; print "<td width='15%' bgcolor='$bkgrnd' align='center'><p align='center'><font style='font-size: 8pt' color='#000000' face='Zurich BT,Arial'>$MemberPhone</font></a></td>"; print "<td width='13%' bgcolor='$bkgrnd' align='center'><font style='fontsize: 8pt' color='#000000' face='Zurich BT,Arial'>$MemberType</font></td>"; print "<td width='5%' bgcolor='$bkgrnd' align='center'><a href='profile.php?MemberID=$MemberID'><img border='0' src='images/button_view.png'></a></td>"; print "<td width='5%' bgcolor='$bkgrnd' align='center'><a
href='usr_opt.php?MemberID=$MemberID&option=DelApplicant'><img border='0' src='images/button_drop.png'></a></td>"; print "</tr>"; } ?> </table> </td> <td width="1%"><img border="0" src="images/spcr7.gif"></td> </tr> ----------
Figure 12: An excerpt from main.php: PHP code that queries a database and displays the results in a HTML table. Take note of the require statement that inserts the common.inc.php and the db_connect.php into the code. It has similar function to include (see the PHP Reference Manual for the difference between include and require) Step 4 Listing Contacts The rendered HTML of the main.php will be like the following view in browser:
Figure 13. The rendered HTML of the main.php Step 5 Adding Contacts When the link Add Contact is clicked, a browser will be launched showing the rendered HTML of the addcontact.php:
<html> <head> <title>Add a Contact</title> </head> <SCRIPT language=JavaScript> function isEmail(str) { var supported = 0; if (window.RegExp) { var tempStr = "a"; var tempReg = new RegExp(tempStr); if (tempReg.test(tempStr)) supported = 1; } if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0); var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)"); var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[09]{1,3})(\\]?)$"); return (!r1.test(str) && r2.test(str)); } </script> <script language="JavaScript" type="text/javascript"> function checkform ( form ) { if (form.vlastname.value == "") { alert("Please enter Last Name." ); form.vlastname.focus(); return false ; } else if (form.vfirstname.value == "") { alert("Please enter First Name." ); form.vfirstname.focus(); return false ; } else if (form.vmidname.value == "") { alert("Please enter Middle Name." ); form.vmidname.focus(); return false ; } else if (form.vemail.value == "") { alert("Please enter your valid Email Address." ); form.vemail.focus(); return false ; } else if (!isEmail(form.vemail.value)){ alert ("Invalid e-mail address."); form.vemail.focus(); return false ;
} else { return true ; } } </script> <body> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <FORM ACTION="usr_opt.php" METHOD="POST" onsubmit="return checkform(this);"> <?php $option = "membership_add"; ?> <tr> <td width="100%" bgcolor="#C0C0C0"> <table border="0" cellpadding="3" width="100%" cellspacing="1"> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="2">Personal Information</font></b></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Last Name</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vlastname" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;First Name&nbsp;</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vfirstname" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Middle Name</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vmidname" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Contact Category</font></td> <td width="66%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr> <td width="2%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" name="vcategory"></font></td> <td width="10%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Relative</font></td> <td width="2%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" name="vcategory"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Friend</font></td> </tr> </table> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Gender</font></td> <td width="66%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="2%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" name="vgender"></font></td> <td width="10%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Male</font></td> <td width="2%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Female</font></td> </tr> </table> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Year of Birth</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vyearofbirth" value="<? echo "1980"; ?>" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Valid Email<br> Address</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vemail" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Home Address (No. and Street)&nbsp;</font> </td>
<td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vaddress" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Tel. No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vphone" size="48"></font></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"> <p align="center"><input type="submit" value="Submit" name="B1">&nbsp;&nbsp; <input type="reset" value="Reset" name="B2"></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> </table> </td> </tr> </FORM> </table> </body> </html>
Figure 14. The addcontact.php. Take note of the Javascript used for validating the userâ&#x20AC;&#x2122;s input in the form. When the submit button of the form is clicked, the usr_opt.php is triggered. The portion of the usr_opt.php that deals with the addition of data (inserting a record) is the following: <?php require "common.inc.php"; require "db_connect.php";
$hourdiff = "15.5"; // hours difference between server time and local time
$timeadjust = ($hourdiff * 60 * 60); // time adjustment $PlDateTime = date("Y-m-d H:i:s",time() + $timeadjust); // displays military time $PlDate = date("Y-m-d",time() + $timeadjust); // displays date
if ($option == 'membership_add') { $sql_select = "SELECT userid FROM contacts"; $sql_result = mysql_query($sql_select) or die("Couldn't execute query operation."); $vIdNo = mysql_num_rows($sql_result); $vIdNo = $vIdNo + 1; $vMemberID = "CONTACT-".date("YmdHis")."-".$vIdNo; $RawUserPasswd = explode("-",$vMemberID); $UsrPass1 = $RawUserPasswd[0]; $UsrPass2 = substr($RawUserPasswd[1],10,5); $UsrPass3 = $RawUserPasswd[2]; $UserPasswd = $UsrPass2."-".$UsrPass3; if ($vgender == 1) { $vgender = "Male"; } else { $vgender = "Female"; } if ($vcategory == 1) { $vcategory = "Relative"; } else { $vcategory = "Friend"; } $sql_insert = "INSERT INTO contacts (userid, password, lastname, firstname, midname, gender, phone, email, address, category, yearofbirth) values ('$vemail', '$UserPasswd', '$vlastname', '$vfirstname', '$vmidname', '$vgender', '$vphone', '$vemail', '$vaddress', '$vcategory', '$vyearofbirth')"; mysql_query($sql_insert) or die("Couldn't execute insert operation"); header("Location:main.php"); exit(); …………
Figure 15. an excerpt from usr_opt.php
The rendered HTML of the addcontact.php will be like the following view in browser:
Figure 16. The rendered HTML of addcontact.php
Step 6 Editing Contacts When the listed name of a contact is clicked, the profile.php will be executed. The following excerpt from profile.php shows how the form for editing is created: <tr> <td width="99%"> <div align="center"> <center> <table border="0" cellpadding="0" width="75%" cellspacing="0"> <FORM ACTION="usr_opt.php" METHOD="POST" onsubmit="return checkform(this);"> <tr> <td width="100%" bgcolor="#000000"> <table border="0" cellpadding="3" width="100%" cellspacing="1"> <?php require "common.inc.php"; require "db_connect.php";
$Sql_Select = "SELECT userid, lastname, firstname, midname, gender, email, phone, category FROM contacts WHERE userid = '$MemberID'"; $Sql_Result = mysql_query($Sql_Select) or die("Couldn't execute query."); while($MemProfile = mysql_fetch_row($Sql_Result)) { $MemID = $MemProfile[0]; $MemLName = $MemProfile[1]; $MemFName = $MemProfile[2]; $MemMName = $MemProfile[3]; $MemGender = $MemProfile[4]; $MemEmail = $MemProfile[5]; $MemPhone = $MemProfile[6]; $MemCategory = $MemProfile[7]; } if ($MemCategory == 'Relative') { $vChecked1 = "checked"; } else { $vChecked2 = "checked"; } if ($MemGender == 'Male') { $vChecked3 = "checked"; } else { $vChecked4 = "checked"; } $option = "ModProfile"; ?> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="3">Personal Information</font></b></td> </tr> <tr> <td width="25%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Last Name</font></td> <td width="75%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="MemLName" value="<? echo $MemLName; ?>" size="48"></font></td> </tr> <tr> <td width="25%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; First Name&nbsp;</font></td> <td width="75%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="MemFName" value="<? echo $MemFName; ?>" size="48"></font></td> </tr> <tr>
<td width="25%" bgcolor="#FFFFFF" align="right"><font style="FONTSIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Middle Name</font></td> <td width="75%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="MemMName" value="<? echo $MemMName; ?>" size="48"></font></td> </tr> <tr> <td width="25%" bgcolor="#FFFFFF" align="right"><font style="fontsize: 8pt" face="Arial" color="#808080"> Category &nbsp;</font> </td> <td width="75%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" <? echo $vChecked1; ?> name="vcategory"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Relative</font></td> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" <? echo $vChecked2; ?> name="vcategory"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Friend</font></td> </tr> </table> </td> </tr> <tr> <td width="25%" bgcolor="#FFFFFF" align="right"><font style="FONTSIZE: 8pt" face="Arial" color="#808080">Gender</font> </td> <td width="75%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" <? echo $vChecked3; ?> name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Male</font></td> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" <? echo $vChecked4; ?> name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Female</font></td> </tr> </table> </td> </tr>
<tr> <td width="25%" bgcolor="#FFFFFF" align="right"><font style="FONTSIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Email Address</font> </td> <td width="75%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="MemEmail" value="<? echo $MemEmail; ?>" size="48"></font></td> </tr> <tr> <td width="25%" bgcolor="#FFFFFF" align="right"><font style="FONTSIZE: 8pt" face="Arial" color="#808080">Contact Phone&nbsp;</font> </td> <td width="75%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="MemPhone" value="<? echo $MemPhone; ?>" size="48"></font></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <input type="hidden" name="MemID" value="<? echo $MemID; ?>"> <tr> <td width="100%" bgcolor="#000000" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="2"> <p align="center"><input type="submit" value="Submit Changes" name="B1">&nbsp;&nbsp; <input type="reset" value="Reset" name="B2"></td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> </table> </td> </tr> </FORM> </table> </center> </div> </td> <td width="1%"></td> </tr>
Figure 17. an excerpt from profile.php The rendered HTML of the profile.php is as shown in the following:
Figure 18. The rendered HTML of profile.php When the Submit Changes button is clicked, the following excerpt from usr_opt.php is executed: --------} else if ($option == 'ModProfile') {
if ($vgender == 1) { $vGender = "Male"; } else { $vGender = "Female"; } if ($vcategory == 1) { $MemCategory = "Relative"; } else { $MemCategory = "Friend"; } $UPDATE_Prof = "UPDATE contacts SET lastname='$MemLName', firstname='$MemFName', midname='$MemMName',
gender='$vGender', phone='$MemPhone', email='$MemEmail', category='$MemCategory' WHERE userid = '$MemID'";
mysql_query($UPDATE_Prof) or die("Couldn't execute update query.");
header("Location:main.php"); exit(); ---------
Figure 19. an excerpt from usr_opt.php The view in browser after the execution of the profile.php and usr_opt.php will be the rendered HTML of main.php. Step 7 Deleting Contacts When the trash can icon of the table of list of contacts is clicked, the following excerpt from usr_opt.php is executed: ---------} else if ($option == 'DelApplicant') {
$Del_Member = "DELETE FROM contacts WHERE userid = '$MemberID'"; mysql_query($Del_Member) or die("Couldn't execute delete operation."); header("Location:main.php"); exit(); ----------
Figure 20. an excerpt from usr_opt.php that deletes the chosen contact.
Step 8 Putting it All Together The web-based My Address Book Content Management System is an example for a basic web application, that collects data (add a Contact), updates data (edit a Contact), deletes data (delete a Contact) and queries data (lists all contacts) in the database. Five PHP scripts, each implementing a distinct functionality, comprise the web application. Figure 20 lists the task each of the scripts performs. dbconnect.php Connects to the database main.php
Queries the database for all names; depending on the sort variable, the rows are sorted by last name; outputs a table with all data.
addcontact.php Collects user input and submits it to itself; validates that at least a first and last name have been entered; displays error messages if data is missing; if data is complete it is added to the database; profile.php
Structurally almost identical to addcontact.php with the difference that it pre-fills the form with the data that is already in the database; the record number is indicated by the variable $userid which is passed to it.
Usr_opt.php
Depending on the option chosen, it adds, modify, or deletes the data record whose id number is equal to the one passed to the script in the variable $userid Figure 21. The task of each of the five PHP scripts. These are assembled all together in the web serverâ&#x20AC;&#x2122;s subdomain folder. Go to http://aerefre.awardspace.info/cms/index.php to see the full functionality of the My Address Book Content Management System. Advanced Server-Side Scripting Because they mix HTML, JavaScript, Style-sheets and code fragments, PHP scripts can quickly become messy and therefore hard-to-maintain. Try to modularize the functionality of your application and avoid having one script doing too many tasks at once. We typically use a separate PHP file per function. A frequent exception to this rule-of-thumb is combining the add and edit script. Although this leads to longer and harder-to-understand code, it has the advantage that you maintain the layout of the input form in only one place. Imagine you had to add a new field like birthday to the HTML form. If you have two separate files you will have to make the same change twice. If you have only one, you have to do less work.
Another way of modularizing your code is to put frequently-used functionality into self-defined PHP functions. As you have seen before, you can even place PHP statements (and functions) into a separate PHP file and include them using the require or include statement. All this can help to your code shorter, cleaner, easier-to-maintain and more secure. PHP can do many more things than just printing out HTML and communicating with a database (like reading and writing files, creating images on-the-fly, parsing XML, fetching contents from remote servers etc.). It would go beyond the intentions for this tutorial to show all its power. However, we want to at least briefly describe how to implement a login-protected website and how to send emails from within PHP.
Sending e-Mails Using PHP's mail function you can send e-mails from within a script. Figure 16 shows an example script that takes the input from an HTML form and sends it in an e-mail to all the contacts. At the first invocation, the script presents the user with a registration form. When the user clicks on "Submit", the data is sent back to the same script ($_SERVER['PHP_SELF']). If the user fills in all three input fields, the information is send to the registration administrator with the email address myname@mydomain.com. The resulting e-mail message will contain 5 lines (one blank) of text. To indicate a line ending, use the new line code \n. <tr> <td width='100%' background='images/cms_menu_itm1.gif'> <table border='0' width='100%' cellspacing='0' cellpadding='0'> <tr> <td width='2%'><img border='0' src='images/cms_menu_itm_bkg.gif' width='9' height='25'></td> <td width='98%'><b><a href='javascript:messages()'><font style='font-size: 8pt' face='Zurich BT,Arial' color='#FFFFFF'>Send Message to All</font></a></b></td> </tr> </table> </td> </tr>
Figure 22. an excerpt from menu.php <script> function messages() { url = "messages.php"; var dummy = window.open(url,"Send Message","width=520,height=320,scrollbars=yes"); } </script>
Figure 23. an excerpt from main.php
<?php
session_start(); require "functions.php";
if (!authenticateUser($cm_user, $cm_passwd)) { header("Location:index.php"); exit(); }
?> <html>
<head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <title>Send Message</title> </head> <script language="JavaScript" type="text/javascript"> function checkform ( form ) { if (form.vSubject.value == "") { alert("Please enter Subject of this Message." ); form.vSubject.focus();
return false ; } } </script> <body topmargin="10" leftmargin="10">
<table border="0" width="100%" bgcolor="#C1C100" cellspacing="0" cellpadding="2"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="8"> <tr> <td width="100%" bgcolor="#FFFFFF"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <FORM ACTION="usr_opt.php" METHOD="POST" ENCTYPE="multipart/form-data" onsubmit="return checkform(this);"> <tr> <td width="100%" bgcolor="#E8E8E8"> <table border="0" width="100%" cellspacing="1" cellpadding="4"> <tr> <td width="100%" bgcolor="#FFFFFF" colspan="2" background="images/cms_bar.gif"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%"><font face="Arial"><b>Send Message to Members</b></font></td> </tr> </table>
</td> </tr> <tr> <td width="23%" bgcolor="#FFFFFF" valign="top"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">From</font></td> <td width="77%" bgcolor="#FFFFFF" valign="top"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"> Portal Administrator &lt;aerefre@gmail.com&gt;</font></td> </tr> <tr> <td width="23%" bgcolor="#FFFFFF"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">Subject</font></td> <td width="77%" bgcolor="#FFFFFF" valign="top"> <input type="text" name="vSubject" size="52"> </td> </tr> <tr> <td width="100%" bgcolor="#E8E8E8" valign="top" colspan="2"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"><b>Send Message</b></font></td> </tr> <tr> <td width="23%" bgcolor="#FFFFFF" valign="top"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">Message</font></td> <td width="77%" bgcolor="#FFFFFF" valign="top"><textarea rows="6" name="vMessage" cols="38"></textarea></td> </tr> <input type="hidden" name="option" value="SendMess"> <tr>
<td width="100%" bgcolor="#FFFFFF" valign="top" colspan="2"> <table border="0" width="100%" cellspacing="0" cellpadding="5"> <tr> <td width="100%" bgcolor="#E8E8E8"> <p align="center"><input type="submit" value="Send Message" name="B1"></td> </tr> </table> </td> </tr> </table> </td> </tr> </FORM> </table> </td> </tr> </table> </td> </tr> </table> </body> </html>
Figure 24. messages.php Execution of the foregoing script launches the following rendered HTML:
Figure 25. The rendered HTML of messages.php As soon as the Send Message button is clicked, the following portion of the usr_opt.php is executed: ----------} else if ($option == 'SendMess') { $subject = $vSubject; $email_message = $vMessage; $Sql_Select = "SELECT userid, email FROM contacts"; $Sql_Result = mysql_query($Sql_Select) or die("Coudln't execute query."); while($SendEmail = mysql_fetch_row($Sql_Result)) { $MemID = $SendEmail[0]; $MemEmail = $SendEmail[1]; $toAddress = $MemEmail; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: The Portal Administrator <aerefre@gmail.com>\r\n"; $headers .= "Cc: aerefre@gmail.com\r\n"; mail($toAddress, $subject, $email_message, $headers); } header("Location:sent.php"); exit(); ----------
Figure 26. an excerpt from usr_opt.php Security Considerations Disclaimer: Even if you follow all the guidelines below you should not assume that your application is 100% secure. New security vulnerabilities are uncovered daily and the only workable approach is to stay vigilant and to reassess your applications periodically. Unfortunately, this means "extra work". According to an "old" saying, the only truly-secure web application runs on a server which is located in a bomb/earthquake/flood/you-name-it-safe room, protected by plenty of guards and not connected to any type of computer network. In other words, no usable service can be 100% secure. However, by following a couple of guidelines you can reduce the risk of falling victim to an attack.
Risks Why care about security? The risks of a security breach can be manifold and may range from de-facement (someone posts inappropriate messages on your website), data theft (hopefully you don't collect social security or credit card numbers), data integrity issues (modification or deleting of your data), to misuse of your computing resources (someone uses your computer to hack someone else's).
Sources of Vulnerabilities Web applications are vulnerable to attacks on many different levels. Perhaps, the most obvious way to compromise a web application is to hack the web server it is running on. Make sure, your web server's operating system, and server software is appropriately configured and patched. This is quite time-consuming
and far from trivial. If you are not an expert system administrator, consider hosting your website on a server that is professionally administered. Related and often forgotten are the risks to physical integrity. If someone steals the server that is located under your desk, you would lose not only the hardware but also all your data. A caring coworker who unintentionally waters not only your plants but also your webserver may have have a similar effect - another good reason to host your website in a protected and well-managed environment as you would get if you use a professional web hosting service. Another rather obvious security breach is if the attacker gets hold of the userID/password combination that you use to login to the webserver and edit the web application. Therefore, keep your password non-trivial and safe. The latter is difficult if you use un-encrypted data-transfer protocols such as FTP. A malicious person could potentially capture your password by eavesdropping on the network. SFTP, FTP over SSL, or WebDAV over SSL are more secure alternatives. While on the topic of passwords... Make sure to hide your database password. It is quite easy to accidentally expose vital database connection information by putting it in a PHP script. If, for some reason (e.g. wrong file extension), the webserver does not execute your PHP script, it may arrive in cleartext at the user, exposing passwords and other "useful" information. Less obvious are vulnerabilities due to the way the web as a whole and PHP in particular functions. It is quite easy to accidentally write insecure PHP code (the same is true in varying degrees for other technologies such as Java, ColdFusion or ASP). One feature that makes PHP well-suited for beginners is the automatic registration of POST/GET/Cookie/Environment variables. If your web server's PHP installation enables the option register_globals then PHP automatically creates variables with names matching those of your HTML form elements. For example, you could use $phone without having to first get its value assigned from $_POST['phone']. While this is handy it also creates some security risks (as you can read about in the documentation to register_globals). Therefore, whether or not your webserver enables this directive, you should always explicitly initialize variables at the beginning of your PHP script, e.g. $authorized = false;. Also, in order to ensure that your PHP code runs on any other webserver (you may switch servers at some point), you should stick with explicitly assigning form variables, e.g. $phone = $_POST['phone']. An even bigger danger to the integrity of your data are un-checked user inputs. Do not trust any user input - check all inputs. This includes forms inputs (post/get method), parameters that are passed via a hyperlink link (get method), browser cookies, and even automatically-assigned (and fake-able) environment
variables such as browser-ID or referer information. If you want a user to enter a ZIP code then validate the input you receive from the form before you store it in your database (you could check easily whether the input is a number between 10000 and 99999). Input validation not only protects you from risks such as crosssite scripting (a risk to your users) or SQL injection (a risk for your data) but also helps users catch mistakes. In conclusion, we recommend that you do not feel too comfortable about the security of your web application. Be particularly vigilant when collecting sensitive information such as social security or credit card numbers or avoid it altogether. Even websites as famous and well-managed as Amazon have fallen victim to data theft.
Authentication and Authorization Authentication is making sure that a person is who they claim to be. A typical way of ensuring authenticity is requesting some user-ID and password. Authorization determines whether or not a certain person (or group of people) should have access to certain resources. Users may authenticate via an HTML form that asks for their user-ID and password. For security reasons always use the post method for sending the form to the server. Figure 27 shows a simple login script. <?php session_start(); session_register("cm_user"); session_register("cm_passwd"); session_register("cm_usridno"); session_register("cm_userrights"); session_register("TodayDate"); session_register("cm_LastName"); session_register("cm_FirstName"); session_register("cm_MiddleName"); session_register("cm_UserName"); session_register("cm_UserPic"); session_register("cm_postdate"); session_register("PlDate"); session_register("PlDateTime"); session_register("ForumDate"); session_register("timeadjust"); session_register("vAccess"); $hourdiff = "15.5"; // hours difference between server time and local time $timeadjust = ($hourdiff * 60 * 60); // time adjustment
$melbdate = date("Y-m-d h:i a",time() + $timeadjust); // displays common time with am pm $PlDateTime = date("Y-m-d H:i:s",time() + $timeadjust); // displays military time $TodayDate = date("l, j F Y",time() + $timeadjust); $dr_postdate = date("l, j F Y h:i a",time() + $timeadjust); $PlDate = date("Ymd",time() + $timeadjust); $ForumDate = date("j F Y h:i a",time() + $timeadjust); require "common.inc.php"; require "functions.php"; $cm_user = $cm_usrnam; $cm_passwd = $cm_usrpas; if (authenticateUser($cm_usrnam, $cm_usrpas)) { require "db_connect.php"; $sql1 = "SELECT userid, username, password FROM admin WHERE username = '$cm_user' AND password = '$cm_passwd'"; $result1 = mysql_query($sql1) or die("Couldn't execute login query2."); $num = mysql_num_rows($result1); while($e_row = mysql_fetch_row($result1)) { $cm_usridno = $e_row[0]; } $vAccess = "success"; header("Location:main.php"); exit(); } else { $vAccess = "invalid"; header("Location:index.php"); exit(); } ?>
Figure 27. The login.php called by the login form of the index.php as shown in the following: <tr> <td width="100%" bgcolor="#F3F3F3"> <FORM ENCTYPE="multipart/form-data" METHOD="POST" ACTION="login.php"> <table border="0" width="100%" cellspacing="0" cellpadding="8">
<tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"> Please provide User Name and Password nformation to access the CMS. </font></td> </tr> <tr> <td width="100%"><font color="#000000" face="Verdana" size="1"><b>&nbsp;</b></font></td> </tr> <tr> <td width="100%"> <font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial"> <b>User Name</b> </font></td> </tr> <tr> <td width="100%"><input type="text" name="cm_usrnam" size="21"></td> </tr> <tr> <td width="100%"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <tr> <td width="100%"><b><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">Password</font></b></td> </tr> <tr> <td width="100%"><input type="password" name="cm_usrpas" size="21"></td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <?php if ($vAccess == 'invalid') { print "<td width='100%'><p align='center'><b><font style='fontsize: 8pt' color='#000000' face='Zurich BT,Arial'>Invalid User!</font></b></td>"; } else { print "<td width='100%'><p align='center'><b><font style='fontsize: 8pt' color='#000000' face='Zurich BT,Arial'>&nbsp;</font></b></td>"; } ?>
</tr> </table> </td> </tr> <tr> <td width="100%"> <p align="center"><input type="submit" value="Submit" name="B1">&nbsp; <input type="reset" value="Reset" name="B2"> </td> </tr> </table> </td> </tr> </table> </FORM> </td> </tr>
Figure 28. an excerpt from index.php The rendered HTML will be like the following view in browser:
Figure 29. the rendered HTML of index.php
The corresponding logout scripts are as in the following: <?php session_start(); $cm_user = ""; $cm_passwd = ""; $cm_usridno = ""; $cm_userrights = ""; $cm_UserName = ""; $cm_LastName = ""; $cm_FirstName = ""; $cm_MiddleName = ""; $cm_UserPic = ""; $vAccess = ""; session_destroy(); header("Location:index.php"); exit(); ?>
Figure 30. logout.php corresponding to the login.php When you click the Logout link, you get back to index.php. Preferably the user-ID/password combination should be checked against a database rather than being hard-coded into the script.
CHAPTER REVIEW We have learned in this chapter the use of some PHP scripts in combination with MySQL functions and embedded in HTML: 1. 2. 3. 4. 5.
for connecting to a MySQL database, collecting the data from the database and listing them out, adding data to the database, editing the data in the database, and deleting data in the database.
The foregoing are the basic processes going on in a database-driven dynamic website. Other processes and advanced techniques are considered in the following chapters.
EXERCISES
Re-work all the codes in this chapter to build a Classmates Website. For additional exercises, go to the DrRefreâ&#x20AC;&#x2122;s Books: http://www.teachlearnonline.net/aerbooks/ .
CHAPTER 4 â&#x20AC;&#x201C; The Design Layout of the Community Portal and the Database Structure OVERVIEW The Community Portal that we will develop makes use of the model patterned after the Tarlac High School Alumni Class 1957 Portal. We will modify it to suit our needs. We will change the header image of the Homepage to make it generally applicable to any High School Alumni. The Project Alumni Portal After some modifications, the project portal Homepage looks like this:
Description of the Portal Homepage The Homepage consists of the following rows of contents:
1. The image header (High School Alumni Class 2008). You can create this using Adobe Photoshop 7. Put your desired heading using a font you personally choose. 2. The bar consisting of links to specific webpage presenting the subject matter indicated. Development of this involves a lot of Javascript programming in presenting a new window of information. You do not have to this programming from scratch. There are lots of free scripts available from the Web. Use the Google search to look for these. 3. The third row from the top containing two columns (member login/join column and the splash image (map of the Philippines with THS Alumni Class 1957 group photo during their Golden Jubilee Homecoming). The member login involves authentication and validation using a database. As the member successfully logged in, a new page (member exclusive page) appears as shown in the following:
This member exclusive page authorizes the member to upload and share documents, update the memberâ&#x20AC;&#x2122;s profile, attend Forum, and get tutorials. Developing each one of these processes entails practically all the PHP&MySQL techniques you have learned in Chapter 02 and Chapter 03.
The Join in link involves programming as in adding contacts in Chapter 03. Details of this are treated in Chapter 05. 4. The fourth row containing three columns (each column consists of rows dealing with presentation of the contents of the portal).
Setting Up the Web Server All the HTML and PHP files used in this Project portal can be downloaded from http://www.teachlearn-online.net/aerbooks/. Look for the file alumni.zip and download it. Unzip it to your computer hard disk directory alumni (create it if it is not existing). Upload all the files and folders in this directory to the Web server’s subdomain directory, e.g. /www/alumni.awardspace.info. Use the FTP client FileZilla or the File Manager of the cPanel in uploading the files and folders. We learn all the basic techniques in creating a dynamic website using PHP&MySQL by simply discovering how the Project model was built through looking into and analyzing the html code and php script files.
Setting Up the Database and Tables Go back to Chapter 01 and Chapter 03 to see how you have set up the database and its table for the My Personal Address Book Website. You will do similar steps in setting up the database and the tables for the Project Alumni Portal as in the following (Note: You may wish to use another free web hosting service from http://www.0fees.net/ which I find better than awardspace.com because it offers more than 1 database; thus, you can have both your “My Personal Address Book” website and the High School Alumni Portal in one web server). Appendix II provides you a guide on how to use the free webhosting service of 0fees.net. Do the following steps: 1.
Launch your browser and put in the address box: http://cp5.awardspace.com/; then hit the Enter key on your keyboard.
2.
Login to the cPanel using the username and password given to you by the Web hosting provider, i.e. awardspace.com. Click the Website Manager
3.
Click the Subdomain Manager and create a subdomain using awardspace.info (for my sample, I created the subdomain: alumniproj.awardspace.info).
4.
Go to the MySQL Manager section and create a database with the name: alum (the complete name has the prefix of your cPanel username; in my sample, the complete name is alumniproj_alum). The username will be assigned to this database which is normally the same as the database name. Create your password.
5.
Go back to the cPanel Website Manager section again and click phpMyAdmin.
6.
At the left panel you will see the database as you have created. Click the (prefix)_alum and you see at the right panel tool bar menu for your use. Click the SQL button at the top bar menu and you will see Choose File button. Click it and look for the alumni.sql file (you must have downloaded this earlier from the aerbooks website). Then click the Go button. When this is done, you will see that alumni(0) becomes alumni(3). Click the alumni(3) and you will see the tables created as shown in the following screenshot:
Click at the left panel the table: member_profile and you will see the following screenshot:
Do the same for the other tables to see the structure of each table.
The Alumni Portal Homepage The Homepage code is index.php (look at the alumni directory of your computer). The whole code can be seen by opening this PHP file in the Winsyntax text editor (you have this installed in your computer as earlier suggested). In the following discussion, we will show only the pertinent part of the Homepage code that uses PHP&MySQL. The links bar that appears just below the header image is the rendering of: ……….. <table border="0" cellpadding="0" width="50%" cellspacing="0"> <tr> <td width="100%"><img border="0" src="images/header.gif" width="828" height="90"></td> <? require "main_menu.php"; ?> <td width="100%" bgcolor="#FFFFFF"><img border="0" src="images/menu_bar_bottom.gif" width="828" height="7"></td> </tr>
………. The PHP function require is used to include a php file into your source page code. The PHP function include may also be used but require is a better choice. The file included here is the main_menu.php. This code is as shown in
the following (putting this in the location where the one liner <? require "main_menu.php"; ?> will make your index.php code longer and cluttered): <?php print"<tr>"; print"<td width='100%' bgcolor='#FFFFFF' background='images/menu_bar.gif'>"; print"<table border='0' cellpadding='0' width='100%' cellspacing='0'>"; print"<tr>"; print"<td width='1%'><p align='center'></td>"; print"<td width='8%'><p align='center'><b><a href='index.php'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>Home</font></a></b></td>"; print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='8%'><p HREF='javascript:makenew()'><font style='font-size: BT,Arial'>About Us</A></font></b></font></td>";
8pt'
border='0'
align='center'><b><A color='#FFFFFF' face='Zurich
print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='15%'><p align='center'><b><A HREF='javascript:make1957pics()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>1957 Pictures</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='8%'><p align='center'><b><A HREF='javascript:makegallery()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>Gallery</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='8%'><p align='center'><b><A HREF='javascript:makenews()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>News</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='12%'><p align='center'><b><A HREF='javascript:makecalevents()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>EventsCalendar</A></font></b></font></td>";
print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='8%'><p align='center'><b><A HREF='upload/index.html' target = '_blank'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>INVITATION</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img src='images/menu_bar_div.gif' width='7' height='25'></td>";
border='0'
print"<td width='17%'><p align='center'><b><A HREF='javascript:makedirectory()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>MembersDirectory</A></font></b></font></td>"; print"<td width='1%'><p align='center'></td>"; print"</tr>"; print"</table>"; print"</td>"; print"</tr>"; ?>
The foregoing PHP code is in effect rendered the HTML portion for the links bar. When you click a link, the corresponding Javascript function is triggered. For example, click the 1957 Pictures link and you will see the rendered pictures1957.php as shown in the following:
The Member Login uses the HTML form for inputting username and password. A more detailed discussion of this is considered in Chapter 06. Adding members by clicking the Join in link is considered in detailed manner in Chapter 05. The Site Statistics is processed by site_stat.php. Note the inserted PHP file <?php require "site_stat.php"; ?> in the index.php through the PHP command. The site_stat.php code is shown in the following: <?php require "config/common.inc.php"; require "config/db_connect.php"; $sql_TApplicants = "SELECT member_id FROM $member_profile"; $res_TApplicants = mysql_query($sql_TApplicants) or die("Couldn't execute query."); $TotalApplicants = mysql_num_rows($res_TApplicants); $sql_TMaterials = "SELECT docu_id FROM $documents"; $res_TMaterials = mysql_query($sql_TMaterials) or die("Couldn't execute query."); $TotalMaterials = mysql_num_rows($res_TMaterials);
$sql_Contributors = "SELECT DISTINCT docu_owner FROM $documents"; $res_Contributors = mysql_query($sql_Contributors) or die("Couldn't execute query."); $TotalContributors = mysql_num_rows($res_Contributors); $sql_Registered = "SELECT member_id, member_status FROM $member_profile WHERE member_status = 'Paid'"; $res_Registered = mysql_query($sql_Registered) or die("Couldn't execute query."); $TotalRegistered = mysql_num_rows($res_Registered); print "<tr>"; print "<td width='70%'><font face='Verdana' size='1'>Total Applicants</font></td>"; print "<td width='7%'><font face='Verdana' size='1'>:</font></td>"; print "<td width='23%'><font face='Verdana' size='1'>$TotalApplicants</font></td>"; print "</tr>"; print "<tr>"; print "<td width='70%'><font face='Verdana' size='1'>Registered Members</font></td>"; print "<td width='7%'><font face='Verdana' size='1'>:</font></td>"; print "<td width='23%'><font face='Verdana' size='1'>$TotalRegistered</font></td>"; print "</tr>"; print "<tr>"; print "<td width='70%'><font face='Verdana' size='1'>Contributors</font></td>"; print "<td width='7%'><font face='Verdana' size='1'>:</font></td>"; print "<td width='23%'><font face='Verdana' size='1'>$TotalContributors</font></td>"; print "</tr>"; print "<tr>"; print "<td width='70%'><font face='Verdana' size='1'>Total Resources</font></td>"; print "<td width='7%'><font face='Verdana' size='1'>:</font></td>"; print "<td width='23%'><font face='Verdana' size='1'>$TotalMaterials</font></td>"; print "</tr>"; ?>
The combination of the MySQL functions: mysql_query() and mysql_num_rows() determines the number of records in the respective tables of the database. Clicking the [view more] of one of the Resources triggers the details.php and you will see a page similar to the following:
The part of the details.php code that describes the resource document is shown in the following: ............ <td width="90%" valign="top"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td width="3%" bgcolor="#F9B949"><img border="0" src="images/bullet.gif" width="20" height="21"></td> <td width="97%" bgcolor="#008080"><font face="Arial" color="#FFFFFF" size="2"><b>&nbsp;Resource Material Details</b></font></td> </tr> </table> </td> </tr> <tr> <td width="100%">
<table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"> <img border="0" src="images/spcr3.gif" width="7" height="5"> </td> </tr> <?php require "config/common.inc.php"; require "config/db_connect.php"; $SQL_DocDetails = "SELECT * FROM $documents WHERE docu_id = '$MatID'"; $DocDetails = mysql_query($SQL_DocDetails) or die("Couldn't execute query."); while($Mat = mysql_fetch_row($DocDetails)) { $MatID = $Mat[0]; $MatTitle = $Mat[1]; $MatAbstract = $Mat[2]; $MatSbjcArea = $Mat[3]; $MatLevel = $Mat[4]; $MatResType = $Mat[5]; $MatFile = $Mat[6]; $MatFileType = $Mat[7]; $MatFileSize = $Mat[8]; $MatDate = $Mat[9]; $MatCat = $Mat[10]; $MatAmount = $Mat[11]; $MatOwner = $Mat[13]; } if ($MatFileType == ".doc") { $DocTypeDesc = "(This is a Word Document file and can be open by MSWORD)"; } else if ($MatFileType == ".xls") { $DocTypeDesc = "(This is a Spreadsheet Document file and can be open by MSEXCEL)"; } else if ($MatFileType == ".ppt") { $DocTypeDesc = "(This is a Presentation Document file and can be open by MSPOWERPOINT)"; } else if ($MatFileType == ".pdf") {
$DocTypeDesc = "(This is a PDF Document file and can be open by Acrobat Reader)"; } if ($MatCat == 'Free') { $vMatCat = "Free Download"; } else { $vMatCat = "Download for ".$MatAmount; } $SQL_Author = "SELECT member_id, member_lname, member_fname, member_mname, member_email FROM $member_profile WHERE member_id = '$MatOwner'"; $Author_Res = mysql_query($SQL_Author) or die("Couldn't execute query."); while($Author = mysql_fetch_row($Author_Res)) { $AuthorID = $Author[0]; $AuthorLName = $Author[1]; $AuthorFName = $Author[2]; $AuthorMName = $Author[3]; $AuthorEmail = $Author[4]; } $AuthorName = strtoupper($AuthorFName." ".substr($AuthorMName,0,1).". ".$AuthorLName);
?> <tr> <td width="100%"><p><b><font face="Arial" size="3" color="#CC3300"><? echo $MatTitle; ?></font></b></td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%" bgcolor="#000000"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr>
<tr> <td width="100%"> <img border="0" src="images/spcr3.gif" width="7" height="5"> </td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%" bgcolor="#EEEEEE" colspan="3"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%" bgcolor="#C0C0C0"><font style="font-size: 8pt" face="Zurich BT,Arial"><b>&nbsp;&nbsp;Sellers Description</b></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#EEEEEE" colspan="3"> <table border="0" width="100%" cellspacing="0" cellpadding="15"> <tr> <td width="100%" bgcolor="#FBFBFB"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatAbstract; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Subject Area </font> </td>
</tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatSbjcArea; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial">Level</font></td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatLevel; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td>
<td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Type of Resource </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatResType; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> File Name </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <?php if ($MatCat == 'Free') {
print "<tr>"; print "<td width='100%'><a href='materials/$MatFile'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatFile</font></a></td>"; print "</tr>"; } else { print "<tr>"; print "<td width='100%'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatFile</font></td>"; print "</tr>"; } ?> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> File Type </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatFileType; ?> <? echo $DocTypeDesc; ?></font></td> </tr> </table> </td> </tr>
<tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> File Size </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> <? echo $MatFileSize; ?> bytes </font> </td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial">Download</font></td> </tr> </table> </td>
<td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $vMatCat; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="100%" bgcolor="#FFFFFF" colspan="3"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial">Teacher-Author</font></td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> <b><? echo $AuthorName; ?></b> </font> </td> </tr> </table>
</td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial">Profile</font></td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><a href="authdesc.php?AuthorID=<? echo $AuthorID; ?>"><font style="font-size: 8pt" color="#000000" face="Zurich BT,Arial">Learn more about this Author</font></a></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Free Products </font> </td> </tr> </table>
</td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> List of Free Products of this Author </font> </td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Ask the Author&nbsp; </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> <a href='javascript:messages()'>Click here to send message to the Author's email: </A><? echo $AuthorEmail; ?> </font> </td> </tr> </table> </td> </tr> <tr>
<td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> </table> </td> </tr> <tr> <td width="100%"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> <tr> <td width="100%" bgcolor="#000000"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> </table> </td> ………….
Take note of how the relevant information of the document resource are taken from the documents table using the PHP&MySQL functions: SELECT, mysql_query(), and mysql_fetch_row(). When the Ask the Author link is clicked, the messages.php is triggered. This provides a HTML form for composing a message to be emailed to the Author. The emailing is processed by the usr_opt.php (option=”SendMmess”). The part of the usr_opt.php code that does this is as shown in the following (take note of how variables are passed from one page, messages.php, to the other, usr_opt.php): ………. } else if ($option == 'SendMess') { $subject = $vSubject; $email_message = $vMessage; $sendto = $vSendto; $sender = $vFrom; $toAddress = $sendto; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: $sender\r\n";
$headers .= "Cc: aerefre@gmail.com\r\n"; mail($toAddress, $subject, $email_message, $headers);
header("Location:sentmsg.php"); exit(); } ………… Take particular note of the dot (period) after the second $headers and the rest.
CHAPTER REVIEEW This chapter plunges you into real-world web application development. We learn how the Homepage of the Project Alumni Portal was created. Analyzing the code for member login, we learn the PHP code for authentication and authorization. Our understanding of the codes for collecting data from the database is bolstered by the site statistics code and the viewing of resource materials in the web server’s folder. How to send email using PHP code is shown in here how easy it is.
EXERCISES Add a login code and sending email code in your “My Personal Address Book” Website. For additional exercises, go to the DrRefre’s Books: http://www.teachlearn-online.net/aerbooks/ .
CHAPTER 5 â&#x20AC;&#x201C; Online Membership Application OVERVIEW This chapter deals with online application using the HTML form. Javascript is used to validate the required information input into the text box. An automatic feedback is done by the system by sending email to the applicant after having succeeded in filling up the form. Online Application to Join In If somebody has not joined in yet, the Homepage provides a Join in link just right below the login text boxes. Clicking this triggers the membership_application.php which is viewed in browser as in the following:
The portion of the membership_application.php that corresponds to this HTML form is as shown in the following: ………… <tr> <td width="100%"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <FORM ACTION="usr_opt.php" METHOD="POST" onsubmit="return checkform(this);"> <?php $option = "membership_add"; ?> <tr> <td width="100%" bgcolor="#C0C0C0"> <table border="0" cellpadding="3" width="100%" cellspacing="1"> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="2">Personal Information</font></b></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Last Name</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vlast_name" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;First Name&nbsp;</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vfirst_name" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Middle Name</font></td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vmiddle_name" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Member Type</font> </td> <td width="66%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" name="vmemtype"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Member</font></td> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input
type="radio" value="3" name="vmemtype"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Relative</font></td> </tr> </table> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp;Gender</font> </td> <td width="66%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Male</font></td> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Female</font></td> </tr> </table> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Birth Date (yyyy-mm-dd)</font> </td> <td width="66%" bgcolor="#FFFFFF"> <font face="Verdana" size="1" color="#748CA4"><input type="text" name="vbirth_date" value="<? echo date("Y-m-d"); ?>" size="48"></font> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Place of Birth</font> </td> <td width="66%" bgcolor="#FFFFFF"> <font face="Verdana" size="1" color="#748CA4"><input type="text" name="vplace_birth" size="48"></font> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Religiion</font> </td> <td width="66%" bgcolor="#FFFFFF"> <font face="Verdana" size="1" color="#748CA4"><input type="text"
name="vreligion" size="48"></font> </td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="2">Occupational Profile</font></b></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Official </font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Designation/Position</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vdesignation" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Name of Institution/Organization</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vinstitution" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Address of Institution</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vinst_address" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Contact Phone&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vphone" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Fax No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vfaxno" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Mobile Phone</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vmobphone" size="48"></font></td> </tr>
<tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Valid Email<br>Address</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vemail_address" size="48"></font></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="2">Residential Profile</font></b> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Home Address (No. and Street)&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vhome_address" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Town&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vtown" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">City/Province&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vcityprovince" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Region No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vregion" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Zip Code&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vzipcode" size="48"></font></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Tel. No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF"><font face="Verdana" size="1" color="#748CA4"><input type="text" name="vhome_telno" size="48"></font></td>
</tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"> <p align="center"><input type="submit" value="Submit" name="B1">&nbsp;&nbsp; <input type="reset" value="Reset" name="B2"></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> </table> </td> </tr> </FORM> </table> </td> </tr> …………
Take note of the use of Javascripts to validate entries into the form. It is important that a valid email is entered because this is going to be used as the username in the member login. Furthermore, the applicant will not be able to receive the feedback to the application if the email is not valid.
The Method=”POST” The following code lines dictate how the values of the variables in the form are going to be put into the specific table of the database: <FORM ACTION="usr_opt.php" METHOD="POST" onsubmit="return checkform(this);"> <?php $option = "membership_add"; ?>
The manner in which the values are going to be inserted into the table is specified by the portion of usr_opt.php with $option = “membership.add”. The code is as in the following: <?php include "config/common.inc.php"; include "config/db_connect.php";
$extlimit = "no"; //Do you want to limit the extensions of files uploaded $limitedext = array(".gif",".jpg",".png",".jpeg",".doc",".xls",".ppt",".pdf"); //Extensions you want files uploaded limited to. $sizelimit = "no"; //Do you want a size limit, yes or no? $sizebytes = "200000"; //size limit in bytes $hourdiff = "15.5"; // hours difference between server time and local time $timeadjust = ($hourdiff * 60 * 60); // time adjustment $vDate = date("Y-m-d h:i:s",time() + $timeadjust); // displays common time with am pm if ($option == 'membership_add') { $sql_select = "SELECT member_id FROM $member_profile"; $sql_result = mysql_query($sql_select) or die("Couldn't execute query operation."); $vIdNo = mysql_num_rows($sql_result); $vIdNo = $vIdNo + 1; $vMemberID = "PHILEDSYN-".date("YmdHis")."-".$vIdNo; if ($vgender == 1) { $vGender = "Male"; } else { $vGender = "Female"; } $sql_insert = "INSERT INTO $member_profile (member_id, member_lname, member_fname, member_mname, member_gender, member_bdate, member_pbirth, member_religion, member_occupation, member_organization, member_org_add, member_contact, member_fax, member_mobile, member_email, member_home_add, member_home_town, member_home_cityprovince, member_home_region, member_home_zipcode, member_home_telno, member_joindate) values ('$vMemberID', '$vlast_name', '$vfirst_name', '$vmiddle_name', '$vGender', '$vbirth_date', '$vplace_birth', '$vreligion', '$vdesignation', '$vinstitution', '$vinst_address', '$vphone', '$vfaxno', '$vmobphone', '$vemail_address', '$vhome_address', '$vtown', '$vcityprovince', '$vregion', '$vzipcode', '$vhome_telno', '$vDate')"; mysql_query($sql_insert) or die("Couldn't execute insert operation"); $RawUserPasswd = explode("-",$vMemberID); $UsrPass1 = $RawUserPasswd[0]; $UsrPass2 = substr($RawUserPasswd[1],10,5); $UsrPass3 = $RawUserPasswd[2];
$UserPasswd = $UsrPass2."-".$UsrPass3; if ($vmemtype == 1) { $vMemType = "Member"; } else { $vMemType = "Relative"; } $sql_insert2 = "INSERT INTO $member_usracnt (idno, username, password, member_type) values ('$vMemberID', '$vemail_address', '$UserPasswd', '$vMemType')"; mysql_query($sql_insert2) or die("Couldn't execute insert2 operation."); $toName = "Dr. Antonio E. Refre"; $toAddress = "DR. ANTONIO E. REFRE <aerefre@gmail.com>"; $subject = "HS Class 2008 Membership Application."; $email_message = " <p>Message alert!</p> <p>Details of new HS Class 2008 Membership Application.</p> <table> <tr> <td>Name</td> <td>:</td> <td>$vlast_name,&nbsp;$vfirst_name&nbsp;$vmiddle_name</td> </tr> <tr> <td>Gender</td> <td>:</td> <td>$vGender</td> </tr> <tr> <td>Tel. No.</td> <td>:</td> <td>$vphone / $vhome_telno</td> </tr> <tr> <td>Mobile Phone</td> <td>:</td> <td>$vmobphone</td> </tr> <tr> <td>E-mail Address</td> <td>:</td> <td><a href='mailto:$cookie_email'>$vemail_address</a></td>
</tr> <tr> <td>Postal Address</td> <td>:</td> <td>$vhome_address</td> </tr> <tr> <td>Application Member Type</td> <td>:</td> <td>$vMemType</td> </tr> <tr> <td colspan='3' bgcolor='#000000'></td> </tr> </table> "; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: $vfirst_name $vlast_name <$vemail_address>\r\n"; $headers .= "Cc: aerefre@gmail.com\r\n"; mail($toAddress, $subject, $email_message, $headers);
$appsAddress = "$vfirst_name $vlast_name <$vemail_address>"; $appsSubject = "HS Class 2008 Membership Application"; $appsMessage = "Thank you for expressing your interest in HS Class 2008 Collaboration. If you have not done it yet,<br><br> (1)Please proceed to a <b>BancoDeOro Branch</b> near you and deposit your joining fee of three hundred (P 300.00)pesos only to the Antonio E. Refre <b>Savings Account No. 480151156</b> (BDO Taft-Nakpil Branch);in case there is no BDO branch in your locality, go to a Metrobank branch and make a deposit of P300 to Savings Account No. 244-3244170634 (Metrobank Farmers-Cubao branch) Account Name: ANTONIO E. REFRE. <br><br> (2) Keep the validated deposit slip and write legibly your full name on it.<br><br> (3) Have the deposit slip xeroxed and fax this xerox copy to <b>02-927-2408</b> or sent an email to aerefre@gmail.com giving the code printed on the deposit slip by the validation machine of the bank.<br><br> (4) The information that you have submitted will be checked against the statement from the BDO Taft-Nakpil Branch or Metrobank Farmers-Cubao Branch. If everything is alright,
your joining the organizatrion becomes effective and your earning credit points commences <br><br> To Login to the Member site use the following:<br> <b>Username: $vemail_address<br> Password: $UserPasswd</b> <br><br> Click this <a href='http://www.teachlearn-online.net/ths57/' target='_blank'> THS57 </a>to login. <br><br> ";
$vheaders = "MIME-Version: 1.0\r\n"; $vheaders .= "Content-type: text/html; charset=iso-8859-1\r\n"; $vheaders .= "From: HS Class 2008 <aerefre@gmail.com>\r\n";
mail($appsAddress, $appsSubject, $appsMessage, $vheaders); header("Location:membership_application_res.php?vMemberID=$vMemberID"); exit(); …………
Take note that the values of the variables: $member_profile and $member_usracnt are specified in the common.inc.php. These are tables of the database alumni. After inserting the prospective member’s data into the tables, an email is sent to the applicant giving instructions on how to pay the membership fee and the login username and password. Thus, in the next visit to the Portal, the member can already get inside the member exclusive page. The password is automatically generated by the following scripts using the PHP explode function: $RawUserPasswd = explode("-",$vMemberID); $UsrPass1 = $RawUserPasswd[0]; $UsrPass2 = substr($RawUserPasswd[1],10,5); $UsrPass3 = $RawUserPasswd[2]; $UserPasswd = $UsrPass2."-".$UsrPass3;
Study how the variable $email_message is created as shown in the following: $email_message = " <p>Message alert!</p>
<p>Details of new HS Class 2008 Membership Application.</p> <table> <tr> <td>Name</td> <td>:</td> <td>$vlast_name,&nbsp;$vfirst_name&nbsp;$vmiddle_name</td> </tr> <tr> <td>Gender</td> <td>:</td> <td>$vGender</td> </tr> <tr> <td>Tel. No.</td> <td>:</td> <td>$vphone / $vhome_telno</td> </tr> <tr> <td>Mobile Phone</td> <td>:</td> <td>$vmobphone</td> </tr> <tr> <td>E-mail Address</td> <td>:</td> <td><a href='mailto:$cookie_email'>$vemail_address</a></td> </tr> <tr> <td>Postal Address</td> <td>:</td> <td>$vhome_address</td> </tr> <tr> <td>Application Member Type</td> <td>:</td> <td>$vMemType</td> </tr> <tr> <td colspan='3' bgcolor='#000000'></td> </tr> </table> ";
This is the technique in sending email in HTML format. Notice some of the emails you receive that are not just texts but containing some images. Modify the contents of the variables to reflect your profile so that you receive in your email a copy of the feedback. CHAPTER REVIEW
In Chapter 03 we learn how to add data into the MySQL database using PHP scripts. This chapter bolsters further our understanding on how to use PHP&MySQL in inserting records to the tables of the database. Similarly, we learn how to send HTML email. EXERCISES Add an online application in your My Personal Address Book website with sending email feedback. For additional exercises, go to the DrRefreâ&#x20AC;&#x2122;s Books: http://www.teachlearn-online.net/aerbooks/ .
CHAPTER 6 â&#x20AC;&#x201C; Member Exclusive Page OVERVIEW After the membership application is accomplished, the member is accepted. Acceptance is explicitly mentioned in the email sent to the applicant by the provision of username and password for logging in to the member exclusive page. This chapter deals with the process of logging in and the activities the member can do inside the member exclusive page.
Validation and Authentication The member logins using the username and password provided in the email sent to him/her after joining in successfully. These login information are validated and authenticated by the login.php code. This code is as shown in the following: <?php session_start(); session_register("v_idno"); session_register("v_user"); session_register("v_pass"); require "functions.php"; if (authenticateUser($v_usrnam, $v_usrpas)) { $v_user = $v_usrnam ; $v_pass = $v_usrpas ; require "config/common.inc.php"; global $hostname, $username, $password, $dbname, $user_account, $user_profile, $user_level; if (!($connection = mysql_connect($hostname, $username, $password))) { echo "Couldn't connect to server."; return 0; } $db = mysql_select_db($dbname) or die ("Couldn't select database."); $sql = "SELECT idno, username, password, member_type FROM $member_usracnt WHERE username ='$v_user' AND password ='$v_pass'"; $result = mysql_query($sql) or die("Couldn't execute query.");
while($e_row = mysql_fetch_row($result)) { $v_idno = $e_row[0]; $v_memtype = $e_row[3]; } if ($v_memtype == 'Relative') { $accepted = "yes"; header("Location:main.php"); exit(); } else if ($v_memtype == 'Member') { $accepted = "yes"; header("Location:main.php"); exit(); } else { $accepted = "no"; header("Location:index.php"); exit(); } } else { $accepted = "no"; header("Location:index.php?Login=failure"); exit(); } ?>
Take note on how the variables from the login form in the index.php are passed into the login.php through PHP function session_register(). If login is successful, the main.php is triggered and the browser launches the following page:
The Homepage of the Member Exclusive Page is the rendering of the main.php. Open this file in the Winsyntax text editor to see the whole code. The member can now avail of the benefits of being a member. These are looking for resource materials, updating his/her profile, uploading documents for sharing, and attending online forum and tutorials.
Logged-In User IInformation The portion of the main.php that processes the member’s data to present them in the Login User box is as in the following: ………… <tr> <td width="100%" bgcolor="#FFFFFF"> <table border="0" width="100%" cellspacing="0" cellpadding="9"> <?php require "config/common.inc.php";
require "config/db_connect.php";
$sql_paid = "SELECT member_id, member_status FROM $member_profile WHERE member_id = '$v_idno' AND member_status = 'Paid'"; $paid_res = mysql_query($sql_paid) or die("Couldn't execute query."); $paid_row = mysql_num_rows($paid_res); if ($paid_row == 1) { print "<tr>"; print "<td width='100%' align='center'><b><font style='font-size: 8pt' face='Zurich BT,Arial'>Paid : P 300.00<br>Your Credit Point is :</font></b></td>"; print "</tr>"; } else { print "<tr>"; print "<td width='100%' align='center'><b><font style='font-size: 8pt' face='Zurich BT,Arial'>Paid : P 0.00<br>Your Credit Point is :</font></b></td>"; print "</tr>"; } ?> </table> </td> </tr>
The Menu
The Menu has links to Main (the Member Exclusive Homepage), Resource Materials (for listing out all available resource materials), My Profile (for updating the member’s profile), and My Documents (for uploading documents intended for sharing). The Main (main.php) is discussed at the beginning of this chapter. Clicking the Resource Materials triggers resources.php and the following view in browser shows its rendering:
The portion of the resources.php code that does the listing out of these resources is as shown in the following: ………… <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <?php require "config/common.inc.php"; require "config/db_connect.php"; $SQL_DocMat = "SELECT docu_id, docu_title, docu_abstract, docu_date, docu_cat, docu_amount, docu_owner FROM $documents ORDER BY docu_date DESC LIMIT 10"; $DocMat_Res = mysql_query($SQL_DocMat) or die("Couldn't execute query.");
while($DocMat = mysql_fetch_row($DocMat_Res)) { $MatID = $DocMat[0]; $MatTitle = $DocMat[1]; $MatAbstract = $DocMat[2]; $MatDate = $DocMat[3]; $MatCat = $DocMat[4]; $MatAmount = $DocMat[5]; $MatOwner = $DocMat[6]; if ($MatCat == 'Free') { $vMatCat = "free"; } else { $vMatCat = $MatAmount; } $vAbs = substr($MatAbstract,0,215); print "<tr>"; print "<td width='3%' valign='top'><img border='0' src='images/bullet1.gif' width='15' height='20'></td>"; print "<td width='97%'><font face='Arial' size='2' color='#FF0000'><u><b>$MatTitle</b></u></font></td>"; print "</tr>"; print "<tr>"; print "<td width='100%' colspan='2'><img border='0' src='images/spcr3.gif' width='7' height='5'></td>"; print "</tr>"; print "<tr>"; print "<td width='3%'></td>"; print "<td width='97%'><font face='Verdana' size='1'>$vAbs... [<a href='docdetails.php?MatID=$MatID'>view</a>] [<u>download for $vMatCat</u>] [<u>Author</u>] [<u>date added: $MatDate</u>]</font></td>"; print "</tr>"; print "<tr>"; print "<td width='100%' colspan='2'><img border='0' src='images/spcr3.gif' width='7' height='5'></td>"; print "</tr>"; } ?> <tr> <td width="100%" colspan="2"><font face="Verdana" size="1">&nbsp;</font></td> </tr> <tr> <td width="100%" colspan="2" background="images/divider01.gif">&nbsp;</td> </tr> </table> </td> </tr> …………
Clicking the My Profile triggers myprofile.php and the following view in browser shows the page:
The portion of the myprofile.php code that shows the HTML form for updating is as shown in the following: ………… <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <FORM ACTION="usr_opt.php" METHOD="POST" ENCTYPE="multipart/form-data" name="nameform"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%" bgcolor="#C0C0C0"> <table border="0" cellpadding="3" width="100%" cellspacing="1"> <?php $Sql_Select = "SELECT * FROM $member_profile WHERE member_id = '$v_idno'"; $Sql_Result = mysql_query($Sql_Select) or die("Couldn't execute query."); while($MemProfile = mysql_fetch_row($Sql_Result)) { $MemID = $MemProfile[0]; $MemLName = $MemProfile[1]; $MemFName = $MemProfile[2]; $MemMName = $MemProfile[3]; $MemGender = $MemProfile[4]; $MemBDate = $MemProfile[5]; $MemPBirth = $MemProfile[6]; $MemReligion = $MemProfile[7]; $MemOccupation = $MemProfile[8]; $MemOrganization = $MemProfile[9]; $MemOrgAdd = $MemProfile[10]; $MemContact = $MemProfile[11]; $MemFax = $MemProfile[12]; $MemMobile = $MemProfile[13]; $MemEmail = $MemProfile[14]; $MemHomeAdd = $MemProfile[15]; $MemHomeTown = $MemProfile[16]; $MemHomeProv = $MemProfile[17]; $MemRegion = $MemProfile[18]; $MemZipCode = $MemProfile[19]; $MemHomeTelNo = $MemProfile[20]; $MemAchievements = $MemProfile[23]; $MemPicture = $MemProfile[24]; } if ($MemGender == 'Male') { $vChecked1 = "checked"; } else { $vChecked2 = "checked"; }
$option = "ModProfile"; ?> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="3"><b><font face="Arial" color="#FFFFFF" size="2">Personal Information</font></b></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Last Name</font></td> <td width="43%" bgcolor="#FFFFFF"><input type="text" name="MemLName" value="<? echo $MemLName; ?>" size="33"></td> <td width="23%" bgcolor="#FFFFFF" rowspan="6"> <div align="center"> <center> <table border="0" width="65%" cellspacing="0"> <?php if (empty($MemPicture)) { print "<tr>"; print "<td width='100%' bgcolor='#000000'><a href='mypicture.php?MemID=$MemID'><img border='0' src='images/nopic.gif' width='108' height='108'></a></td>"; print "</tr>"; } else { print "<tr>"; print "<td width='100%' bgcolor='#000000'><a href='mypicture.php?MemID=$MemID'><img border='0' src='mempic/$MemPicture' width='108' height='136'></a></td>"; print "</tr>"; } ?> </table> </center> </div> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><b><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font></b><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; First Name</font></td> <td width="43%" bgcolor="#FFFFFF"><input type="text" name="MemFName" value="<? echo $MemFName; ?>" size="33"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Middle
Name</font></td> <td width="43%" bgcolor="#FFFFFF"><input type="text" name="MemMName" value="<? echo $MemMName; ?>" size="33"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Gender</font> </td> <td width="43%" bgcolor="#FFFFFF"> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="1" <? echo $vChecked1; ?> name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Male</font></td> <td width="4%"><font style="FONT-SIZE: 8pt" face="Arial" color="#748CA4"><input type="radio" value="2" <? echo $vChecked2; ?> name="vgender"></font></td> <td width="46%"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Female</font></td> </tr> </table> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Birth Date (yyyy/mm/dd)</font> </td> <td width="43%" bgcolor="#FFFFFF"> <input type="text" name="MemBDate" value="<? echo $MemBDate; ?>" size="33"> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Place of Birth</font> </td> <td width="36%" bgcolor="#FFFFFF"> <input type="text" name="MemPBirth" value="<? echo $MemPBirth; ?>" size="33"> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Religion</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"> <input type="text" name="MemReligion" value="<? echo $MemReligion; ?>" size="33">
</td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="3"><b><font face="Arial" color="#FFFFFF" size="2">Occupational Profile</font></b></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Official </font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Designation/Position</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemOccupation" value="<? echo $MemOccupation; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Name of Institution/Organization</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemOrganization" value="<? echo $MemOrganization; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Address of Institution</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemOrgAdd" value="<? echo $MemOrgAdd; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Contact Phone&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemContact" value="<? echo $MemContact; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Fax No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemFax" value="<? echo $MemFax; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">Mobile Phone</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemMobile" value="<? echo $MemMobile; ?>" size="51"></td> </tr> <tr>
<td width="34%" bgcolor="#FFFFFF" align="right"><font style="FONT-SIZE: 8pt" face="Arial" color="#FF0000">*</font><font style="FONT-SIZE: 8pt" face="Arial" color="#808080">&nbsp; Email Address</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemEmail" value="<? echo $MemEmail; ?>" size="51"></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="3"><b><font face="Arial" color="#FFFFFF" size="2">Residential Profile</font></b> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Home Address (No. and Street)&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemHomeAdd" value="<? echo $MemHomeAdd; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Town&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemHomeTown" value="<? echo $MemHomeTown; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">City/Province&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemHomeProv" value="<? echo $MemHomeProv; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Region No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemRegion" value="<? echo $MemRegion; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Zip Code&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemZipCode" value="<? echo $MemZipCode; ?>" size="51"></td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Tel. No.&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><input type="text" name="MemHomeTelNo" value="<? echo $MemHomeTelNo; ?>" size="51"></td>
</tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="3"><b><font face="Arial" color="#FFFFFF" size="2">Professional Achievements&nbsp;</font></b> </td> </tr> <tr> <td width="34%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Explain briefly your achievements<br> as a Professional in your<br> chosen career&nbsp;</font> </td> <td width="66%" bgcolor="#FFFFFF" colspan="2"><textarea rows="13" name="MemAchievements" cols="38"><? echo $MemAchievements; ?></textarea></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <input type="hidden" name="MemID" value="<? echo $MemID; ?>"> <tr> <td width="100%" bgcolor="#C0C0C0" align="right" colspan="3"> <table border="0" width="100%" cellspacing="0" cellpadding="15"> <tr> <td width="100%"> <p align="center"><input type="submit" value="Submit Changes" name="B1">&nbsp; <input type="reset" value="Reset" name="B2"></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </FORM> </table> </td> </tr> …………
Clicking on the member’s photo triggers mypicture.php which launches the following web page:
The portion of the mypicture.php code which shows the HTML form for uploading the member’s picture is as shown in the following: ………… <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <FORM ACTION="usr_opt.php" METHOD="POST" ENCTYPE="multipart/form-data" name="nameform"> <tr> <td width="100%" bgcolor="#C0C0C0"> <table border="0" cellpadding="3" width="100%" cellspacing="1"> <?php require "config/common.inc.php"; require "config/db_connect.php"; $Sql_Select = "SELECT member_id, member_lname, member_fname, member_mname FROM $member_profile WHERE member_id = '$MemID'"; $Sql_Result = mysql_query($Sql_Select) or die("Couldn't execute query."); while($MemProfile = mysql_fetch_row($Sql_Result)) { $MemID = $MemProfile[0]; $MemLName = $MemProfile[1]; $MemFName = $MemProfile[2];
$MemMName = $MemProfile[3]; } $option = "ModPic"; ?> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><b><font face="Arial" color="#FFFFFF" size="2">Personal Information</font></b></td> </tr> <tr> <td width="21%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Last Name</font> </td> <td width="79%" bgcolor="#FFFFFF"><b><font face="Arial" size="2"><? echo $MemLName; ?></font></b></td> </tr> <tr> <td width="21%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">First Name</font> </td> <td width="79%" bgcolor="#FFFFFF"><b><font face="Arial" size="2"><? echo $MemFName; ?></font></b></td> </tr> <tr> <td width="21%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">Middle Name</font> </td> <td width="79%" bgcolor="#FFFFFF"><b><font face="Arial" size="2"><? echo $MemMName; ?></font></b></td> </tr> <tr> <td width="100%" bgcolor="#C0C0C0" colspan="2"><img border="0" src="images/spcr3.gif" width="7" height="5"> </td> </tr> <tr> <td width="21%" bgcolor="#FFFFFF" align="right"><font style="font-size: 8pt" face="Arial" color="#808080">My Picture</font> </td> <td width="79%" bgcolor="#FFFFFF"><input type="file" name="file" size="51"></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <input type="hidden" name="MemID" value="<? echo $MemID; ?>"> <tr> <td width="100%" bgcolor="#C0C0C0" align="right" colspan="2"> <table border="0" width="100%" cellspacing="0" cellpadding="15"> <tr> <td width="100%"> <p align="center"><input type="submit" value="Submit My Picture" name="B1">&nbsp;<input type="reset" value="Reset" name="B2"></td> </tr> </table> </td> </tr> </table> </td> </tr>
</FORM> </table> </td> </tr> …………
The portion of usr_opt,php which takes the $option = "ModPic" is as shown in the following (this is how a file is uploaded to the /public_html/mempic folder and the member_profile’s record on the picture field is modified): ………… } else if ($option == 'ModPic') { $dl = "http://aerefre.890m.com/mempic"; //url where files are uploaded $absolute_path = "/home/a9553135/public_html/mempic/"; //Absolute path to where files are uploaded $websiteurl = "http://aerefre.890m.com/mempic/"; //Url to you website $ext = strrchr($file_name,'.'); $dir = "dir"; if ($file != "") { if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less."); } $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } $Update = "UPDATE $member_profile SET member_pic='$file_name' WHERE member_id='$MemID'"; mysql_query($Update) or die("Couldn't execute update operation."); header("Location:myprofile.php?v_idno=$MemID"); exit(); …………
When the submit changes button of the My Profile form is clicked, the usr_opt.php is triggered using the $option=”ModProfile”. This portion of the code is as shown in the following: …………
} else if ($option == 'ModProfile') { if ($vgender == 1) { $vGender = "Male"; } else { $vGender = "Female"; } $UPDATE_Prof = "UPDATE $member_profile SET member_lname='$MemLName', member_fname='$MemFName', member_mname='$MemMName', member_gender='$vGender', member_bdate='$MemBDate', member_pbirth='$MemPBirth', member_religion='$MemReligion', member_occupation='$MemOccupation', member_organization='$MemOrganization', member_org_add='$MemOrgAdd', member_contact='$MemContact', member_fax='$MemFax', member_mobile='$MemMobile', member_email='$MemEmail', member_home_add='$MemHomeAdd', member_home_town='$MemHomeTown', member_home_cityprovince='$MemHomeProv', member_home_region='$MemRegion', member_home_zipcode='$MemZipCode', member_home_telno='$MemHomeTelNo', member_achievements='$MemAchievements' WHERE member_id = '$MemID'"; mysql_query($UPDATE_Prof) or die("Couldn't execute update query."); header("Location:myprofile.php?v_idno=$MemID"); exit(); …………
Clicking on the My Documents link of the Menu will trigger mydocuments.php. Browser rendering shows the following web page:
The member can Add New Document. He can also edit or delete documents (only his own documents). The portion of the mydocuments.php that does these processes is as shown in the following: ………… <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"> <p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial"><b>: : : <a href="newresource.php"><font color="#000000">Add New Document</font></a> : :&nbsp;</b></font> </td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="1" cellpadding="3"> <tr> <td width="57%" colspan="2" bgcolor="#000000"> <table border="0" width="100%" cellspacing="0"> <tr> <td width="100%"> <p align="center"><font face="Arial" color="#FFFFFF" size="2"><b>Title</b></font></td>
</tr> </table> </td> <td width="16%" bgcolor="#000000"><p align="center"><font face="Arial" color="#FFFFFF" size="2"><b>Type&nbsp;</b></font></td> <td width="15%" bgcolor="#000000"><p align="center"><font face="Arial" color="#FFFFFF" size="2"><b>Date Added</b></font></td> <td width="12%" bgcolor="#000000" colspan="2"><p align="center">&nbsp;</td> </tr> <?php require "config/common.inc.php"; require "config/db_connect.php"; $SQL_MyDocs = "SELECT docu_id, docu_title, docu_date, docu_cat, docu_amount, docu_owner FROM $documents WHERE docu_owner = '$v_idno' ORDER BY docu_date DESC"; $MyDocs_Res = mysql_query($SQL_MyDocs) or die("Couldn't execute query."); $Cnt = 0; $RCnt = 1; while($Materials = mysql_fetch_row($MyDocs_Res)) { $MatID = $Materials[0]; $MatTitle = $Materials[1]; $MatDate = $Materials[2]; $MatCat = $Materials[3]; $MatAmount = $Materials[4]; $MatOwner = $Materials[5]; if ($MatCat == 'Free') { $vCategory = $MatCat; } else { $vCategory = $MatAmount; } if ($RCnt == 1) { $bkground = "#EEEEEE"; $RCnt = $RCnt + 1; } else { $bkground = "#FEEDCF"; $RCnt = 1; } $Cnt = $Cnt + 1; print "<tr>"; print "<td width='4%' bgcolor='$bkground'><font style='font-size: 8pt' face='Zurich BT,Arial'>$Cnt.</font></td>"; print "<td width='53%' bgcolor='$bkground'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatTitle</font></td>"; print "<td width='16%' bgcolor='$bkground' align='center'><font style='font-size: 8pt' face='Zurich BT,Arial'>$vCategory</font></td>"; print "<td width='15%' bgcolor='$bkground' align='center'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatDate</font></td>"; print "<td width='6%' bgcolor='$bkground' align='center'><a href='editresource.php?MatID=$MatID'><img border='0' src='images/b_edit.png' width='16' height='16'></a></td>"; print "<td width='6%' bgcolor='$bkground' align='center'><a href='usr_opt.php?MatID=$MatID&option=DelMat'><img border='0' src='images/b_drop.png'
width='16' height='16'></a></td>"; print "</tr>"; } ?> </table> </td> </tr> <tr> <td width="100%"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> <tr> <td width="100%" bgcolor="#000000"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td width="100%" valign="top" colspan="2"> <img border="0" src="images/spcr4.gif" width="7" height="2"> </td> </tr> </table> </td> </tr> …………
Clicking the Add New Document link triggers newresource.php and the browser rendering shows the following web page:
The portion of the newresource.php code that shows the New Resource Material form is as shown in the following: ………… <td width="90%" valign="top"> <FORM ACTION="usr_opt.php" METHOD="POST" ENCTYPE="multipart/form-data" onsubmit="return checkform(this);"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td width="3%" bgcolor="#F9B949"><img border="0" src="images/bullet.gif" width="20" height="21"></td> <td width="97%" bgcolor="#008080"><font face="Arial" color="#FFFFFF"
size="2"><b>&nbsp;New Resource Material</b></font></td> </tr> </table> </td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"><font face="Verdana" size="2">Enter Your Resource Material attributes</font></td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0"> <tr> <td width="100%" bgcolor="#000000"> <table border="0" width="100%" cellspacing="0"> <tr> <td width="100%" bgcolor="#FFFFFF"> <table border="0" width="100%" cellspacing="1" cellpadding="3"> <tr> <td width="100%" colspan="2" bgcolor="#000000"> <p align="center">&nbsp;</td> </tr> <?php require "config/common.inc.php"; require "config/db_connect.php"; $SQL_Author = "SELECT member_id, member_lname, member_fname, member_mname FROM $member_profile WHERE member_id = '$v_idno'"; $Author_Res = mysql_query($SQL_Author) or die("Couldn't execute query."); while($Author = mysql_fetch_row($Author_Res)) { $AuthorID = $Author[0]; $AuthorLName = $Author[1]; $AuthorFName = $Author[2]; $AuthorMName = $Author[3]; } $AuthorName = strtoupper($AuthorFName." ".substr($AuthorMName,0,1).". ".$AuthorLName); $SQL_ResMat = "SELECT docu_id FROM $documents"; $ResMat_Result = mysql_query($SQL_ResMat) or die("Couldn't execute query."); $ResMat_Row = mysql_num_rows($ResMat_Result); $ResMat_Cnt = $ResMat_Row + 1; $ResMatID = "PHILEDSYN-"."DOCUMENTS-".date("YmdHis")."-
".$ResMat_Cnt; $hourdiff = "15.5"; // hours difference between server time and local time $timeadjust = ($hourdiff * 60 * 60); // time adjustment $PlDateTime = date("Y-m-d H:i:s",time() + $timeadjust); // displays military time $PlDate = date("Y-m-d",time() + $timeadjust); // displays date $TodayDate = date("j F Y",time() + $timeadjust); $option = "NewMaterial"; ?> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Resource ID No.</font></td> <td width="77%" bgcolor="#EEEEEE"><font style="font-size: 8pt" face="Zurich BT,Arial"><b><? echo $ResMatID; ?></b></font></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Resource Material Title</font></td> <td width="77%" bgcolor="#EEEEEE"><input type="text" name="vResMatTitle" size="58"></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Subject Area</font></td> <td width="77%" bgcolor="#EEEEEE"><input type="text" name="vSubjectArea" size="58"><br><font style="font-size: 8pt" face="Zurich BT,Arial">(Ex. Science, Math, Phisics, Anatomy, Physiology, etc.)</font></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Level</font></td> <td width="77%" bgcolor="#EEEEEE"><input type="text" name="vLevel" size="58"><br><font style="font-size: 8pt" face="Zurich BT,Arial">(Ex. Primary, Secondary, College, Vocational, Higher Education, etc.)</font></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Type of Resource</font></td> <td width="77%" bgcolor="#EEEEEE"><input type="text" name="vResourceType" size="58"><br><font style="font-size: 8pt" face="Zurich BT,Arial">(Ex. Lesson Plan, Syllabus, Whole Course, etc.)</font></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Brief Description</font></td> <td width="77%" bgcolor="#EEEEEE"><textarea rows="11" name="vDescription" cols="44"></textarea></td> </tr> <tr>
<td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Category</font></td> <td width="77%" bgcolor="#EEEEEE"> <table border="0" width="100%" cellspacing="0"> <tr> <td width="4%"><input type="radio" value="V1" checked name="Category"></td> <td width="14%"><font style="font-size: 8pt" face="Zurich BT,Arial">Free&nbsp;</font></td> <td width="4%"><input type="radio" value="V2" name="Category"></td> <td width="18%"><font style="font-size: 8pt" face="Zurich BT,Arial">For a Fee&nbsp;</font></td> <td width="12%"><font style="font-size: 8pt" face="Zurich BT,Arial">Amount:&nbsp;</font></td> <td width="48%"><input type="text" name="vAmount" size="20"></td> </tr> </table> </td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Electronic File</font></td> <td width="77%" bgcolor="#EEEEEE"><input type="file" name="file" size="47"></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Author</font></td> <td width="77%" bgcolor="#EEEEEE"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $AuthorName; ?></font></td> </tr> <tr> <td width="23%" bgcolor="#FEEDCF"><p align="right"><font style="font-size: 8pt" face="Zurich BT,Arial">Posting Date</font></td> <td width="77%" bgcolor="#EEEEEE"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $TodayDate; ?></font></td> </tr> <input type="hidden" name="option" value="<? echo $option; ?>"> <input type="hidden" name="ResMatID" value="<? echo $ResMatID; ?>"> <input type="hidden" name="PlDate" value="<? echo $PlDate; ?>"> <input type="hidden" name="Owner" value="<? echo $v_idno; ?>"> </table> </td> </tr> </table> </td>
</tr> </table> </td> </tr> <tr> <td width="100%"> &nbsp; </td> </tr> <tr> <td width="100%"> <p align="center"><input type="submit" value="Submit Resource Material" name="B1">&nbsp; <input type="reset" value="Reset" name="B2"> </td> </tr> <tr> <td width="100%"> &nbsp; </td> </tr> </table> </td> </tr> </FORM> </table> </td> …………
Clicking the Submit New Material button triggers usr_opt.php with $option=”NewMaterial”. The portion of the usr_opt.php that post and insert a new record for the new material into the table documents of the database alumni is as shown in the following: ………… } else if ($option == 'NewMaterial') { $dl = "http://www.teachlearn-online.net/ths57/materials"; //url where files are uploaded $absolute_path = "/home/teachlea/public_html/ths57/materials/"; //Absolute path to where files are uploaded $websiteurl = "http://www.teachlearn-online.net/ths57/materials/"; //Url to you website $ext = strrchr($file_name,'.'); $dir = "dir"; if ($file != "") { if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less.");
} $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } if ($Category == 'V1') { $vCat = "Free"; $INSERT_NewMat = "INSERT INTO $documents (docu_id, docu_title, docu_abstract, docu_sbjcarea, docu_level, docu_restype, docu_file, docu_filetype, docu_filesize, docu_date, docu_cat, docu_owner) values ('$ResMatID', '$vResMatTitle', '$vDescription', '$vSubjectArea', '$vLevel', '$vResourceType', '$file_name', '$ext', '$file_size', '$PlDate', '$vCat', '$Owner')";
} else { $vCat = "For a Fee"; $INSERT_NewMat = "INSERT INTO $documents (docu_id, docu_title, docu_abstract, docu_sbjcarea, docu_level, docu_restype, docu_file, docu_filetype, docu_filesize, docu_date, docu_cat, docu_amount, docu_owner) values ('$ResMatID', '$vResMatTitle', '$vDescription', '$vSubjectArea', '$vLevel', '$vResourceType', '$file_name', '$ext', '$file_size', '$PlDate', '$vCat', '$vAmount', '$Owner')";
} mysql_query($INSERT_NewMat) or die("Couldn't execute insert operation."); header("Location:mydocuments.php"); exit(); …………
The code for the Forum is not included in this book. You can develop this using the Yahoo e-Group as your model. The Online Tutorials are simply links to
websites dealing with the tutorials (see the portion of the code of main.php that shows the links to the Online Tutorials).
CHAPTER REVIEW Login authentication and validation using the database are shown in a more detailed manner in this chapter. The technique of editing of data in the database as shown in Chapter 03 is again shown in here with some improvements. How to upload files from your computer to the web serverâ&#x20AC;&#x2122;s directory using PHP scripts is not really difficult to program: simply use the PHP function copy().
EXERCISES Add a PHP code for uploading a picture of each of the contacts in the My Personal Address Book website. For additional exercises, go to the DrRefreâ&#x20AC;&#x2122;s Books: http://www.teachlearn-online.net/aerbooks/ .
CHAPTER 7 – Uploading and Downloading Files (documents and images) for Sharing OVERVIEW Uploading files using PHP&MySQL are easily programmed with the help of the HTML form, and the PHP function copy(). We have seen this in Chapter 06 in usr_opt.php but not explained in detail. We explain this fully in this chapter. The simplest way to have a file downloadable is to create a link to the file using HTML tag: <A href=”filenamewithextension“>FilenameWithExtension</A> Clicking this link triggers the browser to send a request to the web server for the file and ask the user whether to open it or save it.
Uploading Files In our Alumni Portal project, uploading of files (Add New Material in mydocuments.php and modify picture in myprofile.php) are done in the usr_opt.php. The new material file is copied from your computer hard disk directory and saved to the (root directory)/materials folder of your web server; the photo image is saved to the (root directory)/mempic folder. In order for these files to be successfully stored in these folders, you have to modify the folders’ permission to 777 in the File Manager of the cPanel of your web server. How to do this? Do the following steps: 1. Go to the cPanel of your website (in the case of awardspace.com, this is http://cp5.awardspace.com/) 2. Enter your given username and password. 3. Go to the File Manager 4. Choose the web server root directory (in the case of awardspace.com, this is the folder of the subdomain you created). 5. Check the materials folder at the right panel and click the Change Permissions at the top tool bar (in the case of awardspace.com, click the materials folder). 6. Check all the boxes to make permissions 777.
7. Uncheck the materials folder and check the mempic folder; then, click the Change Permissions at the top tool bar. 8. Check all the boxes to make permissions 777 9. Logout Let us look again at the portions of usr_opt.php that perform the uploading of files:
Figure 1. Excerpt from usr_opt.php for uploading files into the materials folder as viewed in the Winsyntax editor. The following is a clearer presentation of the scripts of this excerpt of usr_opt.php: ............ } else if ($option == 'NewMaterial') { $dl = "http://alumniproj.awardspace.info/materials"; //url where files are uploaded - replace with the one of yours $absolute_path =
"/home/www/alumniproj.awardspace.info/materials/"; //Absolute path to where files are uploaded - replace with the one of yours $websiteurl = "http://alumniproj.awardspace.info/materials/"; //Url to you website - replace with the one of yours $ext = strrchr($file_name,'.'); $dir = "dir"; if ($file != "") { if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less."); } $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } if ($Category == 'V1') { $vCat = "Free"; $INSERT_NewMat = "INSERT INTO $documents (docu_id, docu_title, docu_abstract, docu_sbjcarea, docu_level, docu_restype, docu_file, docu_filetype, docu_filesize, docu_date, docu_cat, docu_owner) values ('$ResMatID', '$vResMatTitle', '$vDescription', '$vSubjectArea', '$vLevel', '$vResourceType', '$file_name', '$ext', '$file_size', '$PlDate', '$vCat', '$Owner')";
} else { $vCat = "For a Fee"; $INSERT_NewMat = "INSERT INTO $documents (docu_id, docu_title, docu_abstract, docu_sbjcarea, docu_level, docu_restype, docu_file, docu_filetype, docu_filesize, docu_date, docu_cat, docu_amount, docu_owner) values ('$ResMatID', '$vResMatTitle', '$vDescription', '$vSubjectArea', '$vLevel', '$vResourceType', '$file_name', '$ext', '$file_size', '$PlDate', '$vCat', '$vAmount', '$Owner')";
}
mysql_query($INSERT_NewMat) or die("Couldn't execute insert operation."); header("Location:mydocuments.php"); exit(); ………… ………… } else if ($option == 'ModPic') { $dl = "http://alumniproj.awardspace.info/mempic"; //url where files are uploaded - replace with the one of yours $absolute_path = "/home/www/alumniproj.awardspace.info/mempic/"; //Absolute path to where files are uploaded - replace with the one of yours $websiteurl = "http://alumniproj.awardspace.info/mempic/"; //Url to you website - replace with the one of yours $ext = strrchr($file_name,'.'); $dir = "dir"; if ($file != "") { if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less."); } $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } $Update = "UPDATE $member_profile SET member_pic='$file_name' WHERE member_id='$MemID'"; mysql_query($Update) or die("Couldn't execute update operation."); header("Location:myprofile.php?v_idno=$MemID"); exit(); …………
The PHP script: @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); does the job of copying and $Update = "UPDATE $member_profile SET member_pic='$file_name' WHERE member_id='$MemID'";
mysql_query($Update) or die("Couldn't execute update operation.");
does the job of storing the file.
Downloading Files To know how to make files downloadable, let us look at the portion of the details.php involving resource materials uploaded by a member: …………. <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="3"> <tr> <td width="100%"> <img border="0" src="images/spcr3.gif" width="7" height="5"> </td> </tr> <?php require "config/common.inc.php"; require "config/db_connect.php"; $SQL_DocDetails = "SELECT * FROM $documents WHERE docu_id = '$MatID'"; $DocDetails = mysql_query($SQL_DocDetails) or die("Couldn't execute query."); while($Mat = mysql_fetch_row($DocDetails)) { $MatID = $Mat[0]; $MatTitle = $Mat[1]; $MatAbstract = $Mat[2]; $MatSbjcArea = $Mat[3]; $MatLevel = $Mat[4]; $MatResType = $Mat[5]; $MatFile = $Mat[6]; $MatFileType = $Mat[7]; $MatFileSize = $Mat[8]; $MatDate = $Mat[9]; $MatCat = $Mat[10]; $MatAmount = $Mat[11]; $MatOwner = $Mat[13]; } if ($MatFileType == ".doc") {
$DocTypeDesc = "(This is a Word Document file and can be open by MSWORD)"; } else if ($MatFileType == ".xls") { $DocTypeDesc = "(This is a Spreadsheet Document file and can be open by MSEXCEL)"; } else if ($MatFileType == ".ppt") { $DocTypeDesc = "(This is a Presentation Document file and can be open by MSPOWERPOINT)"; } else if ($MatFileType == ".pdf") { $DocTypeDesc = "(This is a PDF Document file and can be open by Acrobat Reader)"; } if ($MatCat == 'Free') { $vMatCat = "Free Download"; } else { $vMatCat = "Download for ".$MatAmount; } $SQL_Author = "SELECT member_id, member_lname, member_fname, member_mname, member_email FROM $member_profile WHERE member_id = '$MatOwner'"; $Author_Res = mysql_query($SQL_Author) or die("Couldn't execute query."); while($Author = mysql_fetch_row($Author_Res)) { $AuthorID = $Author[0]; $AuthorLName = $Author[1]; $AuthorFName = $Author[2]; $AuthorMName = $Author[3]; $AuthorEmail = $Author[4]; } $AuthorName = strtoupper($AuthorFName." ".substr($AuthorMName,0,1).". ".$AuthorLName);
?>
<tr> <td width="100%"><p><b><font face="Arial" size="3" color="#CC3300"><? echo $MatTitle; ?></font></b></td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%" bgcolor="#000000"><img border="0" src="images/spcr3.gif" width="7" height="5"></td> </tr> <tr> <td width="100%"> <img border="0" src="images/spcr3.gif" width="7" height="5"> </td> </tr> <tr> <td width="100%"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td width="100%" bgcolor="#EEEEEE" colspan="3"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%" bgcolor="#C0C0C0"><font style="font-size: 8pt" face="Zurich BT,Arial"><b>&nbsp;&nbsp;Sellers Description</b></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#EEEEEE" colspan="3"> <table border="0" width="100%" cellspacing="0" cellpadding="15"> <tr> <td width="100%" bgcolor="#FBFBFB"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatAbstract; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0"
src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Subject Area </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatSbjcArea; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial">Level</font></td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich
BT,Arial"><? echo $MatLevel; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial"> Type of Resource </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <tr> <td width="100%"><font style="font-size: 8pt" face="Zurich BT,Arial"><? echo $MatResType; ?></font></td> </tr> </table> </td> </tr> <tr> <td width="100%" bgcolor="#000000" colspan="3"><img border="0" src="images/spcr8.gif" width="7" height="1"></td> </tr> <tr> <td width="2%" bgcolor="#FBD088">&nbsp;</td> <td width="18%" bgcolor="#FBD088"> <table border="0" width="100%" cellspacing="0" cellpadding="4"> <tr> <td width="100%"> <font style="font-size: 8pt" face="Zurich BT,Arial">
File Name </font> </td> </tr> </table> </td> <td width="80%" bgcolor="#FEEDCF"> <table border="0" width="100%" cellspacing="0" cellpadding="6"> <?php if ($MatCat == 'Free') { print "<tr>"; print "<td width='100%'><a href='materials/$MatFile'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatFile</font></a></td>"; print "</tr>"; } else { print "<tr>"; print "<td width='100%'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatFile</font></td>"; print "</tr>"; } ?> </table> </td> </tr> …………
The PHP script: print "<td width='100%'><a href='materials/$MatFile'><font style='font-size: 8pt' face='Zurich BT,Arial'>$MatFile</font></a></td>"; when rendered will show the name of the file with its extension as in the following:
When you click the File Name link, you will be shown a dialogue window as in the following:
Thus, you can open the file or save it to your computer.
CHAPTER REVIEW In order to save/store the uploaded files into the web serverâ&#x20AC;&#x2122;s directory/folder, the permissions of the folder should be changed to 777. Have this done in the cPanel of your website.
EXERCISES Add a folder in the (root directory)/addrbook. Have the permissions of this folder changed to 777. Add in the Menu of your Personal Address Book a PHP code for uploading files into the added folder. Have these files listed out on a page and downloadable. For additional exercises, go to the DrRefreâ&#x20AC;&#x2122;s Books: http://www.teachlearn-online.net/aerbooks/ .
OVERALL SUMMARY Conclusion and Recommendation This book was developed with the assumption that the user/learner has just a basic understanding of computer programming not beyond web authoring using HTML. Those who do not have the basic understanding of HTML, Javascript, and CSS are provided online tutorial references in the Bibliography of this book. These tutorials can be learned without much difficulty. DrRefre’s School on the Web (http://www.teachlearn-online.net/aersow/) and DrRefre’s Books (http://www.teachlearn-online.net/aerbooks) are free web reference that can be used as a starter. Additional references can be seen in the Glossary, Appendix I, and Appendix II This book has applied the principles of Constructivism (i.e. building new knowledge upon acquired knowledge) and Constructionism (i.e. learning by doing – experiential learning). This book has provided you with tutorial-style content and Sample Program Capsule containing easy-to-use, real, and open programming environments in which to try as a foundation for building the Project Alumni Portal dynamic website. The Internet and the Web have enabled coaching anywhere and anytime. The author takes cognizance of this innovation that in case you need further help, visit DrRefre’s Books website: http://www.teachlearn-online.net/aerbooks/. This book can be used in the last year of secondary education by selecting some lessons in chapters 01, 02, and 03 that can already build a simple dynamic website. In college (tertiary and postgraduate), this book can be a very good companion in courses involving web applications development. For those who are or would like to become a Web Portal Developer, this book will surely be a very profitable reference. It is recommended that you further develop the Project Alumni Portal by incorporating a Collaboration and Messaging Site to make you adept in using PHP and MySQL in creating dynamic/database-driven websites.
GLOSSARY PHP and MySQL Statements and Functions Used in this Book
CONTROL STRUCTURES The next examples will show you how to use control structures in PHP. We will not go through all but just the ones that we will use in the code examples in this booksite. The control structures are if else while for If Else The if statement evaluates the truth value of it's argument. If the argument evaluates as TRUE the code following the if statement will be executed. And if the argument evaluate as FALSE and there is an else statement then the code following the else statement will be executed. Example: <?php $ip = $_SERVER['REMOTE_ADDR']; $agent = $_SERVER['HTTP_USER_AGENT']; if(strpos($agent, 'Opera') !== false) $agent = 'Opera'; else if(strpos($agent, "MSIE") !== false) $agent = 'Internet Explorer'; echo "Your computer IP is $ip and you are using $agent"; ?>
The strpos() function returns the numeric position of the first occurrence of its second argument ('Opera') in the first argument ($agent). If the string 'Opera' is found inside $agent, the function returns the position of the string. Otherwise, it returns FALSE. When you're using Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT'] would be something like: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) and if you're using Opera the value the value may look like this :
Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.0 [en] So if you use Opera the strpos() function will return value would be 61. Since 61 !== false then the first if statement will be evaluated as true and the value of $agent will be set to the string 'Opera'. Note that we use the !== to specify inequality instead of != The reason for this is because if the string is found in position 0 then the zero will be treated as FALSE, which is not the behavior that we want. While Loop The while() statement is used to execute a piece of code repeatedly as long as the while expression evaluates as true. For example the code below will print the number one to nine. Example: <?php $number = 1; while ($number < 10) { echo $number . '<br>'; $number += 1; } ?>
You see that we make the code $number += 1; as bold. We did it simply to remind that even an experienced programmer can sometime forget that a loop will happily continue to run forever as long as the loop expression ( in this case $number < 10 ) evaluates as true. So when you're creating a loop please make sure you already put the code to make sure the loop will end in timely manner. Break The break statement is used to stop the execution of a loop. As an example the while loop below will stop when $number equals to 6. Example: <?php $number = 1; while ($number < 10) { echo $number . '<br>'; if ($number == 6) {
break; } $number += 1; } ?>
You can stop the loop using the break statement. The break statement however will only stop the loop where it is declared. So if you have a cascading while loop and you put a break statement in the inner loop then only the inner loop execution that will be stopped. Example: <?php $floor = 1; while ($floor <= 5) { $room = 1; while ($room < 40) { echo "Floor : $floor, room number : $floor". "$room <br>"; if ($room == 2) { break; } $room += 1; } $floor += 1; echo "<br>"; } ?>
If you run the example you will see that the outer loop, while ($floor <= 5), is executed five times and the inner loop only executed two times for each execution of the outer loop. This is the proof, that the break statement only stops the execution of the inner loop where it is declared. For The for loop syntax in PHP is similar to C. For example to print 1 to 10 the for loop is like this shown below: <?php for ($i = 1; $i <= 10; $i++) { echo $i . '<br>'; } ?>
A more interesting function is to print this number in a table with alternating colors. Here is the code: Example: <html> <head><title>Alternate-Colors</head> <body> <table width="200" border="0" cellspacing="1" cellpadding="2"> <tr> <td bgcolor="#CCCCFF">Alternating row colors</td> </tr> <?php for ($i = 1; $i <= 10; $i++) { if ($i % 2) { $color = '#FFFFCC'; } else { $color = '#CCCCCC'; } ?> <tr> <td bgcolor="<?php echo $color; ?>"><?php echo $i; ?></td> </tr> <?php } ?> </table> </body> </html>
This code displays different row colors depending on the value of $i. If $i is not divisible by two it prints yellow otherwise it prints gray colored rows. Copy file from Local to Web Server @copy($file, "$absolute_path/$file_name") Example: } else if ($option == 'ModPic') { $dl = "http://aerefre.890m.com/mempic"; //url where files are uploaded $absolute_path = "/home/a9553135/public_html/mempic/"; //Absolute path to where files are uploaded $websiteurl = "http://aerefre.890m.com/mempic/"; //Url to you website $ext = strrchr($file_name,'.'); $dir = "dir"; if ($file != "") {
if (($sizelimit == "yes") && ($file_size > $sizebytes)) { die("File is to big. It must be $sizebytes bytes or less."); } $ext = strrchr($file_name,'.'); if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { die("The file you are uploading doesn't have the correct extension."); } @copy($file, "$absolute_path/$file_name") or die("The file you are trying to upload couldn't be copied to the server"); } $Update = "UPDATE $member_profile SET member_pic='$file_name' WHERE member_id='$MemID'"; mysql_query($Update) or die("Couldn't execute update operation.");
echo () Output one or more strings
echo ( string $arg1 [, string $... ] ) Outputs all parameters. echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses. Sending Email $subject = $vSubject; $email_message = $vMessage; $sendto = $vSendto; $sender = $vFrom; $toAddress = $sendto; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: $sender\r\n"; $headers .= "Cc: aerefre@gmail.com\r\n"; mail($toAddress, $subject, $email_message, $headers);
Sending HTML Email Example: $toName = "Dr. Antonio E. Refre"; $toAddress = "DR. ANTONIO E. REFRE <aerefre@gmail.com>"; $subject = "HS Class 2008 Membership Application."; $email_message = " <p>Message alert!</p> <p>Details of new HS Class 2008 Membership Application.</p> <table> <tr> <td>Name</td> <td>:</td> <td>$vlast_name,&nbsp;$vfirst_name&nbsp;$vmiddle_name</td> </tr> <tr> <td>Gender</td> <td>:</td> <td>$vGender</td> </tr> <tr> <td>Tel. No.</td> <td>:</td> <td>$vphone / $vhome_telno</td> </tr> <tr> <td>Mobile Phone</td> <td>:</td> <td>$vmobphone</td> </tr> <tr> <td>E-mail Address</td> <td>:</td> <td><a href='mailto:$cookie_email'>$vemail_address</a></td> </tr> <tr> <td>Postal Address</td> <td>:</td> <td>$vhome_address</td> </tr> <tr> <td>Application Member Type</td> <td>:</td> <td>$vMemType</td> </tr> <tr> <td colspan='3' bgcolor='#000000'></td> </tr>
</table> "; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: $vfirst_name $vlast_name <$vemail_address>\r\n"; $headers .= "Cc: aerefre@gmail.com\r\n"; mail($toAddress, $subject, $email_message, $headers); session(), session_register(), authenticateuser() <?php session_start(); session_register("v_idno"); session_register("v_user"); session_register("v_pass"); require "functions.php"; if (authenticateUser($v_usrnam, $v_usrpas)) { $v_user = $v_usrnam ; $v_pass = $v_usrpas ; require "config/common.inc.php"; global $hostname, $username, $password, $dbname, $user_account, $user_profile, $user_level; if (!($connection = mysql_connect($hostname, $username, $password))) { echo "Couldn't connect to server."; return 0; } $db = mysql_select_db($dbname) or die ("Couldn't select database."); $sql = "SELECT idno, username, password, member_type FROM $member_usracnt WHERE username ='$v_user' AND password ='$v_pass'"; $result = mysql_query($sql) or die("Couldn't execute query."); while($e_row = mysql_fetch_row($result)) { $v_idno = $e_row[0]; $v_memtype = $e_row[3]; } if ($v_memtype == 'Relative') {
$accepted = "yes"; header("Location:main.php"); exit(); } else if ($v_memtype == 'Member') { $accepted = "yes"; header("Location:main.php"); exit(); } else { $accepted = "no"; header("Location:index.php"); exit(); } } else { $accepted = "no"; header("Location:index.php?Login=failure"); exit(); } ?>
Take note on how the variables from the login form in the index.php are passed into the login.php through PHP function session_register(). If login is successful, the main.php is triggered
String Concatenation <?php $quote1 = "Never insult Dumbledore " . "in front of me!"; $quote2 = "Nami, you are my nakama!"; echo $quote1 . "<br>"; echo $quote2; ?>
String Functions substr($string, $start, $end) get a chunk of $string <?php // print '12' echo substr('123456789', 0, 2); // print '56789' echo substr('123456789', 4); // print '89' echo substr('123456789', -2);
// print '456' echo substr('123456789', 3, -4); ?>
str_repeat($string, $n) repeat $string $n times For example if you want to print a series of ten asteriks ( * ) you can do it with a for loop like this : <?php for ($i = 0; $i < 10; $i++) { echo '*'; } ?>
Or you can go the easy way and do it like this : <?php echo str_repeat('*', 10); ?>
strrchr($string, $char) find the last occurrence of the character $char in $string For example: you want to get the file extension from a file name. You can use this function in conjunction with substr() <?php $ext = substr(strrchr($filename, '.'), 1); ?>
What the above code do is get a chunk of $filename starting from the last dot in $filename then get the substring of it starting from the second character ( index 1 ). To make things clearer suppose $filename is 'tutorial.php'. Using strrchr('tutorial.php', '.') yield '.php' and after substr('.php', 1) we get the file extension; 'php' trim($string) remove extra spaces at the beginning and end of $string <?php // print 'abc def' echo trim(' abc def ?>
');
addslashes($string) adding backslashes before characters that need to be quoted in $string This function is usually used on form values before being used for database queries. explode($separator, $string) Split $string by $separator This function is commonly used to extract values in a string which are separated by a certain separator string. For example, suppose we have some information stored as comma separated values. To extract each values we can do it like shown below <?php // extract information from comma separated values $csv = 'Uzumaki Naruto,15,Konoha Village'; $info = explode(',', $csv); ?>
Now, $info is an array with three values: Array ( [0] => Uzumaki Naruto [1] => 15 [2] => Konoha Village )
We can further process this array like displaying them in a table, etc. implode($string, $array) Join the values of $array using $string This one does the opposite of the previous explode function. For example to reverse back the $info array into a string we can do it like shown below: <?php $info = array('Uzumaki Naruto', 15, 'Konoha Village'); $csv = implode(',', $info); ?>
Another example : Pretend we have an array containing some values and we want to print them in an ordered list. We can use the implode() like this : <?php // print ordered list of names in array $names = array('Uchiha Sasuke', 'Haruno Sakura', 'Uzumaki Naruto', 'Kakashi'); echo '<ol><li>' . implode('</li><li>', $names) . '</li></ol>'; ?>
The result of that code is like an ordered list just like shown below 1. Uchiha Sasuke 2. Haruno Sakura 3. Uzumaki Naruto 4. Kakashi By the way, we did write the above php code to print that list instead of writing the list directly number_format($number) display a number with grouped thousands When displaying numbers it is usually more readable if the numbers is properly formatted like 1,234,567 instead of 1234567. Using this function is very simple like shown below: <?php // display 15,120,777 echo number_format(15120777); ?> $ip = $_SERVER['REMOTE_ADDR']; $agent = $_SERVER['HTTP_USER_AGENT']; if(strpos($agent, 'Opera') !== false) $agent = 'Opera'; else if(strpos($agent, "MSIE") !== false) $agent = 'Internet Explorer'; echo "Your computer IP is $ip and you are using $agent"; $number = 1; while { echo $number += 1;
($number $number
< .
10) '<br>';
USING FUNCTION Real world applications are usually much larger than the examples above. It has been proven that the best way to develop and maintain a large program is to construct it from smaller pieces (functions) each of which is more manageable than the original program. A function may be defined using syntax such as the following: <?php function addition($val1, $val2) { $sum = $val1 + $val2; return $sum; } ?>
Using Default Parameters When calling a function you usually provide the same number of argument as in the declaration. Like in the function above you usually call it like this : $result = addition(5, 10);
But you can actually call a function without providing all the arguments by using default parameters. Example: <?php function repeat($text, $num = 10) { echo "<ol>\r\n"; for($i = 0; $i < $num; $i++) { echo "<li>$text </li>\r\n"; } echo "</ol>"; } // calling repeat with two arguments repeat("I'm the best", 15); // calling repeat with just one argument repeat("You're the man"); ?>
Function repeat() has two arguments $text and $num. The $num argument has a default value of 10. The first call to repeat() will print the text 15 times because the value of $num will be 15. But in the second call to repeat() the second parameter is omitted so repeat() will use the default $num value of 10 and so the text is printed ten times. Returning Values Applications are usually a sequence of functions. The result from one function is then passed to another function for processing and so on. Returning a value from a function is done by using the return statement. Example: <?php $myarray = array('php tutorial', 'mysql tutorial', 'apache tutorial', 'java tutorial', 'xml tutorial'); $rows = buildRows($myarray); $table = buildTable($rows); echo $table; function buildRows($array) { $rows = '<tr><td>' . implode('</td></tr><tr><td>', $array) . '</td></tr>'; return $rows; } function buildTable($rows) { $table = "<table cellpadding='1' cellspacing='1' border='1'>$rows</table>";
bgcolor='#FFCC00'
return $table; } ?>
You can return any type from a function. An integer, double, array, object, resource, etc. Notice that in buildRows() we use the built in function implode(). It joins all elements of $array with the string '</td></tr><tr><td>' between each element. weI also use the '.' (dot) operator to concat the strings.
You can also write buildRows() function like this shown below: <?php ... function buildRows($array) { $rows = '<tr><td>'; $n = count($array); for($i = 0; $i < $n - 1; $i++) { $rows .= $array[$i] . '</td></tr><tr><td>'; } $rows .= $array[$n - 1] . '</td></tr>'; return $rows; } ... ?>
Of course it is more convenient if you just use implode(). WORKING WITH DATABASES Connecting to the Database and Querying it $connection = mysql_connect($hostname, $username, $password) or die ("Couldn't connect to server."); $db = mysql_select_db($dbname) or die ("Couldn't select database.");
Listing of data in the table of a database $sql1 = "SELECT lastname, firstname, midname, phone FROM contacts ORDER BY lastname"; $result1 = mysql_query($sql1) or die ("Couldn't execute query."); $cnt = 0; $vline = 1; while($e_row = mysql_fetch_row($result1)) { $vlnam = $e_row[0] ; $vfnam = $e_row[1] ; $vmnam = $e_row[2] ;
$vphone = $e_row[3] ; $cnt = $cnt + 1 ; $vname = trim($vlnam).","." ".trim($vfnam)." ".substr($vmnam,0,1) ; if ($vline == 1) { $bg_color = "#F0F0FF"; $vline = 2; } else { $bg_color = "#F9F9FF"; $vline = 1; } print "<tr>"; print "<td width='1%' bgcolor='$bg_color'><p align='left'><font size='3' face='Verdana'>$cnt.</font></td>"; print "<td width='5%' bgcolor='$bg_color'><p align='left'><font size='3' face='Verdana'>$vname</font></td>"; print "<td width='5%' bgcolor='$bg_color'><p align='left'><font face='Verdana' size='3'>$vphone</font></td>"; print "</tr>"; }
Adding of data in the table of a database $sql_insert = "INSERT INTO contacts (userid, password, lastname, firstname, midname, gender, phone, email, address, category, yearofbirth) values ('$vemail', '$UserPasswd', '$vlastname', '$vfirstname', '$vmidname', '$vgender', '$vphone', '$vemail', '$vaddress', '$vcategory', '$vyearofbirth')"; mysql_query($sql_insert) or die("Couldn't execute insert operation");
Editing of data in the table of a database $UPDATE_Prof = "UPDATE contacts SET userid='$vemail', lastname='$vlastname', lirstname='$vfirstname', midname='$vmidname', gender='$vgender', phone='$vphone', email='$vemail', address='$vaddress', category='$vcategory', yearofbirth='$vyearofbirth' WHERE userid = '$v_id'"; mysql_query($UPDATE_Prof) or die("Couldn't execute update query.");
Deleting of data in the table of a database
$sql_delete = "DELETE FROM contacts WHERE userid ='$vid'"; mysql_query($sql_delete) ;
Inserting into a HTML <table border="0" cellpadding="0" width="50%" cellspacing="0"> <tr> <td width="100%"><img border="0" src="images/header.gif" width="828" height="90"></td> <? require "main_menu.php"; ?> <td width="100%" bgcolor="#FFFFFF"><img border="0" src="images/menu_bar_bottom.gif" width="828" height="7"></td> </tr> require "config/common.inc.php"; require "config/db_connect.php";
The PHP function require is used to include a file into your PHP code. The PHP function include may also be used but require is a better choice. include "config/common.inc.php"; include "config/db_connect.php";
The main_menu.php required is as in the following: <?php print"<tr>"; print"<td width='100%' bgcolor='#FFFFFF' background='images/menu_bar.gif'>"; print"<table border='0' cellpadding='0' width='100%' cellspacing='0'>"; print"<tr>"; print"<td width='1%'><p align='center'></td>"; print"<td width='8%'><p align='center'><b><a href='index.php'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>Home</font></a></b></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='8%'><p align='center'><b><A HREF='javascript:makenew()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>About Us</A></font></b></font></td>";
print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='15%'><p align='center'><b><A HREF='javascript:make1957pics()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>1957 Pictures</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='8%'><p align='center'><b><A HREF='javascript:makegallery()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>Gallery</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='8%'><p align='center'><b><A HREF='javascript:makenews()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>News</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='12%'><p align='center'><b><A HREF='javascript:makecalevents()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>EventsCalendar</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='8%'><p align='center'><b><A HREF='upload/index.html' target = '_blank'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>INVITATION</A></font></b></font></td>"; print"<td width='2%'><p align='center'><img border='0' src='images/menu_bar_div.gif' width='7' height='25'></td>"; print"<td width='17%'><p align='center'><b><A HREF='javascript:makedirectory()'><font style='font-size: 8pt' color='#FFFFFF' face='Zurich BT,Arial'>MembersDirectory</A></font></b></font></td>"; print"<td width='1%'><p align='center'></td>"; print"</tr>"; print"</table>"; print"</td>"; print"</tr>";
?>
The Print () does the inserting of HTML tags.
BIBLIOGRAPHY Reference Tutorial Websites
The PHP Manual: http://www.php.net/manual/en/index.php This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.
The MySQL Reference Manual: http://dev.mysql.com/doc/ This manual covers most areas of MySQL use.
HTML Tutorial: http://www.w3schools.com/html/ In this HTML tutorial you will learn how to use HTML to create your own Web site. Client-Side JavaScript Reference: http://docs.sun.com/source/816-6408-10/ This book is a reference manual for the JavaScript language, including both core and client-side JavaScript for version 1.3. JavaScript is Netscape's crossplatform, object-based scripting language for client and server applications. CSS Tutorial 1. http://www.csstutorial.net/ This website is all about CSS, a key tool in web design. In case you're not familiar with CSS. CSS is the sister technology to HTML that is used to style your web pages. 2. http://www.w3schools.com/Css/default.asp In this CSS tutorial you will learn how to use CSS to control the style and layout of multiple Web pages all at once.
APPENDIX I WINDOWS INSTALLATION OF WEB SERVER USING WampServer It is normally recommended that you install and set up your web server, PHP, and MySQL individually, using the official installation packages for each. This is especially useful for beginners, because it gives you a strong sense of how these pieces all fit together. However, this is a complex process that will take you an awful lot ot time to accomplish. Let us do a quick solution by using the popular WampServer. WampServer (where Wamp stands for Windows, Apache, MySQL, and PHP) is a free, all-in-one program that includes built-in copies of recent versions of the Apache web server, PHP, and MySQL. Go through the following steps of installing it: 1. Download the latest version from theWampServer web site. (http://www.wampserver.com/en/) After downloading the file (as of this writing, WampServer 2.0g is about 16MB in size), doubleclick it to launch the installer, as shown in Figure 1.
Figure 1. The WampServer installer 2. The installer will prompt you for a location to installWampServer. The default of c:\wamp shown in Figure 2 is an ideal choice for most purposes, but if you have strong feelings about where itâ&#x20AC;&#x2122;s installed, feel free to specify your preferred location.
Figure 2. The default installation directory is a good choice 3. At the end of the installation, WampServer will ask you to choose your default browser. This is the web browser it will launch when you use the included system tray icon tool to launch your browser. If you have Firefox installed it will ask if youâ&#x20AC;&#x2122;d like to use it as your default browser. If you answer No, or have a different browser installed, it will ask you to select the executable file for the browser you want to use. As shown in Figure 3, it selects Internet Explorer (explorer.exe) for you, which is fine. If youâ&#x20AC;&#x2122;re using an alternative browser such as Chrome, Safari or Opera, you can browse to find the .exe file for your browser if you want to.
Figure 3. The default choice of Internet Explorer is fine 4. As WampServer is installed, it fires up its built-in copy of the Apache HTTP Server, a popular web server for PHP development.Windows will likely display a
security alert at this point, like the one in Figure 4, since the web server attempts to start listening for browser requests from the outside world.
Figure 4. This security alert tells you Apache is doing its job If you want to make absolutely sure that Apache rejects connections from the outside world, and that only a web browser running on your own computer can view web pages hosted on your development server, feel free to click Keep blocking. WampServer has its own built-in option to block connections from the outside world when you want to, however, so I recommend clicking Unblock in order to have the flexibility to grant access to your development server if and when you need to. 5. Next, as shown in Figure 5, the WampServer installer will prompt you for your SMTP server and email address. A PHP script can send an email message, and these settings tell it the outgoing email server, and the default “from” address to use. Type in your email address, and if you can remember your Internet Service Provider’s SMTP server address, type it in too. You can always leave the default value for the time being, though, and set it manually if and when you need to send email using a PHP script.
Figure 5. Fill in your Internet Service Providerâ&#x20AC;&#x2122;s SMTP server address if you know it Once the installation is complete, you can fire up WampServer. An icon will appear in your Windows System Tray. Click on it to see the WampServer menu shown in Figure 6.
Figure 6. The WampServer menu By default, your server can only be accessed by web browsers running on your own computer. If you click the Put Online menu item, your server will become accessible to the outside world.
To test that WampServer is working properly, click the Localhost menu item at the top of the WampServer menu. Your web browser will open to display your server’s home page, shown in Figure 7.
Figure 7. The home page provided by WampServer confirms Apache, PHP, and MySQL are installed When you’re done working with WampServer, you can shut it down (along with its built-in servers) by right-clicking the System Tray icon and choosing Exit. When you’re next ready to do some work on a database driven web site, just fire it up again! You will need to use some of the programs that come with the MySQL server built into WampServer. To work properly, these programs must be added to your Windows system path. To add the MySQL command prompt programs that come with WampServer to your Windows system path, follow these instructions: 1. Open the Windows Control Panel. Locate and double-click the System icon. 2. Take the appropriate step for your version of Windows: • In Windows XP, switch to the Advanced tab of the System Properties window. • In Windows Vista or Windows 7, click the Advanced system settings link in the sidebar. 3. Click the Environment Variables… button. 4. In the list labeled User variables for user, look for a variable named PATH. • If it exists, select it and click the Edit… button.
• If there’s no variable, click the New… button and fill in the Variable name by typing PATH. 5. Add the path to WampServer’s MySQL bin directory2 as the Variable value: • If the Variable value is empty, just type in the path. • If there is already text in the Variable value field, add a semicolon (;) to the end of the value, then type the path after that. 6. Click the OK button in each of the open windows to apply your changes. What to do after installation Once PHP is installed and the MySQL server is functioning, the very first action you need to perform is assign a root password for MySQL. MySQL only allows authorized users to view and manipulate the information stored in its databases, so you wll need to tell MySQL who is authorized and who is unauthorized. When MySQL is first installed, it’s configured with a user named root that has access to do most tasks without even entering a password. Your first task should be to assign a password to the root user so that unauthorized users are prohibited from tampering with your databases. Importance of Security It is important to realize that MySQL, just like a web server, can be accessed from any computer on the same network. If you’re working on a computer connected to the Internet, then, depending on the security measures you’ve taken, anyone in the world could connect to your MySQL server. The need to pick a difficult-to-guess password should be immediately obvious! To set a root password for MySQL, you can use the mysqladmin program that comes with MySQL. If you followed the instructions to install MySQL separately (as explained earlier in this chapter), the mysqladmin program should be on your system path. This means you can pop open a Terminal window (or inWindows, a Command Prompt) and type the name of the program without having to remember where it’s installed on your computer. Go ahead and try this now, if you have yet to already. Open a Terminal or Command Prompt and type this command: mysqladmin -u root status When you hit Enter you should see a line or two of basic statistics about your MySQL server, like this: Uptime: 102261 Threads: 1 Questions: 1 Slow queries: 0 Opens: 15 Flush tables: 1 Open tables: 0 Queries per second avg: 0.0 If you’re seeing a different message entirely, it’s probably one of two options. First, you might see an error message telling you that the mysqladmin program was unable to connect to your MySQL server: mysqladmin: connect to server at 'localhost' failed error: 'Can't connect to MySQL server on 'localhost' (10061)' Check that mysqld is running on localhost and that the port is 3306. You can check this by doing 'telnet localhost 3306' This message normally means that your MySQL server simply is not running. If you have it set up to run automatically when your system boots, double-check that
the setup is working. If you normally launch your MySQL server manually, go ahead and do that before trying the command again. You are done! With everything set up and running, you’re ready to write your first PHP script. Before we do that, however, you might want to write a short email to your web host. What to Ask Your Web Host While you tinker with PHP and MySQL on your own computer, it might be good to start collecting the information you’ll need when it comes time to deploy your first database driven web site to the public. Here’s a rundown of the details you should be asking your web host for. First, you’ll need to know how to transfer files to your web host. You’ll upload PHP scripts to your host the same way you normally send the HTML files, CSS files, and images that make up a static web site, so if you already know how to do that, it’s unnecessary to bother your host. If you’re just starting with a new host, however, you’ll need to be aware of what file transfer protocol it supports (FTP or SFTP), as well as knowing what username and password to use when connecting with your (S)FTP program. You also have to know what directory to put files into so they’re accessible to web browsers. In addition to these, you’ll also need to find out a few details about the MySQL server your host has set up for you. It’s important to know the host name to use to connect to it (possibly localhost), and your MySQL username and password, which may or may not be the same as your (S)FTP credentials. Your web host will probably also have provided an empty database for you to use, which prevents you from interfering with other users’ databases who may share the same MySQL server with you. If they have provided this, you should establish the name of that database. Have you taken in all that? Here is a spot to record the information you will need about your web host: My Hosting Details File transfer protocol: ■ FTP■ SFTP (S)FTP host name: _________________________ (S)FTP username: _________________________ (S)FTP password: _________________________ MySQL host name: _________________________ MySQL username: _________________________ MySQL password: _________________________ MySQL database name: _________________________ Your First PHP Script It would be unfair to help you install everything—but stop short of giving you a taste of what a PHP script looks like. So here is a little morsel to whet your appetite. Open your favorite text or HTML editor and create a new file called today.php. Type this into the file:
Script of today.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Today&rsquo;s Date</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> </head> <body> <p>Today&rsquo;s date (according to this web server) is <?php echo date('l, F dS Y.'); ?> </p> </body> </html>
Editing PHP Scripts in Windows with Notepad Windows users should note that, to save a file with a .php extension in Notepad, you’ll need to either select All Files as the file type, or surround the filename with quotes in the Save As dialog box; otherwise, Notepad will unhelpfully save the file as today.php.txt, which will fail to work. Try a Free IDE! As you can tell from the preceding warnings, the text editors provided with current operating systems are a little unsuitable for editing PHP scripts. There are a number of solid text editors and Integrated Development Environments (IDEs) with rich support for editing PHP scripts that you can download for free. Here are a few that work on Windows, Mac OS X, and Linux: NetBeans http://www.netbeans.org/features/php/ Aptana http://www.aptana.com/php/ Komodo Edit http://www.activestate.com/komodo_edit/ If you’d prefer to avoid typing out all the code, you can download this file— along with the rest of the code in this book—from the code archive. See the Preface for details on how to download the code archive. Save the file, and move it to the web root directory of your local web server. Where’s My Server’s Web Root Directory? For Apache servers built into WampServer, the web root directory is the www directory within yourWampServer directory. You can reach it quickly by selecting the www directory menu item from theWampServer menu in yourWindows System Tray. Open your web browser of choice, and type http://localhost/today.php (or http://localhost:port/today.php if Apache is configured to run on a port other than the default of 80) into the address bar to view the file you just created. You Must Type the URL
You might be used to previewing your web pages by double-clicking on them, or by using the File > Open…feature of your browser. These methods tell your browser to load the file directly from your computer’s hard drive, and so they’ll fail to work with PHP files. As previously mentioned, PHP scripts require your web server to read and execute the PHP code they contain before sending the HTML code that’s generated to the browser. Only if you type the URL (http://localhost/today.php) will your browser request the file from your web server so that this can happen. Figure 8 shows what the web page generated by your first PHP script should look like.
Figure 8. See your first PHP script in action! If you use the View Source feature in your browser, all you will see is a regular HTML file with the date in it. The PHP code (everything between <?php and ?> in the code above) was interpreted by the web server and converted to normal text before it was sent to your browser. If you installed Apache on Windows, you may have selected the option to run it on port 8080. Be reassured also that before too long you will know code (like this example) as well as the back of your hand. If the date is missing, or if your browser prompts you to download the PHP file instead of displaying it, then something is wrong with your web server’s PHP support. If you can, use View Source in your browser to look at the code of the page. You’ll probably see the PHP code right there in the page. Since the browser fails to understand PHP, it just sees <?php … ?> as one long, invalid HTML tag, which it ignores. Double-check that you have requested the file from your web server rather than your hard disk (that is, make sure the location bar in your browser shows a URL beginning with http://localhost), and make sure that PHP support has been properly installed on your web server using the instructions provided earlier in this Appendix.
You should now be fully equipped with a web server that supports PHP scripts, a MySQL database server, and a basic understanding of how to use each of these. You should even have dirtied your hands by writing and successfully testing your first PHP script!
APPENDIX II HOW TO GET FREE WEBHOSTING How to Get the Free Web Hosting Service from 0fees.net: 1. Go to http://www.0fees.net/
2. Click the Order Now! Button and fill the sign up form
3. After you click Register button, you will be advised to open your email and get the pertinent information for getting into the cPanel. Go to
http://cpanel.0fees.net/
4. After successful login, click the Control Panel at the top bar menu and select domain->sub-domains.
5. Create sub-domain with your chosen domain from the drop list (in my case, I chose mypersonaladdressbook.isgreat.org and highschoolalumniportal.isgreat.org).
6. Click Control Panel at the top bar menu and select Database Management->MySQLdatabases :
7. Create your databases (in my case, I created addrbook and alumni; notice that the system prefixes your username):
8. The next thing you should do is to create tables for the database created. Click the [Admin] of the specific database and you will be directed to the phpMyAdmin. You may manually create the tables; but the easier way of doing this is by importing the sql file. Click the Import button and look for
the
specific
sql
file
to
upload:
9. To complete the process of building your site, you have to upload all the files and folders to the document root directory of the server. You can do this by going to the Control Panel->Site Management->Online File Manager:
10. Your subdomains document directories are shown. The main is htdocs. Click the respective directories and upload the relevant files and folders.
11. A better and faster way of doing the uploading of files and folders is by using an FTP client, e.g. filezilla. Install it in your computer and fill up the
necessary information to connect:
After having done the foregoing steps, test the websites you have just built using different browsers. In the examples I have given, the My Personal Address Book Website and the High School Alumni Portal are accessible by going first to the following: http://aerefreprojects.0fees.net/ http://mypersonaladdrressbook.isgreat.org/ http://highschoolalumniportal.isgreat.org/
ABOUT THE AUTHOR
Antonio E. Refre, Ph.D. #4 Legaspi St., PAEL Subd., Brgy Culiat Quezon City 1128 Philippines Tel. No. (632) 496-3381 Fax No. (632) 927-2408 CellPhone: +63920-2431560 Email: aerefre@consultant.com, aerefre@gmail.com, aerefre@yahoo.com Dr. Antonio E. Refre is a Ph.D. holder in Applied Sciences/Engineering, a Master of Chemical Engineering holder, a trained Nuclear Power Plant Safety Specialist, a registered Chemical Engineer, and a self-trained ICT expert. He is a professorial lecturer in ICT, Chemical Engineering, Nuclear Engineering, Nuclear Safety, Mathematics, and Statistics. He has developed a Learning Management System (LMS) called AERVLES for use in the universities, colleges, and training centers in their Online Education and Training. He is a well-known developer of Web applications for businesses, government/non-government organizations, and cause-oriented communities.