Your Ad Here

php web tutorial

                                       What you need

Code requires PHP version 5 and some sections will require at least version 5.1.2. Increasingly, version 5.2.3 (released May 2007) is regarded as the oldest version that should be supported by advanced software systems. At the time of writing the code is believed to run on all released PHP versions up to 5.3.2.
Examples of SQL assume MySQL of at least version 4.1 although development
will increasingly require version 5 which is now widely used by typical web
hosting services.


Beginners who have never programmed before or who have                              never worked with databases


Setting Up Your Work space


Your computer needs to be able to run as a web server with PHP and MySQL. XAMPP is a
package of software that installs the web server, PHP, and MySQL for you. You learn how to
download and install XAMPP in this lesson.
If you already have a web server with PHP and MySQL running on your computer, you do not
need XAMPP. Other packages that fulfi ll the same need are WAMPServer and MAMP.
You also need a text editor that can produce plain-text fi les. You learn how to download
and install Eclipse PDT in this lesson. Some other text editors that you can use are Adobe’s
Dreamweaver in code mode, Notepad, TextWrangler, or NetBeans.

INSTALLING XAMPP

XAMPP stands for whatever operating system you have: (X), Apache (A), MySQL (M), PHP
(P), and Perl (P). Separate packages are available for each of the different operating systems
such as Windows, Mac OS X, or Linux. This lesson covers installing the Windows and Mac
versions.
Perl is another programming language. It’s popular for housekeeping tasks and
for communications between different programs and programming languages.)



XAMPP is intended for local development work. It is not set up for running production
websites.

(Do not use XAMPP to host websites on the Internet. Although it uses the same
building blocks as production hosts, it is not set up to be secure. You will get
hacked if you try it.)





Installing XAMPP on a Windows PC

downloading the proper XAMPP package and installing it on your
Windows PC. If you have a Mac, skip forward to the section “Confi guring XAMPP on Mac OS X.”
1. Go to the Apache Friends website at www.apachefriends.org/en/xampp.html.
2. Locate the section labeled XAMPP for Windows and click the title. Scroll down to the
Download section that lists the versions available for download.

3. You have a choice of three ways to install this package: via the installer, via a ZIP fi le, or via
a 7zip fi le. The easiest way to change options is to use the installer, but you are more likely
to encounter problems. Because you are using the defaults, use the ZIP version. Click the ZIP
link and save the ZIP fi le.
4. Unzip all the fi les to c:\. The ZIP fi le contains a folder called xampp that holds all the folders
and fi les so unzipping to the c: drive creates the c:\xampp folder.
5. The program you use is c:\xampp\xampp-control.exe. In Windows Explorer, right-click
the fi le and select Create Shortcut. Drag that shortcut to your desktop.
6. Double-click the XAMPP Control desktop icon you just created. The Control Panel is displayed.



7. To start XAMPP, fi rst start the Apache web service by clicking the Start button next to
Apache. Then start MySQL by clicking the Start button next to MySQL. You do not need to
start FileZilla or Mercury. When you click the Start buttons, they change to Stop buttons
to indicate that the processes are running.
8. To stop XAMPP, click the Stop button next to MySQL and then click the Stop icon next to
Apache.
9. To test that XAMPP is properly working, go to your browser and enter http://localhost/
xampp.


If the installation is successful, Well done if not send me a buzz.









Configuring XAMPP



Now that you have successfully installed XAMPP on your Windows PC or Mac, make sure
XAMPP is running and then call up XAMPP in your browser. The address to call up XAMPP is
http://localhost/xampp.A screen similar to this


You need to create a password on MySQL. Some programs do not allow you to use MySQL unless
MySQL has a password, for security reasons. Click the phpMyAdmin link on the left-side navigation
under Tools to open the page shown in Figure 1-9.
Click Privileges on the top menu. You see a table of the users. Click the Edit icons next to the users.
Scroll down to fi nd the Change Password box as shown in Figure 1-10.
Enter a password and click Go. Do this for each of the users with All Privileges.
Now that you’ve added a password to MySQL, you need to change the confi guration in XAMPP for
phpMyAdmin so that it can access the database. The confi guration fi le is in c:\xampp\phpMyAdmin\
config.inc.php on the Windows PC or in /Applications/XAMPP/xamppfiles/phpmyadmin/
config.inc.php on the Mac. Find the following code:
/* Authentication type */
$cfg[‘Servers’][$i][‘auth_type’] = ‘config’;
/* Server parameters */
$cfg[‘Servers’][$i][‘host’] = ‘localhost’;
$cfg[‘Servers’][$i][‘user’] = ‘root’;
$cfg[‘Servers’][$i][‘password’] = ‘’;


