View Full Version : The Ultimate PHP Tutorial Thread
jazzer01
05-03-2007, 12:55 AM
Well....it does what it says on the tin really!!
Post any tutorials, scripts and the like that you have for PHP here, and help the PHP comunity here!!
If enough people post tutorials, I will create an index for it right.... erm..... Here ==>
I'll go first with a quick hash before bed.....
----------------
include, require
PHP comes with for functions to include an outside file into your script. They are:
include()
require()
include_once()
require_once()
and they take a single argument, the path (or url) to the file to fetch.
For example, I have a template in two files, top.php and bottom.php. To include them in my index.php file, I would use
<?php
include ("top.php");
Welcome to my index page.... etc etc.
include("bottom.php");
?>
In fact, they are all almost identical, except for two things.
1. _once: somewhat obviously, this makes sure that a file is only included once. This is useful when you might have be declaring a function in a page - if you included that page twice, PHP would throw up an error. For example:
index.php includes config.php and functions.php
config.php includes functions.php
functions.php has been included twice, so the interpreter would print an error, becuase a function cannot be redefined once it’s declared. By using include_once() or require_once(), we tell PHP that we only want one instance of the file, so if it has already been included, it won't do it again! :)
The other difference is between the includes and the requires, and it is simply how they handle unfound files - include() and include_once() will post a warning if a files isn't found, whereas require() and require_once() will post an error, and so stop running.
jazzer01
05-03-2007, 01:28 PM
This tutorial is inspired by a forum post I read at WebJrs (http://www.webjuniors.com) about secure contact forms. Millions of websites have some form of contact script, consisting of a form and some processing, and so that is the first thing we will do:
<!-- Filename:contact.html -->
<form name='contactform' action='sendmail.php' method='post'>
<b>Name:</b> <input type='text' name='name' /><br />
<b>E-Mail:</b> <input type='text' name='email' /><br />
<b>Comment</b> <textarea name='comment'></textarea><br />
<input type='submit' value='Send Message' />
</form>
<?php
#Filename:sendmail.php
$to = "me@domain.com"; #email address to send form to
$name = $_POST["name"]; #FOrm field name
$email = $_POST["email"]; #Form field email
$comment = $_POST["comment"]; #Form field comment
mail ("$to","WebForm Submission","Message From $email:\n\n$comment","From:$email"); #Send the email
?>
And there is your basic form - that will accept input and, as long as PHP is set up correctly, email whoever is specified in $to the results.
However, there are some key problems with that code - none of the input is being checked (for example, a user could enter biteme as an email address), and it is an easy target for spam. With a few code updates, we can fix these problems.
Checking Input
To check the input on a form we are going to use regular expressions. Explaining how regex works is outside the scope of this tutorial, but a good site for reference is http://www.regular-expressions.info/. For this, all that needs to be said is that the regex
^(([a-z0-9\.\-_]+)([a-z0-9]+)@([a-z0-9\-]+)(\.[a-z0-9\-]+){1,6})$
will suffice to check emails. The function we are going to use is eregi() (http://uk3.php.net/eregi) - which is a case insensitive regex match, which takes two arguments: The regex expression we are using, and the string we wish to match.
We are also going to make sure that each field has been filled in (by checking that their strlen() (http://www.php.net/strlen) is at least 1. Adding these to our code gives us:
<?php
#Filename:sendmail.php
$to = "me@domain.com"; #email address to send form to
$name = $_POST["name"]; #FOrm field name
$email = $_POST["email"]; #Form field email
$comment = $_POST["comment"]; #Form field comment
$emailregex = "^(([a-z0-9\.\-_]+)([a-z0-9]+)@([a-z0-9\-]+)(\.[a-z0-9\-]+){1,6})$";
if (eregi($emailregex, $email) AND (strlen($name) > 0 ) AND (strlen($comment) > 0 )){
mail ("$to","WebForm Submission","Message From $email:\n\n$comment","From:$email"); #Send the email
}else{
print "There has been an error - please make sure you fill in all the fields, and have used a valid e-mail address";
}
?>
So now we have dealt with bad inputs (agreed there is more you could do, but for most tasks the above will suffice), we can prevent robots from spamming the form. The most common way of doing this is using image verification, however, for servers that don't have GD this becomes tricky (not impossible, as you could have a bank of already made images and a DB table that links image names to their codes), and plus, it is alot of effort for a simple validation form. So, another option that I have seen is text validation. The form asks the user to type a character (or characters) from a random position in a string. We can then get the random number with our form, and check the entry. This means we first need to update our contact form (it now needs to become a PHP file):
<!-- Filename:contact.php -->
<form name='contactform' action='sendmail.php' method='post'>
<b>Name:</b> <input type='text' name='name' /><br />
<b>E-Mail:</b> <input type='text' name='email' /><br />
<b>Comment</b> <textarea name='comment'></textarea><br />
<br />
<?php
$string = "PHP is an ultimate scripting language";
$rand = rand(1,strlen($string));
print "For verification purposes, please enter character $rand from the following sentence: $string<br /><input type='text' name='letter' size='1' />";
#Pass the random number with the form:
print "<input type='hidden' name='number' value='$rand' />";
?>
<input type='submit' value='Send Message' />
</form>
Now in our processing form, we can check that the correct value has been entered, and if it has, continue sending the email:
<?php
#Filename:sendmail.php
$number = $_POST["number"]; #Random number generated
$letter = $_POST["letter"]; #Verification Letter
#Check the validation (remember that the first character is in position 0)
$char = substr("PHP is an ultimate scripting language",$number-1,1);
if ($letter != $char){
print "There has been an error: Your verification letter was incorrect. Please try again";
}else{
$to = "me@domain.com"; #email address to send form to
$name = $_POST["name"]; #FOrm field name
$email = $_POST["email"]; #Form field email
$comment = $_POST["comment"]; #Form field comment
$emailregex = "^(([a-z0-9\.\-_]+)([a-z0-9]+)@([a-z0-9\-]+)(\.[a-z0-9\-]+){1,6})$";
if (eregi($emailregex, $email) AND (strlen($name) > 0 ) AND (strlen($comment) > 0 )){
mail ("$to","WebForm Submission","Message From $email:\n\n$comment","From:$email"); #Send the email
}else{
print "There has been an error - please make sure you fill in all the fields, and have used a valid e-mail address";
}
}
?>
By using this, we have provided a simple, yet effective way to validate user input, and to protect against spammers. There is more you could do with this script, but for most purposes, the above is fine :)
Liam Wiltshire is a web developer working in both Leeds and Swindon, UK. He specialises in PHP, and custom scripting (http://www.lsw-computing.co.uk), as well as working on his own projects. For more information, and other scripts and tutorials, visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
rsanek
05-03-2007, 03:22 PM
Great tutorial! I've been searching around for something like this, I'll try it later. I'm learning php, so This will be great to look through the code. Thanks!
jazzer01
05-03-2007, 03:43 PM
Great tutorial! I've been searching around for something like this, I'll try it later. I'm learning php, so This will be great to look through the code. Thanks!
No problem!! Hopefully, other people will catch on and start posting tutorials too! - I have quite a few to post, but they are on my desktop, so I won't be posting them till next week (I'm @ uni on a laptop lol). But yeah - this is a great way for anyone with PHP knowledge to get their name out there - using an about box at the bottom is great for SEO (provides another link back to your site, and potentially more if others start posting your tutorials too!).
jazzer01
05-03-2007, 11:14 PM
Ok, so I was sat for a while, trying to work out what I would write my next tutorial on, and I found myself coming up with ideas that just made it feel like I was jumping about all over the place. So I thought I would break it down a bit, and look at a slightly more basic, but larger subject....and so, I present to you the first of three 'crash course' tutorials....Strings!
What Is A String?
In PHP, and indeed in any programming language, a string is a series of characters that do not form a number (so ab12da is a string, but 12345 is a number!).
For alot of simple processing in PHP, string manipulation will be at the heart of what you do.
The most basic string function is print("") - and it just 'prints' whatever is inside the quotes to the browser. For example:
<?php #All PHP coding starts with this
print ("hello PHP world"); #print hello PHP world to the browser
?> #End a block ok PHP code
Will result in:
hello PHP world
being sent to the browser.
As with HTML, you have to be careful when it comes to special characters - imagine you had this code:
<?php #All PHP coding starts with this
print ("hello "PHP" world"); #print hello "PHP" world to the browser - or will it?!
?> #End a block of PHP code
By remember that PHP will print out anything between the "...", you can see that there will be a problem! So to avoid this, we use \ (backslash) to 'escape' a character:
<?php #All PHP coding starts with this
print ("hello \"PHP\" world"); #print hello "PHP" world to the browser
?> #End a block ok PHP code
Will result in hello "PHP" world being sent to the browser. :)
There are other special characters that have special meanings in PHP that also need escaping, but you will come across these as you code and learn more!
Finding the Length Of A String
There are times (such as the secure form tutorial above) when you might want to find the length of a string. For this we have a function called strlen(""), whuch just takes the string to count as its argument.
One thing to note however - if you want to print out a function result, you do not use the "...", as shown below:
print ( strlen("this is a string") );#print out the length of the string
This would just return the number 16 :)
Strings Inside Strings
Another thing you might want to do is get strings from other strings. The function for this is slightly more complex it is called substr(), and takes three arguments. The string to take the new string from, the start position, and the length. A note about PHP positioning - just like most programing languages, when PHP is referencing a position, such as the position in a string, the counting starts at 0 (don't ask me why, I have no idea!). That means that the first character is at position 0, the second is at 1, etc.... So say we wanted a substring that started from the fourth letter and was 4 letters long, we would use substr("thisisastring","3","4");.
Again, because this is a function, if we wish to print it out, we do not use ".." in print:
<?php
print ( substr("hello PHP world","3","6") ); #print out from character 4 for 6 characters
?>
This would produce:
lo PHP
:).
And there you go! There are many many many more functions to do with strings, and the way they work, but I just want to give you a flavour of how strings work, just like I will do with numbers and variables, the other two topics in the series!
There are some syntax things in this tutorial that havn't been covered (such as the fact that most lines end with a semi-colon (;)). At some point I will post a quick guide to PHP syntax - or someone else could post one instead :)
Liam Wiltshire is a web developer working in both Leeds and Swindon, UK. He specialises in PHP, and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials (http://www.lsw-computing.co.uk), visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
mullerrwd
05-04-2007, 10:29 AM
Really nice tutorials guys, I will be posting some of mine, but I will first have to translate them because I made them in dutch:P
jazzer01
05-04-2007, 10:38 AM
Really nice tutorials guys, I will be posting some of mine, but I will first have to translate them because I made them in dutch:P
Yay! I was wondering when other people would start posting - can't wait to see someone elses ideas :)
jazzer01
05-04-2007, 11:02 AM
Ok, so I have to go get a train in about 2 hours, but I had some free time on my hands, so I thought I would post my guide to PHP syntax, as I promised I would (don't worry, my next full tutorial will be online tonight - I'm going home, so I'll be on my desktop :))
The Layout of a PHP page
First thing to remember - PHP have a .php extention! There are some exceptions, but they are still obviously php files!
As you may or may not know, PHP files can be a combination of PHP and HTML. Blocks of PHP code have to be marked out with two tags: <?php at the start, and ?> at the end:
<html>
<head>
<title>A Webpage</title>
</head>
<body>
<?php #Start of PHP block
Some PHP code goes here!!
?> <!-- End of PHP block -->
<b>Some more HTML</b>
<br />
<?php #Start of PHP
Some more PHP code
?>
etc. etc. You can keep coming in and out of PHP code at any time in a PHP page, by using <?php and ?>
General Rules
In PHP, most lines of code end with a semicolon ( ; ) - there are two main exceptions - conditionals (if then else), and the <?php and ?> lines
Variables in PHP are deliminated with the dollar sign. There aren't different signs for different types, as the variables can change. For example, if I wanted a variable called box with the value water, I would write:
$box = "water";
Variables must only use letters, numbers and underscores, and must start with a letter.
' vs " - in PHP, strings are placed inside quote marks. Both single and Double can be used, but they have different effects.
' Will process everything inside them literally. For example:
<?php
$box = 'water'; # $box now contains water
print 'This is a $box'; #Will display This is a $box
?>
Will return This is a $box to the browser, as it processes the $ as a literal character. On the other hand:
<?php
$box = 'water'; # $box now contains water
print "This is a $box"; #Will display This is a water
?>
Will return This is a water.
The Great Escape
Certain characters (such as ',",$ that we have seen already) have special meanings in PHP. In order to use them we can do one of two things:
~ If we are using single quotes, then its fine, as all characters are taken literally.
~If we need double quotes (say there is a variable we need to parse), then we need to escape the characters to be printed. In PHP this is done with a backslash.
For example, if we had a line of code:
<?php
print "That book costs $4.50";
?>
PHP would try to make sence of $4 - incidently it would fail, as all variable names must start with a letter, but it would try. However, if we escape it, so it becomes \$, it will be fine:
<?php
print "That book costs \$4.50";
?>
Other characters that need escaping include:
\\ backslash
\$ dollar sign
\" doublequote
\' single quote
There are also others, but they are outside the scope of this tutorial.
Comments
In PHP, it is often useful to write comments (text that doesnt get displayed by PHP), so that you can see whats happeneing if you come back to it at a later date to make changes. You have already seen examples of comments in the above examples. There are three ways to comment PHP:
#This is a Comment
//This is also a Comment
/* This is a comment block
Everything here will be commented
until we end the comment with */
And there we go - of course there are exceptions to rules, and more advanced syntax understand, but this should help you understand code samples, and make things clearer when you are trying to follow tutorials :)
Liam Wiltshire is a web developer working in both Leeds and Swindon (http://www.lsw-computing.co.uk), UK. He specialises in PHP, and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials, visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
Syntax
05-04-2007, 11:07 AM
Really nice tutorials! You should think about writing a program which processes simple PHP/MySQL. It should help less advanced users of it :)
jazzer01
05-04-2007, 07:19 PM
Really nice tutorials! You should think about writing a program which processes simple PHP/MySQL. It should help less advanced users of it :)
THanks - feel free to use any of them on your own sites! Just please leave the box at the bottom intact :). Hopefully soon I will be starting an RSS feed of tutorials from my site - if anyone is interested let me know.
I havn't really done anything major in terms of scripts for the public in a while - been working on my new project - currently stands at about 8,500 lines of code over 45 files :) and I'm only about 2/3 of the way through it, but I hope to start doing some public scripting again soon :)
jazzer01
05-04-2007, 11:02 PM
Welcome to part two of the PHP crash course. This tutorial is going to discuss variables. We have already come accross variables in other tutorials, but now we will look at them in greater depth.
Variables are one of the most common items that appears in php. It is almost like a box that can hold a piece of information.
You can think of it like this. The weather outside is also a variable. It is a variable because it changes. But it still comes under the name weather. In PHP, all variable names start with a $ so for example:
$weather = "fine" ;#the weather
To define a variable (set its value), you simply do $variable = "text"; you can assign the value of a variable to another variable, and you can also use other functions on it.
We are going to look at our hello script again, but we are going to assign a value to a variable, and then print it out:
<?php
$to = "PHP world"; #create the variable $to, and give it a value of PHP world
print ("hello $to");
?>
Notice how we have created the variable $to, and given it a value of PHP world? We are then printing the string hello $to - guess what the output will be? hello PHP world :).
$to could be set to anything - we could set $to as Web Juniors, and the message would be hello Web Juniors, or indeed anything else.
This is just a basica example of what variables can do - they are essential in almost all PHP scripts, as they carry the data around the script.
Now, onto a slightly more complicated type of variable....
Arrays
If a standard variable is a box that holds data, then arrays are like a group of boxes that can hold data, but each one has been given a name.
Using our weather example again, we could say that the weather is sunny, windy and hot. So if you imagine our boxes:
|Sunny||Windy||Hot|
Remembering that PHP indexes start at 0, it means that:
$weather[0] contains Sunny
$weather[1] contains Windy
$weather[2] contains Hot
Notice how the variable had a number in square brackets after it? This is how we reference the position in a variable.
There are many ways to assign values to a variable. The first is the array() function. It takes an unlimted amount of arguments, each one being a 'box' in the array. For example:
<?php
$weather = array("sunny","windy","hot");
?>
Would create the array we were talking about earlier. Another way is to specify which position in the array to insert the data. To do this we use our square brackes, and the number of the box we want to put it in:
<?php
$weather[0] = "sunny";
$weather[1] = "windy";
$weather[2] = "hot";
?>
This would also create the array we created earlier. If you just want to add an array item to the next available box, you leave the square brackets empty (eg. $weather[] = "sunny"; )
And there you have it! There are many other things you can do with variables, but hopefully, now you understand how they work and what they do, so that when these functions come along, they are easier to understand :)
rsanek
05-05-2007, 12:34 AM
You definitely need a site (if you don't already) to post these tutorials on. They're great!
jazzer01
05-05-2007, 01:12 AM
You definitely need a site (if you don't already) to post these tutorials on. They're great!
lol thanks :) - I actally havn't got them posted anywhere else at the moment - like I mentioned, I've been so caught up in this project I am working on, I really havn't done anything else for ages - expect sell a few domains to keep my head afloat!! :p
rsanek
05-05-2007, 03:37 AM
lol thanks :) - I actally havn't got them posted anywhere else at the moment - like I mentioned, I've been so caught up in this project I am working on, I really havn't done anything else for ages - expect sell a few domains to keep my head afloat!! :p
lol 'head afloat'. I try to take time out of my schedule to work on my sites so I don't get caught up in it like you.
jazzer01
05-05-2007, 04:15 AM
lol, my excuse is that I'm a uni student - not sure if it is a good excuse or not, but its my excuse anyway! :p
jazzer01
05-06-2007, 09:37 PM
For the final part of the PHP crash course, we are going to look at numbers.
PHP is very good at handeling numbers and mathmatics as well.
The most obvious uses are the simple +(add),-(subtract),*(multiply) and / (divide).
For Example, to add two numbers together and assign them to a variable you would do:
$variable = 5 + 6; #adds 5 and 6 (11) and assigns them to $variable
Notice how again i have used the # to comment a section. PHP maths follows the same order of precedence (the order in which the signs are used), as normal maths. Therefore, to make sure you get the answer you want, if using multiple operators (+,-,/ etc), it is a good idea to use brackets (,). Eg:
$sum = 4 + (6 / 2); #$sum is equal to 7
$num = (4 + 6) / 2; #$num is equal to 5
As well as these basic signs, there are other, more complicated signs:
% - Modulus (Finds the remainder when you divide a by b):
$number = 5 % 2; # $number is equal to 1 (5 / 2 = 2 remainder 1)
$number = 7 % 3; # $number is equal to 1 (7 / 3 = 2 remainer 1)
++/-- : Increases/Decreases a number by one EG:
$number = 4;
++$number ; # $number is now 5
++$number; # $number is now 6
--$number; # $number is now 5
--$number; # $number is now 4
PHP also has other built in mathmatical functions. These are the main ones:
round() Rounds a decimal to the nearest whole number(integer). For example:
$number = round(23.3009); # $number is 23
$number = round(23.68); # $number is 24
abs() Returns the absolute value of a number (always positive). EG:
$number = abs(-23); # $number is 23
$number = abs(23); # $number is 23
$number = abs(a); # $number is 0
And thats it for another day :) Hopefully this quick crash course will help you understand the other tutorials that people post that bit more, and soon you will be writing your own! :)
Liam Wiltshire is a web developer working in both Leeds and Swindon, UK. He specialises in PHP (http://www.lsw-computing.co.uk), and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials, visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
jazzer01
05-08-2007, 12:26 AM
I havn't been at my laptop all day, so this will only be a short tutorial today - hopefully some of you guys will find it useful :)
Alot of what you do in PHP will revolve around forms. Whether handling email forms, or user logins, shopping carts or forums, forms are used extensivly. Knowing how to handle them, get the results from them, and doing so SAFELY is always important.
Getting data from a form
If you know HTML, you will know that when you send a form, you have two options for the method you use - get or post. Most commonly we use post (the difference is that, in get, the values are sent in the URL, but with post, they are sent in the headers). PHP has two variables that automatically retrieve the values submitted in a form: $_GET["fieldname"]; and $_POST["fieldname]; - no prize for guessing which one handles which method!! :p
Quick Tip: It is normally easier to assign the values to individual variables - standard variables are easier to work with
So, if we had a basic form:
<form action='submit.php' method='post'>
<input type='text' name='name' />
<input type='submit' value='submit' />
</form>
To get the value of name, and to print it out, we might do:
<?php
$name = $_POST["name"];
print "$name";
?>
And that is the basics of retreving results from a form. However, by doing this, you could create problems for yourself! Although not as much of a problem when just displaying the results of a variable, if you were storing variable results to a database, it would be easy for a user to submit malicious values in a form field. Therefore, always check EVERY value submitted, making sure it is what you expected.
Ways you might do this:
Check the length isn't too long (for example, a name is unlikly to be 100 characters long)
Check numeric values are within a correct range (it would be strange if a 250 year old was signing up to your site)
Check inputs such as email addresses are of the correct pattern (would you try sending an email to ilovephp%^&*%@cheese@moose@net.conetworkpro ?)
Check that specific characters are used (again, names do not include % signs, for example).
How to implament data checking
We are going to imagine that a user has submitted the following form:
Name: [__________]
Age : [__________]
Email:[__________]
So, first thing we will do is get the variables into our script:
<?php
$name = $_POST["name"];
$age = $_POST["age"];
$email = $_POST["email"];
?>
.
Now we can start to validate the input. We will start by checking the $name. We are going to check that a) it is no longer than 100 characters, and that it only contains letters and spaces.
To check the first part, we can go back to our strlen()n function. To check that it contains the right characters, we are going to use a regular expression, using the eregi() function. The regex we are going to use is ^[a-z][a-z ]+[a-z]$ which basically means: Start with a character from a to z (^[a-z]), then match any number of the characters a to z and spaces ([a-z ]+), and then end with a character from a to z ([a-z]$). The eregi() function basiaclly is a case insensitive regex match, and takes two arguments, the expression we are trying to match, and the string to match it to. So, now, our code will look like:
<?php
$name = $_POST["name"];
$age = $_POST["age"];
$email = $_POST["email"];
if (strlen($name) > '100'){ #If length of $name is greater than 100, show an error
print "<b>Sorry, but your name should be no more than 100 characers long</b>";
die(); #Stop running the script
}
if (!eregi("^[a-z][a-z ]+[a-z]$",$name)){ #if $name doesnt match our pattern (! means not)
print "<b>Sorry, but your name isn't valid</b>";
die(); #Stop running the script
}
?>
Next we will validate the age. We are going to assume that noone younger than 5 will sign up, and noone older than 125 will sign up (just as an example). We do not need any specific functions for this, we just check that $age isnt < (less than ) 5, and $age isnt > (greater than) 125 :
<?php
$name = $_POST["name"];
$age = $_POST["age"];
$email = $_POST["email"];
if (strlen($name) > '100'){ #If length of $name is greater than 100, show an error
print "<b>Sorry, but your name should be no more than 100 characers long</b>";
die(); #Stop running the script
}
if (!eregi("^[a-z][a-z ]+[a-z]$",$name)){ #if $name doesnt match our pattern (! means not)
print "<b>Sorry, but your name isn't valid</b>";
die(); #Stop running the script
}
if ($age < 5 OR $age > 125){ #If age is less than 5 or greater than 125, display an error
print "<b>Sorry, but your age should be between 5 and 125</b>";
die(); #Stop script
}
?>
Finally, we will go back to our regex to check our emails. There are lots of different regexs for emails, each with their pros and cons. For the sake of this tutorial, I am going to use ^(([a-z0-9\.\-_]+)([a-z0-9]+)@([a-z0-9\-]+)(\.[a-z0-9\-]+){1,6})$
This basically means start with any number of characters a-z, 0-9, periods, hypens and underscores ([a-z0-9\.\-_]+), then any number of a-z and 0-9 ([a-z0-9]+), then an @. Then any number of a-z, 0-9, hypens ([a-z0-9\-]+), and finally ending with between 1 and 6 of a-z, 0-9, periods and hypens ((\.[a-z0-9\-]+){1,6})$)
This is quite a complex pattern, and sure will still let some invalid email addresses through, but there is no perfect regex for email it will always be a tradeoff.
Using this, our final script is
<?php
$name = $_POST["name"];
$age = $_POST["age"];
$email = $_POST["email"];
if (strlen($name) > '100'){ #If length of $name is greater than 100, show an error
print "<b>Sorry, but your name should be no more than 100 characers long</b>";
die(); #Stop running the script
}
if (!eregi("^[a-z][a-z ]+[a-z]$",$name)){ #if $name doesnt match our pattern (! means not)
print "<b>Sorry, but your name isn't valid</b>";
die(); #Stop running the script
}
if ($age < 5 OR $age > 125){ #If age is less than 5 or greater than 125, display an error
print "<b>Sorry, but your age should be between 5 and 125</b>";
die(); #Stop script
}
if (!eregi("^(([a-z0-9\.\-_]+)([a-z0-9]+)@([a-z0-9\-]+)(\.[a-z0-9\-]+){1,6})$",$email)){ #if $email doesnt match our pattern (! means not)
print "<b>Sorry, but your email address isn't valid</b>";
die(); #Stop running the script
}
#If it gets to here, all the input is clean :) - continue processing as you require
?>
And there you go, a method for validating input. There are other checks you might like to include for other inputs, and additional things to do, say before you input data into a database, but for most purposes, this is more than enough to ensure that you have clean data :)
Liam Wiltshire is a web developer working in both Leeds and Swindon (http://www.lsw-computing.co.uk), UK. He specialises in PHP, and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials, visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
creativehustle
05-08-2007, 10:22 AM
wow great tutorials thanks
jazzer01
05-08-2007, 01:11 PM
wow great tutorials thanks
Thanks, I'm just trying to roll them out - alot of them are either ones I wrote a while back, or adaptations of old ones, but I have some new tricks up my sleve too! :p
Hopefully if people like the tutorials I'm going to start posting them in a blog type format....tho I'm kinda swamped with projects atm lol
jazzer01
05-09-2007, 01:38 AM
We have already touched upon conditionals in some of the earlier tutorials, but I thought I would go through them in some greater detail, so here we go :).
Once you start processing your data, you will need to know what to do with it. Sometimes this might be simple, like posting it to a database, or just displaying it on screen, but often the action you take will depened on the value of the data you have. This is where conditionals come in.
Conditionals essentially work like this:
IF this is true, THEN do this, ELSE do this. You do not always have to use the entire block (you might just have an if statement by itself), but explaining them together is the easiest way. In PHP, it looks like this:
if (condition){
Functions to run ();
}else{
Functions to run ();
}
Notice how there are no semi-colons at the end of the conditional lines - that is one of thoes examples I was talking abot that do not need a semi-colon at the end of lines.
Now you have the basic shape of the conditional, its time to look at what the condition might be. There are lots of PHP comparison operators. Here are some of the common ones:
$a == $b - $a is equal to $b
$a != $b - $a is not equal to (remember how we said ! means not?) $b
$a <> $b - $a is not equal to (again) $b
$a < $b - $a is less than $b
$a > $b - $a is greater than $b
$a <= $b - $a is less than or equal to $b
$a >= $b - $a is greater than or equal to $b
So for example, if we wanted to get a random number, and display different text depending on the resut, we might do:
$rand = rand(1,30); # Generate a random number between 1 and 30
if ($rand < 15){
print "You got a small number!";
} else {
print "You got a big number!";
}
Thats great, but what if we wanted more options? We could nest if statements together, but that would get very messy very quickly. Instead, we have a way of expanding out statements, with elseif ( in otherwords, if one thing isn't true, try this, then try this etc...).
Once you start doing this, you may want to perform more than one comparison (say if you wanted to check a number was greater than 1 AND less than 10), and for that, we can just use AND:
if (condition AND condition){
...
}
So now we could expand on our script:
$rand = rand(1,30); # Generate a random number between 1 and 30
if ($rand == 1){ # If $rand is 1
print "You got the smallest number!!";
} elseif ($rand > 1 AND $rand < 10) { # otherwise if $rand is greater than 1 and less than 10
print "You got a small number!";
} elseif ($rand > 10 AND $rand <= 20) { # otherwise if $rand is greater than 10 and less than or equal to 20
print "You got a medium number!";
} else { # FInally, if all else fails
print "You get a big number";
}
And that is conditionals in a nutshell! Tomorrow I will discuss something very similar to conditionals, that uses a similar syntax - loops. Have fun till then! :)
jazzer01
05-11-2007, 02:18 PM
Due to a large amount of alcohol, and work, I didn;t get a chance to post a tutorial yesterday. however, as promise, here is the second part of this tutorial: Loops :)
In all programming languages, Loops are an oft useful feature. They allow you to loop through arrays, or print out code x numbers of times, as well as other things.
In PHP, there are three main types of loop: while, for and foreach.
While
While is the most common used loop in PHP. It literally means while this is true, do that.
As mentioned before, loops have an identical syntax to the conditions we looked at before:
while (condition){
#Perform tasks
}
The condition could be any comparison that will provide a true or false answer, but normally we use it to loop through numbers:
$i = "1"; #Set the value of $i to 1
while ($i < "50"){ #While the value of $i is less than 50
print "Loop $i<br />"; # Print Loop and the value of $i
$i++; # Increase the value of $i by one
}
This will loop round 49 times ($i = 1 to $i = 49, because when $i is 50, it is no longer less than 50!), displaying Loop1, Loop2, Loop3 etc..
As we mentioned before, this can be used to loop round an array - all we need to do is test for $i being less than the number of results in the array:
$array[] = "red";
$array[] = "orange";
$array[] = "yellow";
$array[] = "green";
$array[] = "blue";
$array[] = "indigo";
$array[] = "violet";
$count = count($array); # find the number of elements in the array
$i = "0" ; # Remember index counting starts at 0!
while ($i < $count){ #While $i is less than the number of arrays (becuase we start at 0, not 1)
print "$array[$i]<br />"; # display the value of the array element at $i
$i++ ; #increase $i by 1
}
This will loop around each element array and display it - giving us a rainbow! :)
For
For is actually very similar to while. In fact, it does exactly the same thing, in a condensed form. It looks like this
<?php
for ($i=1; $i<=5; $i++){ #initilize a variable; set its condition; set its incrment
print "Loop $i<br />"; # Print Loop and the value of $i
}
?>
As you can see, we have all the parts of our while loop before, but condensed into the main for arguments. First of all you initialise (set) a variable that we will be comparing. THen you set the condition for that variable. Finally you set the increment of each loop (doesnt have to be 1!)
This is usful as it is a condensed version of the loop we saw before, however, it can only be used with increasing numbers, you can't, for example use to loop while a string doesnt match another string, which you can do with while.
Foreach
Finally, we have the actual loop designed to loop round an array, foreach. This is simpler than the other, as you do not have to set an argument. It will just loop round an array once, assigning the value of each array element to a variable. To initiate a foreach, we just need to use:
foreach(array as value){
#Action
}
Where array is the array we are using, and value is the variable we want each value set to.
If we look at our rainbow again, to loop it usng foreach, we might do:
$array[] = "red";
$array[] = "orange";
$array[] = "yellow";
$array[] = "green";
$array[] = "blue";
$array[] = "indigo";
$array[] = "violet";
foreach ($array as $value){ #For each $array element, set the value to $value
print "$value<br />"; # display the value of the array element
}
This would do exactly the same as our while loop before, but with less typing!
And there we go - there are variations of these loops, as well as other loops, but they are alot less common.
Liam Wiltshire is a web developer working in both Leeds and Swindon, UK. He specialises in PHP, and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials (http://www.lsw-computing.co.uk), visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
jazzer01
05-13-2007, 01:37 PM
If you are programming in PHP, there will undoubtedly be a time when you need to encrypt some data, be it passwords, user details, credit card details etc. There are various forms of encryption in PHP, each with their own adantages and disadvantages. Here are the main ones:
crypt() | Built Into PHP --|-- Can't be decrypted - one way encryption
md5() | Built Into PHP, hash function - also good for validating files| Can't be decrypted - one way hash
mcrypt_encrypt() | More secure than PHP versions - can be decrypted | Not included in PHP - seperate mcrypt lib, initialization needed before it will encrypt
You may be thinking - whats the point in string that cant be decrypted? For alot of things, you will not need to decrypt a string - for example, if you have encrypted a password, to check the user has entered the right password, just encrypt that too, and then compare them - they should be the same! :)
These are the main three encryption options that you will come across - if your host has mcrypt, the it is the most secure option, but then it depends on what you need it for.
Now we will go through how to use each function:
Crypt()
PHP's standard crypt function is a one shot function - you just use the crypt() function to do what you require, no seeding or initialisation first. The format of the function is
crypt(string,[salt]).
The salt is an optional paramater, and for most uses, it is better just to leave it to use the system default.
So, if you had a password, and wanted to encrypt it with crypt(), you would use:
<?php
$password = $_POST["password"]; # We are getting the password from a submitted form.
$password = crypt($password); # crypt() $password and assign it back to $password
print "$password"; # display our encrypted password
?>
And thats all you need to do!
md5()
md5 is very similar. It is a one shot function, but this time without an optional paramater. All you need is:
md5(string)
So, if we were going to encrypt the above password in md5(), we would use:
<?php
$password = $_POST["password"]; # We are getting the password from a submitted form.
$password = md5($password); # md5() $password and assign it back to $password
print "$password"; # display our encrypted password
?>
mcrypt_encrypt()
As mentioned before, mcrypt is alot more complex than the other methods discussed. It has a wide range of different options, many of which are outside the scope of this tutorial. However, here is the method you have to go through to intialise and use mcrypt_encrypt();
1. Set the string to be encrypted
2. Set the encryption key (the string that will decrypt the code)
3. Set the algorithm - there are lots to choose from, however, discussing them in detail is a tutorial for its own!! For now we will stick with MCRYPT_RIJNDAEL_128
4. Create the Initialisation Vector (basically brings together the variables you have just set)
5. Encrypt the variable
At this point, you have produced a binary encrypted value of your original string.
To decrypt a string, you need to use the same variables as above, in the following function:
mcrypt_decrypt(algorithm, key,
encrypted string, MCRYPT_MODE_CBC, intialisation vector);
Told you it was more complex!!
So, if you wanted to encrypt your password this was, you would need to use the following:
<?php
$string = $_POST["password"]; # We are getting the password from a submitted form.
$key = "PHP key"; # Set the key
$cipher_alg = MCRYPT_RIJNDAEL_128; # Set the algorithm
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
MCRYPT_MODE_ECB), MCRYPT_RAND); # Create the Initialisation Vector
$string = mcrypt_encrypt($cipher_alg, $key,
$string, MCRYPT_MODE_CBC, $iv); # Encrypt $string and assign back to $string
?>
$string is now a binary variable, containing an encryption of the string we have created. To decrypt it, we would do the following:
<?php
$key = "PHP key"; # Set the key
$cipher_alg = MCRYPT_RIJNDAEL_128; # Set the algorithm
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
MCRYPT_MODE_ECB), MCRYPT_RAND); # Create the Initialisation Vector
$string = mcrypt_decrypt($cipher_alg, $key,
$string, MCRYPT_MODE_CBC, $iv); # Decrypt $string and assign back to $string.
?>
Where $string was our encrypted string.
And there we go - that last one is kinda confusing, and to be honest, for most uses crypt() and md5() are more than secure enough - but for thoes times you really need to be able to encrypt and decrypt secure data, mycrypt is the way to go.
For more information on mcrypt, and a more detailed discussion on the cyper algorithms etc, visit http://uk2.php.net/mcrypt
Liam Wiltshire is a web developer working in both Leeds and Swindon, UK. He specialises in PHP, and custom scripting, as well as working on his own projects. For more information, and other PHP scripts and tutorials (http://www.lsw-computing.co.uk), visit http://www.lsw-computing.co.uk
---
You may reproduce this tutorial on any site or blog, as long as the above notice stays intact.
If you want to get someone's IP address using PHP then you can use the following code:
$ip = (getenv(HTTP_X_FORWARDED_FOR))
? getenv(HTTP_X_FORWARDED_FOR)
: getenv(REMOTE_ADDR);
Spaceman3750
05-20-2007, 01:14 AM
$_SERVER['REMOTE_ADDR'] is easier ;).
Yes, but for as far as I know that doesn't always contain the real IP.
jazzer01
05-21-2007, 07:58 PM
At some point or another, you are undoubtedly going to want to send an email in PHP. There are two types of emails you can send, simple, text emails, and more complex HTML emails. Both of these use the mail() command, but in different ways.
The standard syntax and arguments for mail() are:
mail(to,subject,message,headers);
These must be formed to comply with the relevant standards (eg multiple headers must be seperated with \r\n (CRLF)
Text Emails
Sending text emails in PHP is relativly simple. All you need to do is use the above format and add in the correct variables:
<?php
$to = "liam@lsw-computing.co.uk"; # set where the email is going
$subject = "Test Email"; # Set the subject
$message = "This is a test email\nThis is a newline"; # Set the message
$headers = "From: billgates@microsoft.com"; # Set who the email is from (yes, it is that easy to spoof an email address)
mail($to,$subject,$message,$headers); #Send the email
?>
This will send a simple email to liam@lsw-computing.co.uk, supposidly from billgates@microsoft.com.
You can also use all the other standard headers, CC:, BCC: etc - just remember to seperate each one with \r\n
Thats all there is to sending a straight text email - if you are getting data from forms, remember to validate the information first, to check it is correct!
HTML emails
By PHPs own admission, if you want to send complicated emails, such as HTML, it is better to use the PEAR Package. However, there are times when such luxuries don't exist, and I've never had a problem using mail(), so I'll share it anyway.
The trick is in the headers. To send HTML emails, the Content-type header must be set to text/html; charset=iso-8859-1 (or another valid charset), and the MIME-Version should be set to 1.0 .
Your message can then use any HTML you want - but bear in mind some email clients/webmail interfaces strip some sorts of HTML/Javascript etc.
Using the example above as a starting point, a HTML formatted email might look like:
<?php
$to = "liam@lsw-computing.co.uk"; # set where the email is going
$subject = "Test Email"; # Set the subject
$message = "<b>This</b> is a <u>test</u> email<br />This is a newline <br /><hr />"; # Set the message
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1"; # Set the HTML headers
$headers = $headers . "\r\nFrom: billgates@microsoft.com"; # Set who the email is from (yes, it is that easy to spoof an email address) - remember that the . connects two strings
mail($to,$subject,$message,$headers); #Send the email
?>
This would send an email with the following formatting:
TO: liam@lsw-computing.co.uk
From: billgates@microsoft.com
Subject: Test Email
This is a test email
This is a newline
_________________________________
As I mentioned at the beginning, PHP recommends you use PEAR to send complex emails - however, I have never had a problem with mail(), so unless its mission-critical, there is no reason not to use it!!
jazzer01
05-24-2007, 12:18 PM
Database interfacing is one of the central componants in PHP. Possibly the most popular databasing software used online at the moment is mySQL, which is why this tutorial focuses on mySQL interfacing. However, alot of the functions work for other databases too - just replace the mysql bit with the name of the database software, eg. pgsql (http://us3.php.net/pgsql) for PostgreSQL, mssql (http://us3.php.net/manual/en/ref.mssql.php) or MSSQL etc..
Step 1: Connecting to the server, and selecting the DB
Before we can actually manipulate a database, we have to connect to the mySQL service, and to do this, we need to know the username, password and host of the service to connect to. The easiest way to set these is to set each one to a variable. We can then use the mysql_connect() function to connect to the service - the function takes three arguements, the hostname, the username, and the password.
The function returns a connection resource (basically, just the information about where the connection is). As long as you are only connecting to one service, you don't need to worry about this, but if you had more than one connection open, you would need to know which is which, so we will assign the resource to a variable as well.
The code looks like this:
<?php
$host = "localhost"; # The hostname
$user = "donut"; # The Username
$pass = "donut"; # The Password
$link = mysql_connect ($host, $user, $pass); # Connect to the service, and assign the connection details to $link
?>
Now we are connected to the service, we can select the database we wish to work with within the service. To do that, we use the function mysql_select_db() - a function that just takes one argument - the name of the database we are connecting to.
If you are using more than one service - then there is a second argument you need - the variable you assigned the connection to.
So now, our code looks like:
<?php
$host = "localhost"; # The hostname
$user = "donut"; # The Username
$pass = "donut"; # The Password
$link = mysql_connect ($host, $user, $pass); # Connect to the service, and assign the connection details to $link
$database = "mydatabase"; # Set the database we want to connect to
mysql_select_db($database); # select the database
?>
Step 2. Creating Tables
Once you have connected to the database you are working with, whenever you want to talk to the database, you almost always use mysql_query() this just takes one argument - the SQL query you want to run on the database. It automatically runs on the database you have selected.
As before, if you have more than one connection open, you have to use a second argment, which is the connection resource.
the SQL query to create a table is:
CREATE TABLE `customer` (`first` INT,`second` TEXT,`third` TEXT)
This would create a three column table called customer, the first column being called first with an Integer datatype, the second being called second with a text data type, and the third being called third, also with a text datatype. For more information on SQL queries and datatypes, visit http://dev.mysql.com/doc/refman/5.0/en/create-table.html
We can then put this query into out mysql_query() function in PHP:
$query = "CREATE TABLE `customer` (`first` INT,`second` TEXT,`third` TEXT)"; # write the query
mysql_query($query); # Run the query in the database
Remembering that before we can do that, we will have opened the connection and selected the database as above :)
Step 3. Inserting Into Tables
Same as before, we will be using mysql_query to run a query to insert values into the table. Using our table structure above, our query would look like:
INSERT into `customer` values ('6','Text','More Text')
This would insert a row into our table, with the values first=6, second=Text and third=More Text
As before, we just need to plug this in to our mysql_query(), and away we go:
$query = "INSERT into `customer` values ('6','Text','More Text')";
mysql_query($query);
Step 4. Getting Data out of tables
We are still using mysql_query, but this time, there is a difference. Because we are getting data out of the table, we will be getting a result - in the form of a resource which we can then format with other functions. This means we have to assign the output of the function to a variable
A basic query to get information from a database looks like this:
SELECT * from `customer`
This basically means select everything (all the columns) from the table called customer. You can expand this by adding WHERE clauses, so filtering what you get, by putting the results in order, by replacing * with the names of the columns you want, and more. For more information on this, visit http://dev.mysql.com/doc/refman/5.0/en/select.html.
Remember, we need to assign the output to a variable. A commonly used variable is $result:
$query = "SELECT * from `customer`"; # Set the query
$result = mysql_query($query); # Assign the output to $result
Formatting your output
Once we have run the query, we can format the output - at the moment you only have a result resource, if you tried printing it, would would get much information from it. There are a few many functions we can use to get the actual results:
mysql_num_rows() will return the number of rows that were returned in the result. It just takes one argument, which is the result from the query.
mysql_fetch_array() will create an array of the next row in the results - the keys in the array will be the column names. Each time you run this query, the next row is returned - we can use a while() loop to fetch each row and process it one at a time. Again, just takes the single result argument.
Therfore, using all this, a full script that connects, creates a table, inserts values and prints out values would look like:
<?php
host = "localhost"; # The hostname
$user = "donut"; # The Username
$pass = "donut"; # The Password
$link = mysql_connect ($host, $user, $pass); # Connect to the service, and assign the connection details to $link
$database = "mydatabase"; # Set the database we want to connect to
mysql_select_db($database); # select the database
#CREATE TABLE
$query = "CREATE TABLE `customer` (`first` INT,`second` TEXT,`third` TEXT)"; # write the query
mysql_query($query); # Run the query in the database
#INSERT VALUES
$query = "INSERT into `customer` values ('6','Text','More Text')";
mysql_query($query);
$query = "INSERT into `customer` values ('1','Some Text','Some More Text')";
mysql_query($query);
#GET RESULTS
$query = "SELECT * from `customer`"; # Set the query
$result = mysql_query($query); # Assign the output to $result
$count = mysql_num_rows($result); # Assign the number of rows returned to $count
print "Number of Rows: $count"; # Print out number of rows
while ($row = mysql_fetch_array($result)){ # Loop round all the result rows one at a time, creating an array of the results, and assigning it to $row, then perform the following:
print "<br />First: $row[first], "; #Print out the value of column first
print "Second: $row[second], "; #Print out the value of column second
print "Third: $row[third], "; #Print out the value of column third
}#Go back to top of loop, select the next row, and print again
?>
As we have inserted two rows into out table, the above script would output the following:
----
Number Of Rows: 2
First: 6, Second: Text, Third: More Text
First: 1, Second: Some Text, Third: Some More Text
And thats all you need to know! There are other, more advanced functions that you may need later. To see all the mysql functions available, visit http://us3.php.net/manual/en/ref.mysql.php
RichardKnox
05-27-2007, 04:09 PM
Some nice tutorials here. Once I get the time, and/or motivation, i'll be sure to post some :)
For now:
CREATING A FUNCTION
For the sake of this, we shall create a basic function to clean input
<?php
function clean($input) { //Defines the function name and the variables to be used
$clean = htmlspecialchars(mysql_escape_string($input)); //Cleans the input of any HTML and MySQL
} //Closes the function
?>
So thats all fine and dandy, but at the moment its not cleaning input. So if we add this code to the bottom of it:
$username = "<html><a href=\"http://developlive.com\"></a></html>"; //Defines the variable username
clean("$username"); //Cleans the variable username, as defined above
This function would now clean username of any MySQL and HTML there is in it.
Hope this helps :)
Smithers
06-27-2007, 07:26 AM
Any video tutorials out there?
vBulletin® v3.6.5, Copyright ©2000-2012, Jelsoft Enterprises Ltd.