PHP

Learn

Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.

Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.

Click the categories below to get started!

Contribute

Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial

Recommend to Others

If you like a tutorial, please use the "digg" button below it.

What is PHP?

Adding PHP code to an HTML document allows you to create dynamic, interactive web pages. You can add PHP code to an existing web page or to a new HTMl document you create.

PHP code is inserted into HTML code using the <?php opening delimeter and the ?> closing delimeter. The delimeters tell the server where the PHP code begins and ends.

You can add multiple sections of PHP code to an HTML document. You must use an opening and closing delimeter for each section of code. If the PHP code will generate ouput for display in a user's web browser, you can use HTML tags to format the output.

PHP code used to generate ouput must be inserted between the <body> and </body> tags. When a web server recieves a request for a web page containing PHP, the web server processes all the code found between the PHP delimeters.

The information generated by the PHP code is inserted into the web page before the page is sent to a user's web browser. Users who visit the page will not be able to see the PHP code, even if they display the source code for the page. When savijng a PHP page you have crated, you must add the .php extension to the filename of the page.

Some text editors do not recognize the .php extension, so you may have to enclosethe filename in quotation marksm such as "index.php". The PHP page must be saved in the appropriate location on your web server before the page can be displayed.

The Basics

Firstly, before we begin a brief description of PHP, You may have heard of it or you may not have.

PHP is a powerful scripting language, unlike Javascript PHP is processed server side, so what you see is what left the computer hosting it, Because of this some hosts may not have the ablitly to host PHP files. For this Tutorial, some PHP host or access is reccomended,

Ripway should be fine. Now just with any language, we need Tags, to put our PHP content between, with PHP the opening tag is <? or <?PHP while the closing tag is ?>, Anything between that tag must have correct PHP syntax, but lets not worry about that for now.

If we want to display something, other than Hello World, we can use echo. Echo writes what you tell it to, If I wanted my page to say "Howdy Doody" I would use, echo 'Howdy Doody';

That line is correct syntax, so will print Howdy Doody. If I put echo Howdy Doody I would get errors, you must put ' around your work, so PHP nows you are wanting it to echo that. ; is important to, PHP will know no to goto the next line, and forget the previous.

If you want to test a file, try


<?php echo 'Howdy Doody'?>

Save that as test.php and upload it to your host.

Now you have learnt the basics of PHP, you can move on to other tutorials.

Variables

For this tutorial it is reccomended you have access to a PHP host or server, if you wish to try any of the examples.


Variables hold data, thats all. They are not an impressive function, or nor do they require excellent PHP skills they are there to hold data you may need again. For example,



 <? echo 'Hello Woody'
echo 
'Howdy Woody'
echo 
'Was up Woody?'
echo 
'l8r Woody'?>

We could create a variable, to replace Woody. Here is an example of a variable

$who = 'Woody';

The $who is the name of the Variable, by using $ PHP knows we are creating a Variable, the = sign is what the Variable contains, and between the ' are the Variable contents, Simple?

If we want to echo our welcomes to Woody we could use

echo $woody;

Here is a full example



 <? 
    $who 
'Woody'
    echo 
'Hello '.$who.''
    echo 
'Howdy '.$who.''
    echo 
'Was up '.$who.''
    echo 
'l8r '.$who.''
?>

Instead of echoing Woody out, we are now echoing $who out, so if you want Woody could become Woodette or Woot just by changing the Variable content, instead of replacing every Woody we wrote.

Now you should have an understanding of how to create a Variable, and how to echo them.

Arrays

For this tutorial it is recommended you have access to a PHP host.


Arrays can be used to store multiple pieces of information in just 1 variable. Here is an example array


$colors = array('blue','red','green','black');

That is an array, now to call the information, we could


echo $colors[0];
That would output Blue (Remember PHP starts counting at 0, not 1!)

If you wanted to display a random color from the array you could use,


$randy = rand(0,3); echo $colors[$randy];

You could even use a Loop, to display all the colors, but Loops will be left for another tutorial.

Now you should have a basic idea of how to use an Array, and how to display it.

Basic String Manipulation

Hey there, this is my first tutorial so don't be frustrated if you see an error or something, just leave a comment and I'll edit it :P

This tutorial is about how to manipulate strings in PHP, how to filter out words, how to check if a string it too long, and stuff like that.

Checking the length of a string

strlen() is the function we'll be focusing on in the section.

First, lets take a look at the following piece of code:



<?php $string 'I like butter'; if(strlen($string)>$max){ print 'String too long!'; } ?>

Understand that? If you don't, what the strlen() function is doing is returning the length of the string that you input. So, strlen('Cheese'); would return 6 and strlen('Cake'); would return 4. Geddit?

Triming

But what if the input is just spaces? Then we use trim(). trim(); removed all the spaces from the beginning and end of a string. Let's see an example:



<?php $spacedString ' This has spaces! Oh dear.'; print trim($spacedString); ?>

This is quite simple, all this does is removed the 6 spaces infront of the string. It would also remove the spaces at the end if there were any. Simple eh? This is very useful for checking whether a $_POST input isn't just spaces. You can do that like this:


<?php 
    $postedData 
$_POST['data']; // Lets say this is ' '. 
    //There is about 20 spaces in there. 
    
$trimmed trim($postedData); 
    if(
strlen($trimmed)<1){ 
        print 
"Email Invalid\"; 
    } 
?>

Cool eh?

Replacing words

This is good for making a censored words list with. How do you do this? With str_replace()! Lets take this piece of code:



<?php 
    $words
[] = 'Word1'
    
$words[] = 'Word2'// Array of words 
    
function censorString(){ global $words// Get the array 
    
$i 0
        while(
$i<count($words)){ 
            
$string str_replace($words[$i], ' ** Bleep ** '$string); $i++;} 
        return 
$string; } 
?>

Understand any of that? If you didn't, don't worry. I'll break it down for you:

<?php

Starting the php script, obviously.

$words[] = 'Word1'; // Array of words $words[] = 'Word2';

This is an array of the \"bad\" words.

function censorString(){ global $words; // Get the array $i = 0;

This is just starting a function, getting the \"bad\" words array and then setting $i to 0. We'll need the $i to loop through the array later.

while($i<count($words)){

count() returns the number of elements in an array, so in this case it returns 2. You should know about while loops, they're very simple. But this tutorial isn't about while loops, so I'll move on :P

$string = str_replace($words[$i], 'Bleep', $string);

This is when the real stuff is done. The while loop is looping through the array, adding 1 to $i every time, so that we can use it to get each element of the array in turn. str_replace()'s is used like this: str_replace(REPLACE THIS, WITH THIS, IN THIS); So now that the code has looped through all the array, it has replaced all the bad words in a string with 'Bleep'.

$i++; } return $string; }

The $i++; adds 1 to $i to stop the loop going on forever! We then close the while loop, return the string out the function and then end the function. This function would be used like this: censorString(\"This string contains word1\"); that would return \"This string contains **Bleep** \". However, if you wanted to make this more effective, you could use str_ireplace() instead of str_replace() to make the search case insensative. (Search without caring whether its a capital or not.)

Sanitizing Input

This section teaches you ways to make HTML safe to put into databases or something :)

Strip_tags()

This is not a very good method, but its effective non-the-less. It removes all html or php tags, like <b> and <a>. Used like below: strip_tags(\"This string will be <b>stripped</b>\"); Returns \"This string will be stripped\" (Note how there is no bold).

htmlentities()

htmlentites turns all html into their html entities, so &copy; becomes &co[ b][ /b]py; and so on. This is my favourite method, and I recommend it. Used like below: htmlentities(\"<b> Ho ho ho </b>\"); returns \"&[ b][ /b]lt;b&[ b][ /b]gt; Ho ho ho &l[ b][ /b]t;/b&[ b][ /b]gt;]

addslashes()

This is very good aswell, it adds a \"\" in front of all ', \" and existing 's in a string. Used like this:
addslashes(\"I'm very well. And you're name is?\"); this outputs: \"I'm very well. And you're name is?\"

Thanks for reading!

Thanks for reading my tutorial, I'll be making another one on this subject to tell you about more String manipulation functions ;)

Cookies

A cookie is a name given to a small file placed in the users temp files, this file can contain info, so that when they re-visit the site the next day, this info can be read. Well first you want to check if the user has cookies enabled in their browser. We can do that by using the sizeof() function.

if(sizeof($_COOKIE) > 0){ // Cookies Enabled } else { // Cookies Disabled }

Next you will need to know how to set cookies, we can do that by using the setcookie function.

setcookie("Cookie Name", "Cookie Value",time()+1209600);

The first part of the code is obviously what you want the cookie to be named. The second part of the code is what you want the value of the cookie to save. The third part of the code is when you want the cookie to expire, I have it set at two weeks.

if($_COOKIE['CookieName']){ echo "Cookie Here"; }

This would echo "Cookie here" if the cookies value was true.

Email validation with preg_match

We are going to use preg_match to validate an email. The pattern is:



<?php 
    $pattern 
"#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i""; 
?> 

Here is how you validate it:


<?php 
    $pattern 
"#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i"
    
$email "someone@someplace.com"
        if(
preg_match($pattern$email)){ 
            echo 
"Email is valid."
        }else{ echo 
"Email is invalid."; } 
?>

PHP will print out "Email is valid" if the email is valid.

Here is a useful function to validate emails:



<?php 
    
function is_valid_email($email){ 
        if(
preg_match("#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i",$email)){ 
            return 
true
        }else{ 
            return 
false; }
    } 
?> 

Here is how you can use the function:


<?php 
    
if(is_valid_email("someone@someplace.com")){ 
        echo 
"email is valid!"
        }else{ 
            echo 
"not valid"; } 
?>

Encrypting Strings with Crypt()

If you have a multi-user website then it is probably good that you have good encryption methods. This tutorial will explain how to encrypt these passwords and then match them with un-encrypted strings when the user comes back. First, you need to encrypt it. This is fairly simple.


<? $password crypt("abc123"); ?>


That will make abc123 a whole bunch of different characters.

Now, lets say you have a user login. So does the user have to put in all those characters and everything? No. They'll just have to put in abc123. It's up to you to match it with the encrypted password and here's how to do it:



<? 
    $cryptpass 
crypt("abc123"); // this is just an example, 
                //normally you would grab this out of the database 
    
$password $_POST['password']; // this is assuming you're having abc123 sent via a form 
        
if(crypt($password$cryptpass) == $cryptpass){ echo 'success'; } 
            else { 
                echo 
'password incorrect.'
        } 
?>

That is the basics of crypt. You will have to set it up your own way to deal with the way your system is set up, but the function doesn't change none the less.

Explode() & Implode()

The 2 functions "Explode" and "Implode"; are both used in the splitting of a string into several pieces or the joining of an array together. For those of you familiar with JS, \"Explode\" is very similar to \"innerHTML.Split\". The syntax of \"Explode\" is:

Explode ( Split By , String ) ;


<?php 
    $strString 
"Text;Some Text;More Text" 
    
$strArray Explode ";\" , $strString ) ; 
?> 
In this example \"Explode\" takes the string and splits it into several pieces by \";\" creating an array with 3 items. If these were echoed...

<?php 
    
Echo ( $strArray ] ) ; // Gives \"Text\" 
    
Echo ( $strArray ] ) ; // Gives \"Some Text\" 
    
Echo ( $strArray ] ) ; // Gives \"More Text\" 
?> 
Now \"Implode\" can be used to reverse this, the syntax of which is:

Implode ( Join With , Array ) ;


<?php 
    $strArray 
= Array ( "Text\" , \"Some Text\" , \"More Text\" ) ; 
    $strString = Implode ( \";\" , $strArray ) ; 
?>
In this example Implode takes the array and joines it together as a string with \";\" inbetween each piece of text. If this was echoed...

<?php Echo ( $strString ) ; // Gives \"Text;Some Text;More Text\" ?>

Final Notes: The function \"Join\" is exactly the same as \"Implode\" thus...



<?php 
    $strString 
Join ";\" , $strArray ) ; 
    $strString = Implode ( \";\" , $strArray ) ; 
?>

... Do exactly the same thing.

Formatting Numbers Using number_format()

Let's say that you have a counter script on a popular site that you coded yourself. What if you get well over 1,000 hits? Without proper formatting the number would be displayed as 1000 without any commas.

Using number_format you can change this.

Here is a basic number format:



<? $number 1000; echo number_format($number); ?>

Interact with the Filesystem - mkdir() and rmdir()

One of the things I've found great about PHP is that it has very well supported Filesystem interactivity. Meaning, I can alter files and directories of my server very easily and with a robust nature.

While it might not be as fit as Perl, it's still well suited for a Web Development language. So, the point to this tutorial is to introduce you to two functions which as used in making and deleting directories. These functions are mkdir() and rmdir().


bool mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )

First up is mkdir(). You may have guessed that this function is used to create a directory. It accepts two parameters, the first being the directory (path can be included if your script isn't in the area where the dir is being made) and the permission of the directory.

The second parameter may be omitted in scripts being run on Windows, but, you can still include it if you like (PHP will just ignore it). However, you'll always want to set a permission on a Linux server...always =P Example time!



 <?php 
     mkdir
('/path/to/my/dir/mydirhere'0755); 
?>

As you can see the first parameter is a path. It'll create a directory named 'mydirhere' in the "dir" file which is located in the "my" dir, etc. However! Take note that mkdir() will NOT create multiple directories at once. If the directory "dir" did not exist and I ran the above script I'd get an error due to that.

The second parameter may look oddly familiar, yet not so. The last three should most definitely. This is a regular CHMOD value, but PHP suggests you keep it in Octal form. Simply add a '0' before the number =P So, '777' would be '0777'. Simple enough really.


bool rmdir ( string dirname [, resource context] )

And now for rmdir(). This does exactly the opposite of mkdir(), it'll delete a specified directory. The rules are the same as mkdir() with the first parameter. Not the second though, rmdir() doesn't require a second parameter =P Just enter the directory name (full path if need be).



 <?php 
           mkdir
('/path/to/my/dir/mydirhere'0755); 
           
rmdir('/path/to/my/dir/mydirhere'); 
?>

So the example now creates 'mydirhere' found in '/path/to/my/dir'. Sets its permission to 755. Then deletes it. I'll note again though: rmdir() will not delete multiple directors at once. The above example won't delete the 'dir', 'my', 'to', and 'path' directories, as they're the path to the last one.

And there you have it. Two very simple functions, but very useful (especially in registration scripts) ones at that. Try tinkering around with it, shouldn't take any time to get used to, they're very straight-forward. But, as with anything, the knowledge won't stay if you don't apply it =P Have fun.

Introduction to cookie creation and use.

What is a cookie?

A cookie is a file that is stored on your computer that keeps track of nearly anything. It can be used to store usernames, passwords, location, and more.

What is a cookie used for?

A cookie is used to hold a common variable across every page that the cookie is checked on. This is useful for creating a login system and things of that nature. How do I create a cookie? To create a cookie, all you need is one line of code:

setcookie("ymatBBu", $username, time()+3600);

The first part, "ymatBBu" is the name of the cookie, the second part is the value of the cookie, and the third is the expiration date in seconds from the creation time. To delete a cookie, simply set the time to a negative number rather than a positive number.

I have a cookie...what now?

Once the cookie is created, you will need to put this at the top of all the pages you wish to use the cookie on:

ob_start();

It must go at the very top, before all other code. To grab the cookie value that you set for the cookie, you will need to do this:

$uza = ($_COOKIE['ymatBBu']);

The previous line of code set the variable $uza to the value of the cookie that we set earlier (in this case, the value was the value of $username) For a more secure login system, you will need to make 2 cookies, 1 to store the username and the other to store the password. Check both to see if they match with those of the database, and if they do, then you may set the variable to the cookie value.

Introduction to MySQL

So you're interested in learning how to incorporate MySQL into your Web Applications, eh? Well good, you should be. If you've been using PHP for a little while (I'm assuming you know the PHP Basics) then you've probably realized the language is quite useless without some form of a database to store data in. There are many different forms of databases which PHP supports, so your options aren't very limited. MSSQL, Firebird SQL, PostgreSQL, Oracle, they're all other options that are open to you as well.

Why MySQL though? It has various advantages over the others. For one, it's Open Source. Second, it has been ported to many different Operating Systems (means it can be run on almost anything). However, what probably attracts most people is this: It's fast and free. The lack of price on MySQL is what makes it so common, that's why Oracle is really only found on Corporation servers. This tutorial isn't aimed at those people though, this is aimed for the enthusiast =P

Enough jabber already, you should understand why you're choosing MySQL by now anyways. However, I want to mention that for you to use MySQL you must have it either installed on your server or you must have a host that supports it. PHP must also be enabled to support it. If you've got that, then great, lets start.

I plan to discuss the following PHP Functions in this tutorial, all are for interacting with MySQL:

mysql_connect()
mysql_select_db()
mysql_query()
mysql_num_rows()
mysql_fetch_array()


resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )

The mysql_connect() function is where it all begins. To use MySQL you need to form a connection between your script and the database. The function usually only needs three parameters (host, username, password). Here's an example:



<?php
    $dbConn 
mysql_connect ('localhost''root''mysqlPassword');
?>

As seen above, the three parameters are "localhost"(host), "root"(username), "mysqlPassword"(password). Of course these would change depending on your settings. Chances are though you'll always use "localhost" for the host parameter. The only time you should have to use another host address is if your Web Host has MySQL on a different server. You can always ask them for the details if you think they may have MySQL setup like that.


bool mysql_select_db ( string database_name [, resource link_identifier] )

So you've connected your script to MySQL...now what? Well, everything in MySQL is kept in Databases. You might have unlimited databases, 10, 50, 1, it doesn't matter. What does is that you have at least one database setup to store whatever information you wish to put in. Information is further broken into Tables within databases, but that'll be discussed more with the mysql_query() function.

mysql_select_db() only requires one parameter, but it's good practise to include the second. These two parameters are (database name, db_conn_variable). Using the above example to build on:



<?php
    $dbConn 
mysql_connect ('localhost''root''mysqlPassword');
    
$dbSelect mysql_select_db ('testDB'$dbConn);
?>

You'll notice I used the variable which the connection is assigned to. This just sets up an identifier, so if you wish to have multiple connections with multiple databases (wasteful, but possible), you can do it like so. The database in example is called "testDB". This'll have to be changed to whatever the database really is. You make that decision =P


resource mysql_query ( string query [, resource link_identifier] )

MySQL uses the SQL Language for input and manipulation. To pass SQL to the database you need to use the mysql_query() function. Chances are you'll only use one parameter with this, and that's the Query operation. I won't be going into detail about the SQL Language, but, you can reference http://www.w3schools.com/sql/default.asp if need be. Nearly anything you would pass directly to the MySQL Server can be passed through the mysql_query() function. Obviously a few things are unneeded, such as "USE ___database_name___;", as you've already done that with mysql_select_db().



<?php
    $dbConn 
mysql_connect ('localhost''root''mysqlPassword');
    
$dbSelect mysql_select_db ('testDB'$dbConn);
    
$dbQuery mysql_query ("SELECT * FROM testTable WHERE id > 40 AND tab_owner = 'theOwner' ORDER BY id DESC");
?>

That's a simple query to grab all rows where the column "id" is greater than 40 and the column "tab_owner" equals "theOwner". It then orders it by the "id" column, greatest to least.


int mysql_num_rows ( resource result )

One very common thing that people want to do (whether for debugging purposes or to actually display the data) is to find out how many rows come back from a query. This is an amazingly simple process, PHP has a built-in feature to do it for you. That being the mysql_num_rows() function. It takes one parameter only, and that being the variable that holds the query you wish to process. In our current example that variable would be "$dbQuery". If I had multiple queries going on then I'd use the variable of the query I want to number of rows returned about. Extremely simple.



<?php
$dbConn 
mysql_connect ('localhost''root''mysqlPassword');
$dbSelect mysql_select_db ('testDB'$dbConn);
$dbQuery mysql_query ("SELECT * FROM testTable WHERE id > 40 AND tab_owner = 'theOwner' ORDER BY id DESC");
$numRows mysql_num_rows ($dbQuery);
echo 
$numRows;
?>

So now we're assigning how many rows returned to a variable and outputting it.


array mysql_fetch_array ( resource result [, int result_type] )

I wasn't actually going to include this function in this tutorial, but I figured you'd want to know how to output the rows you query =P However, to compromise, I won't discuss the PHP aspects (as you'll see, the while() loop). I'm assuming you know how that works, so it'll go without saying.

mysql_fetch_array() is used to assign to an array the data of a selected row. mysql_fetch_array() has an advantage over mysql_fetch_row(), that being, it can store the data as an Associative Array. This means you can refer to the array items by the column name, not by a number. Lets get the example up, so I can better explain.



<?php
    $dbConn 
mysql_connect ('localhost''root''mysqlPassword');
    
$dbSelect mysql_select_db ('testDB'$dbConn);
    
$dbQuery mysql_query ("SELECT * FROM testTable WHERE id > 40 AND tab_owner = 'theOwner' ORDER BY id DESC");
    
$numRows mysql_num_rows ($dbQuery);
    echo 
$numRows;
    {
        echo 
$myRow [''id''];
        echo 
$myRow [''myOtherColumn''];
        echo 
$myRow [''tab_owner''];
    }
?>

To loop through all the rows we're using a while() loop. This obviously isn't the only way, but it's the most common (and the way I'll almost always use in tutorials). When you look at the "$myRow['___']" a couple things should look familiar. First being that we're using the variable that was assigned the value of the current row's array in the while() loop. Second being the names inside the "['___']" part of the variable. "id" and "tab_owner" have been mentioned before, as they're the names of columns inside our MySQL Table. I just threw in another column name to put more in there. Essentially the code is now doing this:

1. Connec to MySQL
2. Get our database
3. Query the database for the material we want
4. Assign to a variable the amount of rows returned
5. Display the number of rows
6. Begin a loop that'll go through all the rows returned from the query. Assign array to variable
7. Display data from array. Refer to columns through their names, not number
8. Close off the while() loop


So you've now seen a very simple and straight-forward example evolve to encompass various functions. You've already been equipped with the very basic information needed to go forward and create web applications backed by a MySQL Database. You'll want to further your knowledge, if you go into more complex situations. But, you'll still need the knowledge shown to you through this tutorial. Now, go and apply it =P The best way to learn is by using it in a real environment.

Learn how to make code do something based on a condition

It's no doubt the If, else, else if statements are the most widely used in php. They are relatively easy too.

If Statement

This checks if x is true do a, if x is false do b. Syntax for a if statement is as follows:

if (expression) { statement here }

In the () you put the expression like 1>2 and such. The statement is what it should execute based on the expression. Time for an example.

$a = "1"; if ($a == "1") { echo 'There is $a apple'; }

Now if the condition does not meet what is needed to execute the code in the curly brackets, the code is skipped and moves on in the file. Example...

a = "1"; if ($a == "2"){ echo 'we have $a apples'; }

The code is skipped in the curly brackets in the example above. If statements are a fundemental of PHP and is required for any advanced programming.

Else Statements

Think of this as the If statements older brother. This executes code if the condition in the if statement is not met. Please note that you musthave a if statement before an else. Example time...

a = "2"; if (a !="2"){ echo 'a does not equal 2'; } else { echo 'a does equal 2'; }

The code in the if statement curlys are skipped but the code in the else curlys are used. As you can see Else statements are realitvely simple.

Else If

Think of this guy as the parent of this happy family. Else Ifs are an extention of the else statement. It allows you to supply a condition unlike the else statement. Once again, you need a if statement before else if. Else If statements also follow another crucial rule. There can only be 1 else if statement in a file. Adding anymore will give you a nasty parse error. Example time...

$a = "1"; $b = "2"; if ($a == "2") { echo 'a does not equal 2!'; } else if ($b == "2") { echo 'b however equals 2'; }

Else Ifs can get wicked. Of course so can If statements. You can also have if statements inside if statements and such but I don't have time to explain that stuff. Hope you learned alot from this tut. :)

Mail()

To send an email in PHP is very simple. Just use the mail() function. Here is an example:



<?php 
         mail
('to@whom.com''subject of the email'"the email's message!""headers"); 
?>

The only required parameters are the first 3 (to, subject, and message). The headers are what can make HTML enabled, and show who the email is from. Here is an example:


<?php 
// HEADERS: 
    
$headers "From: from@whom.com"
    
$headers "Content-type: text/html"
    
// To 
    
$to "colby@virst.net"
    
// Subject 
    
$subject "A test"
    
$message "<html><head> <title>An email</title> </head> <body> 
    <b>HELLO!</b> This is a <u>really</u> cool email! </body> </html>"

    
mail($to$subject$message$headers); 
?>

When the person gets the email it will look like this: HELLO! This is a really cool email!

mod_rewrite

For this tutorial a host with PHP Support (and .htaccess) is reccomended.


If you have ever visited bigger sites that have urls like, http://blah.com/tutorials/10120/p1/ You may have thought to yourself, Pfft creating all those folders is pointless. But they are not actually folders, They are parts of query string using mod-rewrite. You can turn http://yourdomain.com/?action=view&page=episodes&id=101 into http://yourdomain.com/view/episodes/101/

For this example I am going to show you how I changed my episode guide script urls to be tidier. First things first, Open up notepad (or a text editor) and add this, RewriteEngine On That is turning Apache's mod_rewrite on. Now for the entry, My episode guide uses urls like, ?module=episode&id=101 So to change that into, /episode/101/ We use regexp. RewriteRule ^(.*)/(.*) /episodeguide.php?module=$1&id=$2

^(.*)/(.*)

is the new address we want, If we replace the regexp with some pretend content like episode/101 then you can see how it works.

/episodeguide.php?module=$1&id=$2

That replaces the content of (episode/101) and puts each in its correct place, So now when people visit http://yourdomain.com/episode/101/ they are really seeing http://yourdomain.com/episodeguide.php?module=episode&id=101

RewriteRule ^(.*)/(.*) /episodeguide.php?module=$1&id=$2 The / is important, This seperates what you want to use, with what you want to show.

If I wanted to have more query strings, I would just replace with:
RewriteRule ^(.*)/(.*)/(.*)/(.*) /blah.php?input=$1&extra=$2&but=$3&while=$4
You get the idea :) You now should have the knowledge to make friendly urls using mod_rewrite

Object Oriented Programming

Introduction

PHP is a very powerful tool. The question how will you wield it? With standard programming or with the quick object-oriented programming? Well, the choice is up to you. I find standard a bit easier and quicker to write, but I find the speed and organization of object oriented programming make it no comparison. In this guide I will teach you the basics, and pretty much as much as I know, about Object Oriented Programming (here-on-out known as OOP).

Terms to know:

Class-This is basically what stores local variables and functions, to be later acted upon with an object.
Object Instance-A use of a class, somewhat confusing at first, but I'll go more into later.
Member Variable-A variable inside the class.
Member Function-A function inside the class.
Child Class-A child class extends a parent class, holding all of it's member variables and functions. It can then have additions put on it.
Constructor-A function that takes the class vars (from the initiation) and assigns them variables.

Syntax

Class & Member Variables and functions:

class className { var $myvar; function greet(){ print "Hello World"; }}

Not very much to look at. The top part is really just declaring the class, and the $myvar part is declaring a member variable, very simple. Declaring a function is very easy, just like regular. There is some more to it that I will talk about later in the tutorial.

Object Instance:

$newClass=new className; $newClass->greet();

Again very simple once understood, it took me a little while to catch on due to bad explanations, but anyhow: The $newClass=new className is just creating a new instance of the class I made up above. What is that doing really? It's just allowing you to access the member variables and classes using the variable you declared it as. Then as you can see on the next line, it's all still very simple, you use the variable that you declared the object instance as, and an arrow (->) then write what you want. Variables do not have to have another dollar sign.

Child Class:

class newchild extends className{ }

Very simple, you just add an extends and the name of the class that you want it to be a child of. A class can only have one parent. I'm not going into much depth here, as I don't feel it's really necessary. If you have questions feel free to ask.

Functions:
class example { var $count=0; function writeb($text){ print '<b>'.$text.'</b>'; $this->count++; }}

All I really want to point out here is the $this->count++ part, as you can see it is almost exactly like a new object instance, only difference is it uses $this. In functions, to use member variables you have to put an $this-> in front, very simple.

Constructor:

class consex { var $count; var $rem; function consex($count,$rem){ $this->count=$count; $this->rem=$rem; }

You put all the vars to register in the function declaration, then you can put everything else in there. A constructor is called every time an instance of the class is called. An example of calling a class with a constructor: $cons=new consex(3, "action");

PHP File Uploader Tutorial

This will learn you how to upload files on your website Here is the code



<?php 
    
echo "<form action='' method='post'> 
        <input type='file' name='file'><br/> 
        <input type='submit' name='submit' value='Upload File'></form>"

        if(isset(
$_POST["submit"])){ 
            
$filetm $_FILES['file']['tmp_name']; 
            
$file $_FILES['file']['name']; 
            
$dr "files/"
                if(
move_uploaded_file($filetm,$dr.$file)){ 
                    echo 
"File uploaded successfully<br/>Thank you for uploading the file"
            }              } 
?>

I will explain the code

echo "<form action='' method='post'> <input type='file' name='file'><br/> <input type='submit' name='submit' value='Upload File'></form>";

This will print out the form

if(isset($_POST["submit"])){ $filetm = $_FILES['file']['tmp_name']; $file = $_FILES['file']['name']; $dr = "files/";

If the Upload File button is clicked, it will then put the temporary file in a variable and the file name in a variable and it will put the directory of the file to be uploaded in a variable.

if(move_uploaded_file($filetm,$dr.$file)){ echo "You have uploaded the file successfully<br/>Thank you for uploading the file";

This will upload the file to the server and print a message saying you have uploaded the file successfully.

Thank you for reading my PHP Uploader tutorial Thank you Michael

PHP Form POST and GET Tutorial

This tutorial will learn you the POST and GET method's of form's GET Method The GET method is an alternative to the POST method. If we were to change the method to GET, it would look like this

<form action="page.php" method="get"> Test: <input type="text" name="text"><br/>
Test:
<input type="text" name="textt"><br/>
<input type="submit" name="submit"
value="Submit"></form>

The GET method is different to the POST method, the GET method passes the variables to along to the page.php by appending the variables to the end of the page.php URL. The URL would look like this page.php?text=value&textt=value. The question mark tells the browser that the following items are variables. Now that we have changed the form method to GET, we need to set the variables like this

$item = $_GET['text']; $itemt = $_GET['textt'];

Using the GET method, the code will show the variables to the user, so be sure you are not sending passwords or any other sensitive information with the GET method. POST Method

<form action="page.php" method="post"> Test: <input type="text" name="text"><br/>
Test:
<input type="text" name="textt"><br/>
<input type="submit" name="submit"
value="Submit">
</form>

This code will send the data to page.php using the POST method. The way PHP does this is to store the data into an array $_POST. Be sure to take note of the input names, as they will represent the keys in the $_POST array. We need to set the variables $text = $_POST['text']; $textd = $_POST['textt']; The form names are used as the keys in $_POST, so be sure you don't have two input forms with the same name. Thank you for reading my PHP Form POST and Get tutorial. Thank you Michael

PHP Guestbook Tutorial

This will learn you how to make a guestbook in PHP Here is the SQL code

CREATE TABLE `guestbook` ( `id` INT NOT NULL AUTO_INCREMENT, `name` TEXT NOT NULL, `message` TEXT NOT NULL PRIMARY KEY(`id`) );

Here is the code for guestbook.php

<?php mysql_connect('server','username','password'); mysql_select_db('database'); $queryy = "SELECT * FROM `guestbook` WHERE `id`!='0' ORDER BY `id` DESC"; $fft = mysql_query($queryy); while($ffft = mysql_fetch_array($fft)){ echo "Name: ".$ffft['name']."<br/><br/>Message: ".$ffft['message']."<br/><br/>"; } ?>

I will explain the code mysql_connect('server','username','password'); mysql_select_db('database'); This will connect to the database, you need to change server, username and password and database.

$queryy = "SELECT * FROM `guestbook` WHERE `id`!='0' ORDER BY `id` DESC"; $fft = mysql_query($queryy);

This will select everything from the table guestbook and execute the query.

while($ffft = mysql_fetch_array($fft)){ echo "Name: ".$ffft['name']."<br/><br/>Message: ".$ffft['message']."<br/><br/>";

This is a while loop and this will print out the guestbook messages. Here is the code for addmessage.php

<?php mysql_connect('server','username','password'); mysql_select_db('database'); if(!isset($_POST['submit'])){ echo "<form action='' method='post'> Your name: <input type='text' name='yourname'><br/> Your message: <textarea name='yourmessage'></textarea><br/> <input type='submit' name='submit' value='Submit Message'></form>"; }else{ $rrrt = "INSERT INTO `guestbook` (`id`,`name`,`message`) VALUES ('','".$_POST["yourname"]."','".$_POST["yourmessage"]."');"; mysql_query($rrrt); echo "You have successfully submitted your message<br/>Thank you for submitting your message"; } ?>

I will explain this code

mysql_connect('server','username','password'); mysql_select_db('database');

This will connect to the database, you need to change the server, username and password and database.

if(!isset($_POST['submit'])){ echo "<form action='' method='post'> Your name: <input type='text' name='yourname'><br/> Your message: <textarea name='yourmessage'></textarea><br/> <input type='submit' name='submit' value='Submit Message'></form>";

This checks to see if the Submit Message button isn't set, it will print out the form.

}else{ $rrrt = "INSERT INTO `guestbook` (`id`,`name`,`message`) VALUES ('','".$_POST["yourname"]."','".$_POST["yourmessage"]."');"; mysql_query($rrrt); echo "You have successfully submitted your message<br/>Thank you for submitting your message";

If the Submit Message is set, it will insert the data in the database and execute the query and print out a message saying you have successfully submitted your message thank you for submitting your message.

Thank you for reading PHP Guestbook tutorial Thank you Michael

PHP Security Tutorial

This tutorial will teach you the common mistakes in PHP with a security risk Includes

<?php if(isset($_GET['page'])){ include($_GET['page']); } ?>

This will check to see if the ?page variable is set, if ?page is set it will execute the file in the variable page. This code will look like http://www.website.com/page.php?page=main.php, this is a security risk as a user can execute any PHP code from their server on your server. When a user executes the PHP code from their server to your server it will look like this http://www.website.com/page.php?page=http://www.userswebsite.com/page.ph....

You can prevent this by checking to see if the page variable has a certain value

<?php if($_GET['page'] == "page"){ include('page.php'); } if($_GET['page'] == "index"){ include('index.php'); } ?>

This will check to see if ?page=page is set and if it is it will include page.php, it will also check to see if the ?page=index is set and if it is it will include index.php. User Authentication

<?php if($auth == "1"){ include('page.php'); }else{ include('index.php'); } ?>

This will check to see if the variable auth as the value of 1, if it does it will include page.php. If the variable auth is not the value of 1 it will include index.php. This is a security risk as a user can put http://www.website.com/page.php?auth=1 and it will display page.php.

You can prevent this by making a form which as a username and password text box and a submit button, if username is a certain value and the password is a certain value it will include page.php. If the user submits the wrong username and password it will include index.php.

<?php echo "<form action='' method='post'> Username: <input type='text' name='username'><br/> Password: <input type='password' name='password'><br/> <input type='submit' name='submit' value='Login'></form>"; if(isset($_POST['submit'])){ $username = $_POST['username']; $password = $_POST['password']; if($username == "username" && $password == "password"){ include('page.php'); }else{ include('index.php'); }} ?>

This will print out the form and check to see if the user and clicked the Login button. If the user as clicked the Login button, it will put the value of username and password in a variable and check to see if the username and password are a certain value. If the username and password are the correct value, it will then include page.php. If the username and password are the incorrect value, it will include index.php.

Thank you for reading my PHP Security tutorial Thank you Michael

PHP Shoutbox Tutorial

This tutorial will learn you how to make a shoutbox This is the SQL query code

CREATE TABLE `shouts` ( `shoutid` INT NOT NULL AUTO_INCREMENT, `name` TEXT NOT NULL, `comment` TEXT NOT NULL PRIMARY KEY(`shoutoutid`) );

This is the shoutbox.php code



<?php 
    mysql_connect
('server','username','password'); 
    
mysql_select_db('database'); 
    echo 
"<form action='shoutbox.php' method='post'> Name: <input type='text' name='name'>
    <br/> Comment: <textarea name='comment'></textarea><br/> 
    <input type='submit' name='addshout' value='Add Shout'></form>"

        if(isset(
$_POST["addshout"])){ 
            
$queryye "INSERT INTO `shouts` (`shoutid`,`name`,`comment`) 
            VALUES ('','"
.$_POST["name"]."','".$_POST["comment"]."');"
            
$rrrr mysql_query($queryye); 
            echo 
"Your shout has been posted<br/><br/>Thank you for posting a shout"
        } 
    
$queryyry "SELECT * FROM `shouts` ORDER BY `shoutid` DESC"
    
$rrre mysql_query($queryyry); 
    while(
$rs mysql_fetch_array($rrre)){ 
    echo 
"Name: ".$rs["name"]."<br/>Comment: ".$rs["comment"]."<br/><br/>"; }
?>

I will explain the code

mysql_connect('server','username','password'); mysql_select_db('database');

Connect's to the database, you need to change server, username and password and database.

echo "<form action='shoutbox.php' method='post'> Name: <input type='text' name='name'><br/> Comment: <textarea name='comment'></textarea><br/> <input type='submit' name='addshout' value='Add Shout'></form>";

Print's the form to add a shout

if(isset($_POST["addshout"])){ $queryye = "INSERT INTO `shouts` (`shoutid`,`name`,`comment`) VALUES ('','".$_POST["name"]."','".$_POST["comment"]."');"; $rrrr = mysql_query($queryye); echo "Your shout has been posted<br/><br/>Thank you for posting a shout";

Check's to see if the Add Shout button is click, if the Add Shout button is clicked it will insert the shout in the database. It will execute the query and print a message.

Thank you for reading my PHP Shoutbox tutorial Thank you Michael

PHP Sockets Tutorial

This tutorial will learn you how to use sockets in PHP Sockets can be used to open connections to other people's computer, or to accept incomming connections on your own computer. There are two ways to open a socket, using the socket_ functions and using the fsockopen() function. With the fsockopen function, you can't listen for connections you can only connect to other people's computer. Creating a Socket You need to create a socket using the socket_create() function. The syntax of the socket_create() function is

$socket = socket_create(domain,type,protocol);

A example of this code in use is

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

The first parameter is the domain, there are two types of domains AF_INET IPv4 internet based protocols, TCP and UDP are common protocols of this protocol family. AF_UNIX Local communication protocol family You will be working with the AF_INET domain, as this is the internet based domain. The second parameter is SOCK_STREAM, this can read and write to the socket. The last parameter is the protocol, SOL_TCP is a TCP protocol. Connecting to a Socket You need to connect to a socket using the socket_connect() function. The syntax of this code is

$socketconnect = socket_connect(socketvariablename, address,port);

A example of this code in use is $socketconnect = socket_connect($socket,'URL',6777); The socket we made is called socket, and we assign this variable socketconnect to the variable socket. Reading a Socket We will now read a socket using the socket_read() function, the syntax for the socket_read() function is

$socketread = socket_read(socketname,length,type);

A example of this code in use is

$socketread = socket_read($socket,2444,PHP_NORMAL_READ);

PHP_NORMAL_READ is a way to read the socket Writing to a socket You can write to a socket using the socket_write() function, the syntax for the socket_write() function is

socket_write(socketname,string,length);

A example of this code in use is

socket_write($socket,"Test",6800);

Thank you for reading my PHP Sockets tutorial Thank you Michael

Protection

Includes

Never include a file based on user input, for example $file = $_GET['file']; include($file); A user could easily use that to include sensitive files (such as your password directorys). This could also be used to include a file from another server, at best this could cause your script to return an error, at worse delete a database (or access sensitive info from it).

$file = $_GET['file']; switch($file){ case '': include("pages/index.php"); break; default: include("pages/index.php"); };

Is secure because it only loads the pages above, so if a user tried ?file=http://101.101.101.10/defaced.php They would only see your Index page. Another solution could be to add your pages (secure pages) to an array, and check the input to see if it is the array.

$file = $_GET['file']; $files = array('index.php', 'cast.php', 'google.php'); if( in_array($file, $files) ) { include($file); { else { die("Unlucky!"); }

File Extensions

You may have seen allot of scripts using .inc , .mdu or any other extension they invent for Include files. CuteNews for example includes files like, install.mdu , The problem being if somebody sets their browser to http://mydomain.com/include/install.mdu , The file contents will be displayed. So if you do not want a files contents to be viewable (Maybe it contains your Database info, or other sensitive information) use .php extension! (install.mdu.php would work also)

Register Globals

As of PHP 4.2 Register Globals are turned of by default, and for good reason. Using these makes scripts very insecure, this small paragraph will tell you why. Lets say I created a login script, I wanted to check if the Username and Pass are correct to used if ($username == 'Chandler' and $password == 'Badabing') $authorized = true; }; That seems right, whats the problem? The problem is a register global is auto created for information sent via form (post), url (get), Cookie or Session.

We want to check the form, but PHP will check all 4, I could easiy add ?authorized=1 to the location of the Login script, and be viewing the Colonel's secret recipe instantly. :angry: So now the secret tatic you have being planning to unveil is being posted all over the net.

PHP has some new functions for getting info, which will be discussed in other tutorials. You should now have an understanding of making PHP script securer, any User Input should be validated before you carry out your given process, But thats not the end of it (it is for this tutorial though.

Simple GD

This tutorial requires a host with PHP and GD, To check for GD upload file containing <? phpinfo(); ?> to your host and run it. So what is GD? GD is a graphics library that can be compiled with PHP to allow for image manipulations and generation (Note: From PHP 4.3.0 GD will be bundled with PHP, allowing for ease of configuration.) . Now lets you making your first program, [code] header ("Content-type: image/png"); $img = ImageCreate (250, 25) or die ("Unable to create image"); $bg = ImageColorAllocate ($img, 0, 10, 10); $txt = ImageColorAllocate ($img, 233, 114, 191); ImageString ($img, 5, 5, 5, "My first Program with GD", $txt); ImagePng ($img_handle);[/code] That may look like a load of nonsense but it isn't :wink: The first line sends headers to the browser so it will be expecting an image. $img = ImageCreate (250, 25) or die ("Unable to create image"); That creates the image, and to the size we specify. $bg = ImageColorAllocate ($img, 0, 10, 10); That allocates color to our img (notice the $img reference). The numbers (0,10,10) are RGB references (You cannot directly use HEX colors). $txt = ImageColorAllocate ($img, 11, 65, 110); That allocates color to the text will soon be creating. Again the numbers are RGB colors :) ImageString ($img, 5, 5, 5, "GD rulez!", $txt); That adds our text to the image, the 3 numbers are the co-ordinates for the text. ImagePng ($img_handle); That final line simple makes the Image into PNG format. ImageJPEG and ImageGIF would work also :)

Simple Sessions

To use sessions on a page, you must have this session_start(); That must appear before anything is output to the user so, echo 'Help!'; session_start(); would output errors. session_start(); Is fine since nothing is sent to the user,

Bla Bla Bla <? session_start(); ?>

&

To use sessions on a page, you must have this session_start(); That must appear before anything is output to the user so, echo 'Help!'; session_start(); would output errors. session_start(); Is fine since nothing is sent to the user,

Bla Bla Bla <? session_start(); ?>

&

<? session_start(); ?>

are both wrong, Nothing (even whitespaces should be sent to the user).

Now we have that out of the way, we can move onto doing something with sessions. To define a session we use:

$_SESSION['mysession'] = 'BLA';

Now on the next page we will be able to access that information, Useful to see which page a user came from. To access the Session ID, you can use session_id(); , for example:

$yoursession = session_id(); echo '<a href="?home.php?'.$yoursession.'">Home</a>';

If you do not want to add any info to a session but you wish to create it, you can use session_register("mysession"); If you want to clear ALL sessions use, session_destroy() That removes all sessions and all data. Simple huh? You now should understand the basics of Sessions.

<? session_start(); ?>

strtolower() and strtoupper()

You can use the function strtolower(); to put all the characters in a string lowercase.

Here is an example:



<?php echo strtolower("HELLO! This script is SO cool!\"); ?>

This will output: hello! this script is so cool!

Now, strtoupper does exactly the opposite.

Example



<?php echo strtouppoer("HELLO! This script is SO cool!\"); ?>

Which will output: HELLO! THIS SCRIPT IS SO COOL!

wordwrap()

Two wrap a string you use the function wordwrap(): wordwrap("text", width, "line separator", cut); Example:



<?php 
    $string 
"Hello! This is a really cool function."
    
$wordwrap wordwrap($string6""); 
    echo 
$wordwrap
?>

This will output:

-------
Hello!
This
is a
really
cool
function
.
-------

Notice that each line is about 6 characters long, UNLESS a word is longer than six characters. If you want the function to cut long words in half to fit NO MORE than six characters, put a '1' in the fourth parameter.

Example:



<?php 
    $string 
"Hello! This is a really cool function."
    
$wordwrap wordwrap($string6"",1); 
    echo 
$wordwrap
?>