Change the password to your new password. For instance, if your new password is !xYz72g, the
change looks like the following:
$cfg[‘Servers’][$i][‘password’] = ‘!xYz72g’;
Restart the XAMPP server by going into the Control Panel and stopping fi rst MySQL and then
Apache. Restart by starting Apache and then restarting MySQL.
Call up XAMPP in your browser and see that you can open phpMyAdmin.





INSTALLING YOUR EDITOR



You need a text editor for programming. Word processing editors such as Word change your code and
add extraneous codes and characters that invalidate your program, so you should not use them. Possible
text editors are Notepad, TextWrangler, Dreamweaver in the code mode, NetBeans, or Eclipse.
A good text editor for PHP is Eclipse PDT. It has syntax checking, auto-completion for commands,
color syntax coding, debugging, and other features that become important as you do more complex
PHP programming.
To install Eclipse PDT, go to http://www.eclipse.org/pdt/downloads/ to download the program.


Find the All-in-One package for your operating system and click it. You are given a choice of mirrors
from which you can download the package, as shown in Figure 1-11. Click the mirror displayed
(which in this fi gure is Georgia Tech) and save the fi le when requested.
Unzip the fi le in an appropriate folder. In Windows a good folder is c:\eclipse. It does not need to
be installed. On the Mac, put it in the Applications directory.

The program fi le is eclipse.exe in the eclipse folder. Make a shortcut on your desktop or add it
to your dock (on the Mac) so you can fi nd it easily.




CONFIGURING YOUR WORKSPACE
Now that you’ve installed the programs, you need to do some confi guring.

Preparing a Place to Put Your Files

The fi rst thing you need to do is decide where you are going to put your fi les. By default the Apache
web server looks for web fi les in the htdocs folder. On a Windows PC, this is directly off where you
installed XAMPP. If you installed XAMPP in c:/xampp, then your htdocs fi le is in the c:/xampp/
htdocs folder. On a Mac the path is /Applications/XAMPP/xamppfiles/htdocs.
If you are going to be doing a lot of development work, you should change this default and set up
virtual hosts so that you can put your fi les in more convenient places. However, setting up virtual
hosts is beyond the scope of this book, so use the default htdocs folder.
If you are on a Windows PC, skip forward to the next section, “Using Eclipse for the First Time.”
On the Mac OS X you need to change the permissions to the htdocs folder in order to add folders
and fi les to it. Open Finder, browse to /Applications/XAMPP/xamppfiles,


















Click the arrow next to Sharing & Permissions to expand the section as below

You need to unlock the padlock before you are allowed to make changes to the permissions. Click
the padlock in the lower-right corner. Enter your administrator password for the Mac when asked.
Now you can click the Privilege drop-down for the admin. Change from Read Only to Read &
Write.


Click the padlock again to relock the permissions.

Using Eclipse for the First Time



The fi rst time you go into Eclipse, you have to identify an Eclipse workspace.  This workspace is the place that you put your fi les. You use the htdocs folder.



Use the Browse button to locate and accept the htdocs folder. On the PC, if you installed
XAMPP in c:/xampp, your htdocs fi le is in the c:/xampp/htdocs folder. On a Mac, the path is
/Applications/XAMPP/xamppfiles/htdocs.


Eclipse displays a splash screen along with a request for permission for Eclipse to collect and send usage information,


Uncheck the box if you do not want to have this information collected and sent. Click OK and
then close the tab for the splash screen.

Across the top of the window, Eclipse lists the path to the workspace you are in. If you use virtual
hosts you can create multiple workspaces, although you can have only one open at a time. To switch
between workspaces, or to add a new workspace, use File Í Switch Workspaces. You use only one
workspace.



Within the workspace, you have projects. All your folders and fi les are created inside these projects.
To create a project for this book, click File Í New Í PHP Project. You see a screen similar
to



Type in a project name of php24. You can use what you want here, but this is part of the address
you use to call your programs, so short and uncomplicated is best. Leave all the rest as the defaults
and click Finish. You should see a screen similar to


Notice that you now have the project php24 listed in the left window. This is the PHP Explorer. It
works like the Windows Explorer, showing a hierarchical view of the folders and fi les within the different
projects. Just as in Windows Explorer, you use this to open and select fi les and perform other
actions on them.
Here’s what some of these options do:
‰ New: Use this to create new folders and fi les.
‰ Copy/Paste/Delete: These work as you would expect.
‰ Refactor: This is where Rename and Move are hidden.
‰ Refresh: Use this if you’ve added, renamed, or moved fi les outside of Eclipse.
‰ Debug As: You learn more about this in Lesson 5.
‰ Validate: This is for validating fi les without needing to open them.
‰ Compare With: This compares fi les either with another fi le or with an earlier version of the
same fi le. Files are automatically posted to Local History so you can roll back to a prior version.
See Options (in Windows) or Preferences (Mac) if you want to change how many copies
and how long they are kept.
‰ Properties: This is for quite a bit of Meta information.

In the center of the screen is a blank window. This is where you edit your fi les. Over to the right is
another window with tabs in it. The Outline tab shows you the outline of whatever fi le you have
open and selected and can be used to navigate to various sections in the fi le. The bottom of the
screen has another window with tabs. The Problems tab shows validation errors and the Tasks tab
lists to-do’s you have put inside your fi les and enables you to navigate directly to them.
This full screen that you see is called by Eclipse a “perspective.” This particular perspective is the
PHP perspective. Later you use a Debug perspective. Perspectives, which can be customized in
Windows Í Customize Perspectives, enable you tailor your work area to best suit the project you
are working on.

PHP START



In this Try It, you create a .php fi le and run it to test your PHP setup. This program runs a very
handy function to see how you have your PHP confi gured. This is even handier for hackers so it
is good practice not to have a fi le running it on your system. For a local system it is not a problem
however, because you delete it when you are done.


Lesson Requirements



To run PHP fi les locally, you need to set up your computer so it can process PHP and run MySQL.
This lesson shows you how to do that using XAMPP.
You also need to be able to create the PHP fi les themselves. You can do this with any editor that
can produce plain-text fi les, including Notepad, TextWrangler, Dreamweaver in the code mode,
NetBeans, or Eclipse. You learned in this lesson how to install the Eclipse PDT.
You should have a folder called php24 in the htdocs folder where you put your code fi les. If you created
the Eclipse workspace, the folder was created for you automatically.

(You can download the code and resources for this Try It from the book’s web
page at www.wrox.com. You can fi nd them in the Lesson01 folder in the download.
You will fi nd code for both before and after completing the exercises.)



Hints
This is the code you need in the .php fi le:

<?php phpinfo();

Be sure that the Apache server is running when you run the program.






Step-by-Step

In this lesson I am giving detailed instructions using Eclipse PDT for those new
to Eclipse. You can use a different text editor if you chose not to install Eclipse
PDT.





1. Create a blank .php fi le called test.php. In Eclipse, create it with the following steps:
a. Right-click your project in the PHP Explorer.
b. Select New Í PHP File. Note that this is a PHP fi le, not a PHP project.
c. Leave Source Folder as /php24 (your project name).
d. Type test.php as the name of the fi le in the File Name fi eld.
e. Click Finish. You see a screen

f. The center window contains a fi le called test.php. This fi le is also showing on the left
in the PHP Explorer window. If you don’t see it below your project, click the triangle
next to your project to expand the list.


2. Your text editor may have already typed in <?php for you. If it did, do not retype it in step 3.
3. Type in <?php phpinfo();.
4. Your screen should look like


5. Save the fi le. In Eclipse you save by pressing Ctrl+S on the PC or Command+S on the Mac.
You can also save the fi le by selecting File Í Save.
6. To run the program, go to your browser and enter localhost/php24/test.php.
a. localhost: This identifi es the web server, which in our case points to the htdocs folder.
b. php24: This is the folder that was automatically created to hold your project if you use
Eclipse, or, if you are not using Eclipse, it is a folder you created to contain your code
fi les.
c. test.php: This is the PHP fi le to run.
7. Your screen should look similar to


(TROUBLESHOOTING
If you’re having trouble, verify the following things:
‰ There should be a space between <?php and phpinfo().
‰ There should be no space between phpinfo and the ().
‰ Don’t forget the fi nal semicolon.
‰ Don’t forget to use localhost:8080 if you changed your XAMPP port
to 8080.)



8. Go back to your text editor.
9. Close the fi le. In Eclipse, click the X on the tab with the test.php fi lename to close the fi le.
10. Delete the fi le. In Eclipse, delete your fi le by doing the following:
a. Expand your project by clicking the triangle next to the project name if it is not already
expanded.
b. Right-click test.php.
c. Click Delete.
d. Confirm that you want to delete the file.









PHP for dummies CHAPTER 2


Adding PHP to a Web Page


PHP is a programming scripting language that was fi rst developed to generate HTML statements.
Even programs written totally in PHP are ultimately displayed as ordinary HTML.
You can also write programs that are mostly HTML with just the occasional PHP statement.
In this lesson you start with an HTML page and learn how to add PHP statements to it.
You are also introduced to the Case Study website. By the end of this book, you will have
changed it from a static HTML/CSS site to a dynamic website. In this lesson you add the fi rst
bit of dynamic code.



WRITING YOUR FIRST PHP PAGE



You start with a simple HTML page that looks like >>>>>>>>>>>>>>>

The fi le is called lesson2a.html.
Here’s the HTML for that page:
<html>
<head>
<title>Lesson 2a</title>
</head>
<body>
<h1>Welcome</h1>
<p>Today is Sep 27, 2011</p>
</body>
</html>
Now you turn this into a PHP page. All you do is change the fi le extension from .html to
.php and it becomes a PHP file.

When you call that in your browser it still looks just like same

(You can display standard HTML in your browser by entering the fi le path. An
example of a fi le path is c:/xamppfiles/htdocs/lesson2a.html. With .php
fi les, you enter the address that starts with the web root. An example of an
address is http://localhost/lesson2a.php.)



The difference is that, because of the .php extension, the PHP processor reads through the fi le to see
if there is any PHP to process. Any HTML that it fi nds it prints to the screen. Because all it found
was HTML, the results were just the same as the .html fi le.
So the fi rst rule of writing PHP code is to use the fi le extension .php.


so you can add PHP code to dynamically display today’s date. Make
a copy of the previous fi le, call it lesson2b.php, change the title to Lesson 2b and replace Sep 27,
2011 with the following code:
<?php echo date(‘M j, Y’); ?>
The fi le now looks like the following:
<html>
<head>
<title>Lesson 2b</title>
</head>
<body>
<h1>Welcome</h1>
<p>Today is <?php echo date(‘M j, Y’); ?></p>
</body>
</html>
When you run this code in your browser it looks similar to
. Of course your screen displays the current date.
The PHP processor looks for blocks of code that start with <?php. It interprets everything after that
as PHP code until it gets to a ?>. The echo date(‘M j, Y’) tells the processor to find today’s date;


format it with a three-character month, the day without leading zeros followed by a comma, and a
four-digit year; and then output it. The program continues to output the HTML that it fi nds, but
also processes the new PHP code.




Learning PHP Syntax
You’ve seen how PHP can work on a web page. Now it’s time to learn some basics of coding in
PHP before you get into the detail of the language.
In this lesson you fi nd out about formatting styles for PHP. You learn the general rules of PHP
syntax and how to create comments. You learn the specific c syntax of different PHP elements
as you go over them in subsequent chapters.
Finally, you learn some best practices to make life easier and your code better.


PICKING A FORMATTING STYLE

When you read a book or type a letter you are used to certain conventions. For instance, each
paragraph might have the fi rst line indented and a space before the next paragraph. Each chapter
might start with the fi rst letter enlarged.
Styling makes the text easier to understand because it organizes the information and tells you
what to expect. If there are no paragraphs, if all the sentences continue one after the other
without a break, you can read it but it is more diffi cult.
Programming uses formatting styles in the same way. The program runs fi ne without using
any formatting but it is more diffi cult for a human being to read. It is harder to see what is
happening and harder to fi nd errors.
A computer has no trouble reading this code:

<?php $messages=’’;$task=filter_input(INPUT_POST,’task’,FILTER_SANITIZE_
STRING);if ($task==’product.maint’):$results=maintProduct();$a==true;$mess
ages .=$results;endif;if (‘contact.maint’):$results=maintContact();$messa
ges .=$results;endif;if (‘category.maint’):$results=maintCategory();$messages
.=$results;endif;?>


However, even if you don’t know PHP, the following is much easier to understand:
<?php
$messages = ‘’;
$task = filter_input(INPUT_POST,’task’, FILTER_SANITIZE_STRING);
if ($task == ‘product.maint’) :
$results = maintProduct();
$a == true;
$messages .= $results;
endif;
if (‘contact.maint’) :
$results = maintContact();
$messages .= $results;
endif;
if (‘category.maint’) :
$results = maintCategory();
$messages .= $results;
endif;
?>
Formatting styles address the following issues:
‰ Indention: What should be indented? How big is the indentation? Do you use spaces or a
tab?
‰ Line length: Do you restrict how long a single line can be before you use more than one line?
How many characters is it?
‰ Whitespace: What additional whitespace (that is, spaces, new or blank rows) do you add for
readability?
‰ Use of {} (curly braces): If these are optional in the syntax, do you use them anyway or leave
them off?


Just as one book might have a different style than another, there are different PHP formatting styles.
It’s more important that you are consistent in your coding style than the particular style that you use.
Two popular styles are the Zend Framework (http://framework.zend.com/manual/en/codingstandard.
html) and the Pear Coding Standards (http://pear.php.net/manual/en/standards.php).


As you saw in the preceding lesson, the fi rst step to using PHP is to put your PHP code in a fi le with
the extension of .php. This warns the server to be on the lookout for a PHP block.
A block of PHP code starts with <?php and ends with ?>. So an example code block looks like this:
<?php
some php code here
?>
You can have one PHP block that encompasses an entire fi le or a number of PHP blocks interspersed
with HTML. If your fi le contains only PHP, or if it ends with a PHP block, leave off the fi nal ?>.

(The fi nal ?> is omitted because if there is any information, including blanks or
an extra line, after that fi nal ?>, it is interpreted as HTML and the system sends
that data to the browser. This results in extraneous whitespace and possible
header errors.)


(Some servers permit you to use the short tag version of <? to start a PHP block.
Don’t do this. Your code will not be accepted on all servers and is open to
misinterpretation.)


Each statement ends with a semicolon:
<?php
$first_name = ‘Andrea’;
?>
The end of a statement is often at the end of a line, but not always. This is
particularly noticeable when mixing PHP with HTML.<p>Hello, <?php echo
$first_name; ?></p>
The offi cial manual for PHP located on the php.net website is a great resource, although it can be confusing.
As an example, look up information on the function echo that you used in the previous lesson.
Go to www.php.net/manual/en/index.php.
 





You could use the table of contents to locate what you are looking for, but there’s a quicker way. In
the upper-right corner, type echo in the Search For box and press Enter.





You may be thinking it’s a good thing that you know what echo does because the explanation here
doesn’t help much. The following explanation should help you make more sense of it.

The fi rst section contains a description that starts with the syntax of the element.




The element is in bold text.
The keywords void and string tell you what the type is.
This is
just informational and you don’t type those words.
The parameters are shown in italic. Parameters are the changeable data that the function uses. Detail
about the parameters is contained in the second section.





The square brackets around the second parameter indicate that the parameter is optional. The ellipsis
(...) means that you can have more than one additional parameter.
The third section gives the return values. You learn more about return values in Lesson 10.
The most helpful section is often the next one: Examples. Here you can see how the function is actually
used.





Programmers are allowed to add notes directly to the bottom of the page. These often consist of tips and techniques in using the function.



ENTERING COMMENTS

Comments are an important part of PHP coding. Although you might remember tomorrow what
you were trying to do with a certain bit of code, you probably won’t remember in six months.
Document what you are trying to do as you do it.
Comments are not sent on to the browser so they don’t slow down your system. If you look at the
source code of a web page, the only comments you see are HTML comments, not PHP comments.
There are two main types of PHP comments. The fi rst type is for commenting a single line or partial
line. The comment starts with a // and ends at the end of the line:




<?php
// This is a single line comment
$temperature = 65;
$celsius = ($temperature - 32)* (5/9); // this is also a valid comment
echo ‘<p>The answer is ‘ . $celsius . ‘</p>’;
// You can, of course, have multiple lines
// of single line comments.
?>
The second type of comment is a block comment. The block comment starts with a /* and ends
with a */:
<?php
/* This is an example of using a multiple line comment. With
this type of comment you don’t need to keep repeating
the comment code. */
$temperature = 65;
$celsius = ($temperature - 32)* (5/9); /* this is also a valid comment */
echo ‘<p>The answer is ‘ . $celsius . ‘</p>’;
/* You can also use different techniques
* to make your comments stand out
* because everything is ignored until the */
?>






Note that, unlike the single-line comments, you need to indicate when the block comment ends.
There is a special type of multiple-line comment called a PHPDoc block comment. Automated tools,
including Eclipse PDT, pick up comments that use this specifi c style.
The PHPDoc comment starts with /**, has a * at the beginning of each line, and ends with */. This
is an example that documents the fi le itself:



/**
* Short description for file
*
* Long description for file (if any)...
*
* @version 1.2 2011-02-03
* @package Your Project Name
* @copyright Copyright (c) 2011 Your company name
* @license GNU General Public License
* @since Since Release 1.0
*/
There are specifi c setups for PHPDoc comments depending on what you are documenting.
You learn the common blocks as you learn about the different elements in later lessons. You
can fi nd details about the PHPDoc comment at the phpDocumentor site at http://manual
.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor
.howto.pkg.html.








Popular Posts

Recent posts