Learn PHP

Learn PHP

It’s really not hard, here are the best methods to learn PHP from my personal experience…

So you’re wanting to learn PHP? That’s an excellent choice if you plan on using it for web development! From my experience freelancing, PHP seems to be to top programming languages people hire for. Lucky for you, PHP isn’t that difficult to learn – it’s actually extremely simple. I probably shouldn’t get peoples hopes up, learning PHP may come much easier to some then others depending on how logical you are.

How to learn PHP?

The best way to learn a programming language – or anything for that matter- is actually practicing with it! You are absolutely not going to get far if you simply just read tutorials. After you read a tutorial you need to take what you learned and actually apply it. Just think of a simple script you could program that can be done with what you just learned. It can be something as simple as creating a form that prints out what the person typed in. Don’t start trying to program a full-blown login system for your first project, you will fail – miserably.

There are many different ways you can learn PHP. I would recommend going to your local library or bookstore and getting a moderately recent book on it. Read the first few chapters that introduce you to all the basics and try to wrap your head around it. The first steps you will take to learn PHP will probably be the hardest, you will have to learn the syntax and understand when to use everything. I remember when I first wanted to learn PHP, I gave up multiple times because I was so confused in the first few chapters. After being determined I finally started catching on and understanding, it just takes time and patience.

After you have gone through the first few chapters of a book and have the syntax and very basics down it’s now time to put the book down and go online. Search for websites such as www.w3schools.com/php that will help you learn PHP with tutorials. Now go through these tutorials and actually DO what they are explaining and testing everything for yourself. Once you do this light bulbs will start going off in your head and you will start to grasp the language.

PHP: Step By Step User Registration Script

I am going to walk you through coding a simple user registration feature from the ground up.

Step 1

Putting together the database

The first step is to build the database and get it ready to start being populated by information from the registration script.

Database Fields
Table Name: users

  • userID – varcher(8) – Primary Key – Auto Increment
  • username – varcher(25)
  • password – varcher(16)
  • email – varcher(80)

Step 2

Setting up the registration form

Now that the database is all in place, we need to set up the form users will fill out in order to register for the website. This will be in simple HTML, of course you are welcome to pretty it up using CSS and images.

1
2
3
4
5
6
7
8
9
<form method="post">
 
   Username: <input type="text" name="username" /><br />
   Password: <input type="password" name="pass1" /><br />
   Verify Password: <input type="password" name="pass2" /><br />
   Email: <input type="text" name="email" /><br />
   <input type="submit" value="Register" name="register">
 
</form>

Step 3

Error Checking the users information

Now the user is ready to enter their information into the form. It is extremely important that you always do error checking on user inputted values. You need to make sure the information is what you are expecting – For example, if they supply an email you want to make sure it’s in the correct format before allowing them to register.

When I’m error checking, I like to use an array to store each possible error they encounter. That way at the very end I can loop through and display each error to them with ease.

I can’t stress enough how important it is to use the mysql_real_escape_string() function on ALL variables before they are put in the database. This protects you from MySQL injections that can literally wipe clean your entire database. Why there are people in the world that would do that? Beats me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
 
//check if they submit the form
if (isset($_POST['register'])){
 
	//get all the values from the form
	$username = mysql_real_escape_string($_POST['username']);
	$pass1 = mysql_real_escape_string($_POST['pass1']);
	$pass2 = mysql_real_escape_string($_POST['pass2']);
	$email = mysql_real_escape_string($_POST['email']);
 
	// #### ERROR CHECK ####
 
	//Create array to catch errors
	$errors = array();
 
	//make sure they didn't leave any blank	
	if ($username == "" || $pass1 == "" || $pass2 == "" || $email == "")
		$errors[] = "You must fill out all fields";
 
	//make sure the passwords match
	if ($pass1 != $pass2)
		$errors[] = "Your passwords don't match!";
 
	//Make sure the email is valid
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $this->email))
		$errors[] = "The supplied email address is not valid";
 
	//If there are errors, display them. If not, put information in database
	if (!empty($errors)){
 
		//display errors using foreach loop
		echo '<h2>Errors:</h2>';
		echo '<ul>';
 
		foreach ($errors as $error){
 
			echo "<li>$error</li>";
 
		}
 
		echo '</ul><br><br>';
 
	} else {
 
		//There were no errors, put information in database
 
	}
 
}
 
?>

Step 4

Inserting their information into the database

Now all we need to do is insert their information in the database – assuming they didn’t get any errors. In order to do this you of course must have a connection to your database established. So make sure to include your external config file, or add the connection code.

When inserting the password into the database, we are going to use the function md5() which will encrypt their password. This is important because if someone hacked into your database, they would be unable to get the persons actual password and be presented with a random string of numbers and letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
 
//There were no errors, put information in database
 
$query = "INSERT INTO users (username, password, email)
			VALUES ('$username', '".md5($password)."', '$email')";
 
$result = mysql_query($query)or die(mysql_error());
 
//give them a success message
echo "<font color='green'>Successfully Registered!</font><br><br>";
 
?>

Conclusion

Your users are now ready to sign up for your website! Of course now all you’re missing is a script to allow them to log in (that tutorial will be coming very soon!).

Full Register Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
 
//check if they submit the form
if (isset($_POST['register'])){
 
	//get all the values from the form
	$username = mysql_real_escape_string($_POST['username']);
	$pass1 = mysql_real_escape_string($_POST['pass1']);
	$pass2 = mysql_real_escape_string($_POST['pass2']);
	$email = mysql_real_escape_string($_POST['email']);
 
	// #### ERROR CHECK ####
 
	//Create array to catch errors
	$errors = array();
 
	//make sure they didn't leave any blank	
	if ($username == "" || $pass1 == "" || $pass2 == "" || $email == "")
		$errors[] = "You must fill out all fields";
 
	//make sure the passwords match
	if ($pass1 != $pass2)
		$errors[] = "Your passwords don't match!";
 
	//Make sure the email is valid
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $this->email))
		$errors[] = "The supplied email address is not valid";
 
	//If there are errors, display them. If not, put information in database
	if (!empty($errors)){
 
		//display errors using foreach loop
		echo '<h2>Errors:</h2>';
		echo '<ul>';
 
		foreach ($errors as $error){
 
			echo "<li>$error</li>";
 
		}
 
		echo '</ul><br><br>';
 
	} else {
 
	  //There were no errors, put information in database
 
	  $query = "INSERT INTO users (username, password, email)
				  VALUES ('$username', '".md5($password)."', '$email')";
 
	  $result = mysql_query($query)or die(mysql_error());
 
	  //give them a success message
	  echo "<font color='green'>Successfully Registered!</font><br><br>";
 
	}
 
}
 
?>
 
<form method="post">
 
   Username: <input type="text" name="username" value="<?php echo $_POST['username']; ?>" /><br />
   Password: <input type="password" name="pass1" /><br />
   Verify Password: <input type="password" name="pass2" /><br />
   Email: <input type="text" name="email" value="<?php echo $_POST['email']; ?>" /><br />
   <input type="submit" value="Register" name="register">
 
</form>

About PHP

About PHP

What is PHP?

The official PHP website defines PHP as -

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym.

Here is a little more detail about php.

PHP is a server side programming language. It’s primarily used for the back-end functionality of a website. For example, when you are logging in to a website PHP is the language that checks the information is correct in the database (along with MySQL) and determines what happens depending on if your log in credentials were correct or not. PHP is unable to update parts of a page without a refresh, unlike languages such as JavaScript and AJAX. Of course you can combine PHP with these client-side languages to get your desired result.

Who Should learn PHP?
Anyone with a desire to create dynamic websites should learn about PHP. PHP is an extremely powerful language and can do just about anything you can think of on the Internet.

Why learn PHP?
There are many reasons to learn PHP if you are interested in web development. First off, it’s free and comes with just about every hosting package out there. It’s also extremely easy to learn. I highly recommend PHP if you are new to programming, it will teach you all the concepts that are fundamental to other programming languages. PHP is the dominant language when it comes to web development, and it works great with other programming languages. Basically you can’t go wrong with PHP when it comes to the internet.

PHP GET: Using GET with PHP

What is GET?

The GET method is used when getting information from a URL. You can use a URL to store information for many different purposes. You can store a users ID number in order to retrieve their profile information, or another common use for PHP GET is for forms.

Take this URL for example

www.your-website.com/profile.php?userID=43

At the end of the URL you will notice there is a userID=43. You can now use PHP to get that data from the URL.

<?php
 
   //grab the users ID from the URL
   $userID = $_GET['userID'];
 
   echo $userID; //displays 43
 
?>

When using PHP GET, just remember to use the same name you used in your form for whatever value you want.

$_GET['form_input_name'];

PHP GET With Forms

A very common use for using GET is when dealing with forms. Lets say we want to have a form that asks for a users name and gender. Once they submit it we will extract the information from the URL and display everything for them.

Here is the code for the form -

<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="gender" />
<input type="submit" />
</form>

Once they click the submit button, they will be taken to a page with a URL that looks like this:

http://www.your-site.com/welcome.php?name=Sam&gender=male

As you can see, both the name and gender fields show up on the URL according to what they typed in.

Now lets see what the script looks like to extract and display the information

<?php
 
   //get their name and gender from the URL
   $name = $_GET['name'];
   $gender = $_GET['gender'];
 
   //Now display the information
   echo "Name: $name \n";
   echo "Gender: $gender \n";
 
?>

Important Note!
You should NEVER use php get to pass confidential or sensitive information such as passwords!

You also shouldn’t use php get with large amounts of information. If the values are going to exceed 2,000 chars then you should use POST instead.

Using HTML in PHP

Using HTML in a PHP script is extremely simple.  There are numerous different ways you can go about putting HTML inside your PHP script. I will walk you through each way of doing it with some code examples.

Before you start make sure you’re working in a file with a .php extension

Method 1 for using HTML in PHP

The first method is simply to put the HTML outside of the PHP opening and closing tags. This method comes in handy when you have a lot of HTML without needing any PHP.

1
2
3
4
5
6
7
<?php 
 
//php code here 
 
?> //exit out of PHP by using the closing tag
 
<strong><b>Here is some HTML code</b></strong>

As you can see I only used HTML outside of the <?php and ?> tags.

Method 2 for using HTML in PHP

Another way to use HTML in PHP is to put the HTML inside of the PHP print or echo statement. This is useful when you only have a small amount of HTML to output.

1
2
3
4
5
6
<?php
 
echo "I can put the HTML <em>inside</em> of an echo or print";
print "<strong>I can put the HTML <em>inside</em> of an echo or print</strong>";
 
?>

Method 3 for using HTML in PHP

The last method is using the Heredoc syntax. This allows you to put a large amount of text and/or HTML within PHP.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
print<<<HERE
 
   <b>You can put all your text and HTML here</b>
   <strong>It can be on
 
   multiple lines</strong>
 
HERE;
 
?>

One thing to note about using the Herdoc syntax is the last line which ends the Herdoc MUST have no spaces in front of it. So the “HERE;” must be all the way to the left of the editor or else you will receive an error on the page.

As you can see using HTML in PHP is rather easy. If you have any issues, don’t hesitate to leave a comment!