All times are UTC




Post new topic Reply to topic  [ 1 post ] 
  Print view

PHP Tutorial 1 : The Basics
Author Message
PostPosted: Wed Dec 24, 2008 3:25 pm 
Offline
Site Admin

Joined: Tue Sep 09, 2008 5:29 pm
Posts: 52
This is the first in a series of PHP tutorials aimed at teaching beginners to the language the basics and hopefully answering some of the common beginner questions.

What is PHP and how does it work?

PHP is a scripting language aimed primarily at webpage development. It allows websites to becomes interactive and for webmasters to store and display data from a database as well as dynamically generating content and layouts.

PHP is a top to bottom scripting language meaning that execution of commands within the scripts happens as it is read. For example if you want something to be executed first or on page load then you put it at the very top of the script. If you want something to happen last then you put it at the very bottom of the script.

PHP can be both a functional language and an OOP language.
In this series of tutorials we will only be focusing on the standard functional method of doing things OOP in php is still immature (at least in my opinion) and can massively overcomplicate simple tasks. Whilst there are some advantages to using OO for 90% of the standard day to day websites it is unnessary.

Goals of this Tutorial

The goals of this tutorial are to teach you the basics for handling user input data and demonstrate the basic structure of a PHP page.
In this tutorial we assume you have a working PHP capable web server to test your scripts on. If you are on windows we recommend WAMP Server http://www.wampserver.com/en/ if you are using a Linux based machine then a standard install of Apache and PHP will suffice.

Step 1 setting up your HTML form
1) Create a new text file called index.php within your web directory
2) Create the basic HTML Layout using the code below.
Code:
<html>
<head><title>PHP Tutorial 1</title></head>
<body>
</body>
</html>

3) Now you have your basic HTML file its time to add a form into the page to allow you to accept user inputs. You can use the code below for your form.
Please note that we are using the form method POST. We do this as using a GET method form creates some issues such as a GET header can only store a limited amount of data so a long data input by a user becomes truncated. GET forms are considerably easier for the nerfarious type of user to input corrupted data into your site. Whilst this isn't a major issue in this example when you begin working with databases later on in this series it can cause you issues. The Rule of thumb is ALWAYS use a POST form.
Code:
<p>
<form action="index.php" method="post">
<input type="text" name="userinput" id="userinput" />
<input type="submit" name="action" id="action" value="Submit Form" />
</form>
</p>


If you look closely at the form code above you'll notice a few other things about it. First up the form action is set to the script its self rather than to a separate page. Whilst you could have the form posting to a different page all together with the power of PHP this is not required as we can use PHP to identify if it needs to process any actions or if it should just render the default page.
This is coupled with the submit button being called action as you will see later on in this tutorial.

You should now have your basic HTML file setup with a form this image shows you the code so far and what it should look like when you open that up in your web browser.
Image

Step 2 making it do something interesting

Now we have our form and basic layout but it doesn't do anything at the moment so lets now start adding in some php to make it do something.

First things first remember ALL PHP code has to be enclosed in the following opening and closing tags without these tags the PHP processing engine doesn't know what to do with what you've typed.
The opening PHP tag is
Code:
<?php
the closing PHP tag is
Code:
?>
Take not that the opener is all in lower case this is important as upper case will not work.

Because we used a POST style form with PHP we need to use the $_POST variable.

PHP allows other types of variable retrieval the primary ones you will use are:
$_GET this allows retrieval of information from a query string there will be examples of using a GET in the next tutorial.
$_COOKIE this allows for retrieval of a cookie stored on the users machine this is used in conjunction with the function setcookie() which we will address in a later tutorial.
$_SESSION this allows for retrieval of a session stored on the server. Sessions are the server side equivilent of a cookie however are a little bit more complex to work with. There will be a tutorial dedicated to sessions later in this series.

The next step is to add in some PHP to our HTML template. For now we are simply going to write out the information submitted by the user to the page. In later tutorials we'll see how to process this data and eventually store it within a database.

1) We want the inputted data to be displayed just above the input boxes so to do this our PHP code has to go above our form HTML code. Start by creating your open and close PHP tags above your HTML form. Your page should now contain code that looks like the following.
Code:
<html>
<head><title>PHP Tutorial 1</title></head>
<body>
<?php
//We will use PHP to do stuff here
?>
<p>
<form action="index.php" method="post">
<input type="text" name="userinput" id="userinput" />
<input type="submit" name="action" id="action" value="Submit Form" />
</form>
</p>
</body>
</html>


