PDA

View Full Version : PHP Tutorial


Alakazam
08-06-2007, 08:13 PM
PHP or PHP Hypertext Preprocessor is a web programming language like PERL, HTML, Javascript, ASP. Unlike Javascript, what makes PHP special is that it is a server-side scripting language; javascript executes in the viewer's browser, whie PHP executes on the web server where your website is hsoted. PHP seems like a jumble of languages sometimes resembling something like PERL (especially when using it for forums like Vbulletin), but can also be put in the HTML like Javascript or Side Server Include (SSI).

First you got to know whether PHP is even on your server. If you are using paid hosting PHP comes standard with now a day. Login to your site's control panel www.yoursite.com/cpanel (http://www.yoursite.com/cpanel) and look for PHP to see what version is running. If you're with a free host like Angelfire, they don't have it. If your hosts support PHP, then we need to find the php path to your public_html directory. Create a file named phpinfo.php and then insert this in it:

<?php
phpinfo();
?>

Lets explain the code above for a minute so you understand just what the heck you're doing. First of all, like HTML all PHP has to be inside brackets. Whenever you're starting a PHP code, always start it with <?php on the first line. You have the choice of just using <? without "php", but some servers don't support that, so it's better to just use <?php.

The second line uses what is known as a built-in function. PHP is powerful because it has hundreds of built-in functions to use. As you might notice, phpinfo has "()" after it; the "()" are used to specify if you only want to know certain information displayed such as INFO_GENERAL or INFO_CREDITS. For GENERAL_INFO you would put phpinfo(GENERAL_INFO); to make it work. The last character of the line ends in a semicolon or ";", which is used to end all lines in PHP; it lets PHP know when to stop executing a script for a line.

Just like the beginning, the end of PHP requires ?> to tell it that the script is finished. Never forget to close the PHP tag or there will be a parse error and your script won't be executed properly.

Now that I've explain everything, save the file, upload it to your public_html directory on your web host and go to www.yoursite.com/phpinfo.php (http://www.yoursite.com/phpinfo.php) with your web browser. After you load the page, a bunch of information in tables will appear. Scroll down to see if you have one for MySQL; if you do, then you have MySQL support also. MySQL is a database language used in conjuction with PHP; I explain how it works later on.

Scroll down to the last table (PHP Variables) and go to HTTP_SERVER_VARS["PATH_TRANSLATED"] which should show you the path to your phpinfo file. Now take out the phpinfo.php part and you got your PHP path to your public_html directory! This is important for many scripts because most require you to enter the path to a certain directory. Now delete phpinfo.php for security reasons after you're finished or rename it to something less obvious if you want to refer back to it in the future.

Applying PHP to Layouts

Now that you understand how PHP works I'm going to show you just how PHP can help you with your website. So you have a website and you want to make a layout that makes it easy for your visitors to navigate through your content. Well you could create a layout for each page, but what if you want to add something to the menu? Then you have to go through every single page and edit the menu, which will take you a lot of time. Well with PHP, you don't have to do that; there are two methods for using PHP to include your layout.

Method 1: index.php with variables

Using method 1, your layout is placed in index.php and all your pages of content are created without any coding at all for the menu because the menu is put around the page.

In terms of creating layouts, PHP is like a more powerful version of SSI. The advantage of using this method is that you don't have to put coding on every page to include both the left and right menus. The huge drawback is that search engines like Google tend not to spider sites that use this type of PHP on their website; Google might just spider index.php and skip all the other pages. That is why I do not recommend you use this method for your whole layout; you can use it for only a few pages though if you're in a hurry. The extension of your content files don't really matter, but I would suggest that you use .php.

A major difference between PHP and SSI is the URL. With SSI the files are named page.shtml. With PHP a typical URL looks like this: index.php?id=page. "index.php" is your layout file and "page" being "page.php". You don't have to use "id"; it's up to you.
If you've never used SSI before then that's ok. Just make sure you understand everything I've said so far being you proceed.

Make sure you have your layout already made and ready before you do anything. Now put it all into one file and make sure you know where the content is going to go, which should be somewhere in the middle between the left and right menus. Now save the file as index.php before you do anything else. Now insert this tag where the content is going to go:

<?php include ("$id.php"); ?>
<?php if($id=="") { $id="index2"; } ?>
<?php if (!file_exists("$id.php")) { $id = "404"; }?>

The "id" is part of the url and is where you can change it to whatever you want, but remember that your url will change for everypage. The ".php" bit is the extention of your content files. If all your content files are ".html" or ".shtml", replace ".php" with ".html" or ".shtml". The last two lines make sure that when a visitor goes to index.php, a page will show up and it just won't be your layout with a PHP error. Now create a file called index2.php, which will be your main page. Don't worry if you already have a file for your splash page called index.html. Your splash page (index.html) will get priority over index.php, so if someone goes to http://yourdomain.com, they will be taken to index.html, not index.php. Make sure to create 404.php, which will be displayed when a user clicks on a broken link on your website instead of a PHP error.

Now it's time to test out your layout to see if it works. If something goes wrong, go back and make sure you did everything correctly. Start by typing in the url to your site and then at the end of it add index.php?id= and then add the name of one of your pages of content to the end of it. For example if my content page was named pokemon.php then the URL would be http://www.pokezam.com/index.php?id=pokemon. If the page displays fine then you're well on your way to changing your layout completely over to PHP.

Method 2: including left.php and right.php

This method is very similar to SSI. The advantage to this method is that your site will be spidered by Google for sure, but the disadvantage is that it takes a bit more work of having to go through all your pages and add coding to them.

The first step is to save your left menu as left.php and save your right menu as right.php. Next, for every page of content, add the following pages where the left and right menus are suposed to be displayed:

<? include("/path/to/public_html/left.php"); ?>
<? include("/path/to/public_html/right.php"); ?>

There used to be a command where you could replace "include" with "virtual" and it would call whatever file is in public_html, but the command doesn't work anymore. If you don't know the path to your menus, check in your control panel http://www.yourdomain.com/cpanel to find out or ask your webhost. This is very important or else you will get an error; you can just type left.php without the path only if all of your content files are in the same directory (such as public_html) as the menu files, but if they aren't you'll get an error.

If you want to link to a page or file that is on another host then use the tag below.
<? include("http://www.pokezam.com/news/news.txt"); ?>

If you want to include multiple variables in your PHP file then you have to use the format below:
/tcg/viewcard.php?set=base&pokemon=Alakazam&number=1

To print the variable results in viewcard.php you have to use the format below:
<?echo $variable;?>
For every variable you use, replace $variable with the variable you want to appear on the page. For example $set would make "base" appear on the page.

The only drawback to using variables in the URL of your page is that search engines, such as Google might not spider it. The reason being that Google doesn't want to wait their time and spacee by going through thousands of pages in message boards. So if you use variables in your URL, be prepared to lose a lot of visitors if Google decides not to spider your page.

In the latest version of PHP, variables have been turned off, so if you try using this code above and it doesn't work then it means global variables are turned off. I fixed that, open notepad and paste "php_flag register_globals 1" (without the quotes) in a blank file and save it as .htaccess and upload it to your public_html directory.

If that doesn't work its probably due to the flag command being turned off. To get around that, download php.ini from your publc_html folder and look for register_globals and when you find it change "Off" to "On" and reupload the file to the directory where the file is located. If that doesn't work, ask your host to turn on global variables for you.

Alakazam
08-06-2007, 08:14 PM
Applying PHP to Content

If you have sections on your site, you have the option of putting similar pages into one PHP file to make it simpler to edit the content. Lets say you have 10 pages of content for 1 section, which we will name "Guides". Instead of making ten seperate pages for each guide, we can have only 1 page with the information with the 10 guides in it.
We start with the file guide.php, which should be similar from the one in the applying PHP to Layouts method 1. Now to input the info in this file we simply put to following:

<?

if(guidephp=="pagename/url")
{
print ("content here");
}

?>
Or for multiple pages of info:
<?

if(guidephp=="pagename/url")
{
print ("content here");
}

if(guidephp=="pagename/url")
{
print ("content here");
}

?>

This is a really simple code. Basically you put the name of page in the pagename/url part. An example would be PHPGuide and then that becomes the url to the PHPGuide info:
http://www.pokezam.com/guides.php?action=PHPGuide

As you can see, I put action=content'sname after the main file, which stores all of the information on guide.php. Now to add the content too, just put in it the content here part. However, there are some rules to adding content in that part. In adding content or info for a certain you cannot use double quotation marks (" ") in between the already two quotation marks... And if you think about this according to English grammar it makes sense. So what do I do when i have <img src="image.gif"> you might ask? Well there are three options you can do <img src=image.gif> (without any quotations) or <img src='image.gif'> with only one quotation or you can do <img src=\"image.gif\"> (with a backslash before the double quotations). It's your choice, any one of these will work, but it must be done to everything that has a double quotation before it is put in the content part, otherwise you'll end up with tons of errors and the page won't work properly.

Now some people use page instead of action like ?page=PHPGuide, but if you do that the url would be http://www.pokezam.com/guide.php?page=PHPGuide and code would be:

<?

if(=="pagename/url")
{
print ("content here");
}

?>

Remember, the choice is yours! If you are going to include left and right layouts, they can't have double quotation marks either or else the PHP in the menus won't work.

Handling forms with PHP

One of the most powerful features of PHP is its ability handle web forms. Why is it so powerful? Well it's because anything input by the user into the form is available for you to use. You can have the form print their name on the next page or you can have the form information emailed to you or the user; it's up to you. Below is an example of a form using PHP, which you can name affiliation.php:

<form action="mailinfo.php" method="post">
<input type="hidden" name="subject" value="Affiliation">
<b>Email Address</b><br />
<input type="text" name="email" size="20"><br />
<b>Site's Name</b><br />
<input type="text" name="sitename" size="20"><br />
<b>Site's URL</b><br />
<input type="text" name="siteurl" size="20" value="http://"><br />
<b>Button URL</b><br />
<input type="text" name="buttonurl" size="20" value="http://"> <br /><br />
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Reset"></form>

Now the above form may just look like a regular form, but the difference is what happens to the data. By putting action="mailinfo.php" in the form tag, it tells the form to transfer the data the user enters to mailinfo.php, which is where we start to utilize PHP to its full potential.
Below is mailinfo,php, which is where the data from the form that we submitted goes:

<?php
if ($email && strstr($email, "@") && $sitename && $siteurl && $siteurl != "" && $siteurl != "http://" && $buttonurl && $buttonurl != "" && $buttonurl != "http://") {
mail("webmaster@pokezam.com",
"Affiliation",
"E-mail address: $email\nWebsite: $sitename\nURL: $siteurl\nButton: $buttonurl",
"From: $email <$email>\r\n");
mail("$email",
"Affiliation at PokeZam.com",
"Thanks for applying to affiliate with PokeZam.com (http://www.pokezam.com).\nYou (http://www.pokezam.com%29.%5CnYou) will hear back soon on if you were accepted or not.\n\n-Alakazam",
"From: Alakazam <webmaster@pokezam.com>\r\n");
header("Location: http://www.pokezam.com/thankyou.php");
} else {
header("Location: http://www.pokezam.com/joinerror.php?e=$email&n=$sitename&u=$siteurl&b=$buttonurl");
}
?>

I am now going to talk about the code above by lines. Line two says that if the email is filled in and contains a "@" and if all the other fields are filled and not left blank, to do whatever is between these brackets "{}".

Lines three through ten send an email with the information entered in the form to yourself and an automated response to the user who applied. Anything with a dollar sign ($) in front of it, such as $email is a variable. In affiliation.php, in the input tags, whatever you put in the name tags can be referred to as a variable by putting a dollar sign in front of it.

Line eleven sends the user to a thank you page after they have applied.

Line twelve and thirteen say that if the statement doesn't apply to the if statement on line two, then to send the user to an error page. Just be sure to take a close look at the URL. When it says joinerror.php?e=$email&n=$sitename, joinerror.php is a page that you will create, while we declare a new variable called e, which stands for email and we use the & symbol to create more vairables.

Now why do we need an error page? What if some fields are left blank on the form, or it's filled out wrong, such as with a fake email without a @ symbol in it? Well, instead of receiving a blank form, the form will be rejected using the following code in joinerror.php:

<?php
if ($e == "" || !strstr($e, "@")) { echo "<li>Your email address appears to be invalid<br />"; }
if ($n == "") { echo "<li>You forgot to fill out your site's name<br />"; }
if ($u == "" || $u == "http://") { echo "<li>You forgot to fill out your site's URL<br />"; }
if ($b == "" || $b == "http://") { echo "<li>You forgot to fill out your button URL<br />"; } ?>
<form action="mailinfo.php" method="post">
<input type="hidden" name="subject" value="Affiliation">
<b>Email Address</b><br />
<input type="text" name="email" size="20"><br />
<b>Site's Name</b><br />
<input type="text" name="sitename" size="20"><br />
<b>Site's URL</b><br />
<input type="text" name="siteurl" size="20" value="http://"><br />
<b>Button URL</b><br />
<input type="text" name="buttonurl" size="20" value="http://"> <br /><br />
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Reset"></form>

Now as you can see, lines two through five are if statements for if a field is left blank. After that, the same HTML form from affiliation.php is pasted for the user to fill out again. If information is missing again, the form will keep being rejected until everything is filled out correctly.

MySQL Database

What would PHP be without its partner in crime MySQL? MySQL is a database language, like Excel, where you have tables, with rows and columns to store data. PHP and MySQL work together in the following way: as with the example above, data is gathered through a web form using PHP and instead of just sending an email and losing the data, the data is stored in a MySQL database.

MySQL is a very complicated language, so I'm only going to go briefly into it. You can create a MySQL database by going to your control panel located at http://www.yoursite.com/cpanel. Once you login, go to MySQL Database and create a new database. Once the database has been created, create a new user and add them to the database you just created with all permissions.

Now that your MySQL database is created, be sure to remember your database name, username and password. The database name and username have your cpanel username followed by _ and then whatever you called them; for example: pokezam_forums. The only other thing you need to know about MySQL, is that at the bottom of the MySQL page, then is a link to PHPMyAdmin, where you can select your MySQL database and click on the SQL tab and perform a MySQL dump, where you paste MySQL for a script you may be installing. You will never need to do that if you aren't a programmer.

I'm not going to go more in-depth into MySQL because I've told you basically everything you need to know to be able to fix any errors you may have. With MySQL you can create a member registration script where users enter their username, password and email; the information is stored using MySQL and then they can login to your site and have access to exclusive content. That is just an example of how you can use MySQL, but it's up to you.

Conclusion

This is just an introductory tutorial to help you learn the basics. PHP is a very powerful language and is changing everyday. With PHP you can create things like message boards, web polls and email forms. The best part about knowing PHP is that you'll be able to correct errors you get in your scripts; just put the error in Google and you'll more than likely find the solution because most mistakes are from forgetting to put a semicolon or quotation mark. Check out the Resources page in the Webmaster section for some links to sites with PHP scripts. Thanks for reading this guide!