Note the line within the PHP tags with // at the start. // means this line is commented out and will not be processed. This is handy for you to document your code in code on small pages like this its not really essential however once you start working on larger sites and projects it becomes vital that you document your code every step of the way else maintenance of the code will become near impossible for you and completely impossible for others looking in.

2) As mentioned above we're going to use PHP to make the page detect if the form was submitted or not. To do this we will need the $_POST variable mentioned above, an if() statment and the value of the submit button. What we are going to do is a quick check to see if the form has been submitted. Now if you look around the web there are loads of different ways of achieving this the method I use in this tutorial is my personal favourite as its simple and exact. As you develop your skills you may well choose a different method but for now we'll use this.

Below your PHP comment line we're going to add in our if statement. If statements are page logic statments they allow you to check if something is true or not true and then direct your script to respond accordingly. In our case we are going to check if the value of our submit button is "Submit Form" pay special note to the case sensitivity PHP is a case sensitive language for input values when you are doing string comparisons.

Add the following below your comment line (the line starting with //)
Code:
if ($_POST['action']=="Submit Form") {
// spit out the input
}

I'll try to explain this a little now.
A standard if statement takes the form if (expression) { action } the expression within the () will always return either a true or a false to its if.
In our example above we are retrieving the contents of the submit buttons value. If you remember we called our submit button action. Using the $_POST variable we retrieve the contents of our submit button. In our case we set the value= of our submit to be "Submit Form" so what our if statement is really doing now is "Submit Form"=="Submit Form"
In PHP there are many Boolean operators in our case we are using the == operator this means is equal to (more on these later). So our if statement is now doing the following:
if "Submit Form" is equal to "Submit Form" then do something end if

3) Now for the easy part we want to write out what was input to the screen. To write out a basic string to a webpage the most common method is to use the command echo

echo is a built in function of PHP and is very smart indeed. It can write out a plain string to the page, it can write out variables to the page, and it can even detect variables within strings and replace those variables with their correct value. Here's how we implement the echo within our current code.

Between those curly brackets of the if statement { } we want to put our echo code so for starters we're going to echo out a fixed string.

Code:
echo "User submitted: " ;


Notice for the first time we've appended a semi-colon onto the end of the command. This isn't a typo in PHP all command lines need a ; on the end of them. if/while/for each statements however do not require a ; as they use the curly brackets to specify their container start and end.

Our overall code should now look like this.
Code:
<html>
<head><title>PHP Tutorial 1</title></head>
<body>
<?php
//We will use PHP to do stuff here
if ($_POST['action']=="Submit Form") {
// spit out the input
echo "User submitted: " ;
}
?>
<p>
<form action="index.php" method="post">
<input type="text" name="userinput" id="userinput" />
<input type="submit" name="action" id="action" value="Submit Form" />
</form>
</p>
</body>
</html>

Go ahead and run it in your web browser see what happens. You should see something that looks a little like this.
Image

4) We're not yet writing out what the user submitted to do that we must first store the submitted data into a local variable. Whilst for this tutorial it isn't essential it is good practice for later on. Add a new line above the echo command and insert the following
Code:
$userinput = $_POST['userinput'];

Here we are using a single equals to not a double equals this means we want to set the value of $userinput to be the value of the form field userinput. Again we are using the $_POST command and again we have the semi-colon on the end of the command line.

5) Now we want to write out contents of our new variable $userinput to the screen. Go back to your echo command and change it to say the following.
Code:
echo "User submitted: $userinput" ;

echo being a smart function detects that we have put a variable within our echo string now and it goes into your code and pulls out the value of that variable. Since we set the variable earlier on it will now add what the user initally input on our form to the page.

Your overall code should now look like this
Code:
<html>
<head><title>PHP Tutorial 1</title></head>
<body>
<?php
//We will use PHP to do stuff here
if ($_POST['action']=="Submit Form") {
// spit out the input
$userinput = $_POST['userinput'];
echo "User submitted: $userinput" ;
}
?>
<p>
<form action="lesson1.php" method="post">
<input type="text" name="userinput" id="userinput" />
<input type="submit" name="action" id="action" value="Submit Form" />
</form>
</p>
</body>
</html>

And it should look like this in a web browser
Image

Thats it for the very basics of handling user inputs with PHP. Now you should be able to create your own forms and write the results out to the page.

Here are a few additional little tasks you can try yourself:

1) Submitting a form with multiple inputs and echoing out the different inputs.
2) Highlight the user input on your echo in bold and red.

_________________
CDOSYS & CDONTS auto detecting mail function: Mail Function
500.100.asp debug page: Debug Script


Top
 Profile E-mail  
 

Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron