PDA

View Full Version : [TUT][PHP] Getting started with PHP



I3rap
12-07-2007, 06:13 PM
I posted this here as it wont let me post in the correct section. Propz toPhantomfrom CC Community (No links allowed, breaks rules)

PHP, which stands for PHP: Hypertext Preprocessor, is one of the most used programming languages of the web. In fact it's so powerful and effective that even Yahoo! uses it! It is used to create dynamics within your web documents. PHP can do much more than web dynamics, but let's just start with that

Why should I use PHP? What's wrong with HTML?

Nothing is wrong with HTML. In fact, PHP will be outputting HTML most of the time. PHP simply makes the HTML change under certan circumstances, in addition to other things. This simply makes your web documents more interactive for your visitors.

What will I need?

In order to even use PHP, you will need a web host that supports it. Unfortunately, most free web hosts do not support PHP which makes learning PHP more difficult. Additionally, you will need to know how to upload files to the host so that it can access your PHP document.

Aside from that, the only major requirement is Notepad, Wordpad, or some program that can write text to files. There are also free programs such as PHP Designer 2006 that will color-coat your code as you type it which makes mistakes more noticable. If you're serious about learning and using PHP, I highly recommend you download such a program.

How is a blank notepad going to help me program?

All PHP programming is done in some form of a notepad. PHP programming is basically typing text into a document in a way that can be understood by the server. I'm afraid there are no special programs that make this any easier.

With that being said, let's make a PHP document!

The first thing you type when starting PHP is what's called a PHP tag. It tells the host that you will be using PHP from that point foward until you use the closing PHP tag.

The php tags look like so:



Code:

<?php

Code:

?>


At all times, the opening tag will be found at the beginning of your PHP and the closing tag will be found at the end.

Code:

<?php YOUR CODE HERE ?>

Output text with your PHP document

There are two special language constructs, or functions, that are used to output data: echo and print. Generally, they are both the same thing so it is up to you which one to use. In this tutorial, I will be using echo as it is the more commonly used function between the two.

This is how you would output text (don't forget the tags!)

Code:

<?php echo "This text will be sent to the user!"; ?>

When someone accesses your PHP document via an internet browser, they will see This text will be sent to the user!

There are two things I introduced with the above line of code. One would be how I put quotes around the text that is to be outputted. The text inside the quotes is called a string. A string is defined as a series of characters. Additionally, you can use either single quotes (') or double quotes (") to indicate a string. In other words, with the above example I could also have done this:

Code:

<?php echo 'This text will be sent to the user!'; ?>

Do realize that there is a difference when using single or double quotes, which I will explain later.

The second thing introduced is the semicolon (. A semicolon indicates the end. After each function and variable declaration comes a semicolon to indicate that you are done with the function/variable you are dealing with. In this case, a semicolon is used after the string to indicate that I am done with the echo function. If I wanted to, I could begin using a different function because PHP knows that I am no longer outputting any text with that particular echo function. You can also think of the semicolon as a separator.

Another great thing is you can also start with some HTML and begin PHP in the middle of your HTML! Like this:

Code:

<html><head><title>PHP!</title></head><body><?php echo "This text will be sent to the user!"; ?></body></html>

As long as you surround your PHP code with the PHP tags, it will work perfectly!

Please note that PHP will only work inside a document that has the extension php. Otherwise, the PHP code will be shown to the user who tries to access the page.

What if I need a quote inside my message?

In some cases, you may need to use the same quote inside your message as you did to begin the string.

Code:

echo 'This isn't going to work';

PHP will consider the single quote in isn't as the end of the line thus you will receive an error. One solution may be to simply switch the opening and closing quote so it doesn't match the one you need to use, but that will only work for some situations.

By simply placing a backslashes \ before the quote, PHP will ignore it as being the end of the line and instead consider it as part of the string.

Code:

echo 'This isn\'t going to work';

The above line works perfectly since PHP knows the quote in isn't is not the end of the line due to the backslash. It will instead consider the quote after work as the end of the line.

Variables

A variable is defined as something that changes. In PHP, variables are identified by using the dollar sign $ with the name of the variable following it. $var is an example of a variable and var is the name of that variable.

All variables are accessed and set the same way. The only difference is the name you give them which is the string you use after the dollar sign.

One thing you cannot do is begin a variable with a number (e.x. $1var ). PHP simply does not allow that and an error will be shown when you access the document. However, you can use numbers elsewhere in your variable in addition to underscores.

Setting a variable

First of all, there are seven kinds of variables. Five of these kinds are basic and will be covered in this tutorial. The other two, however, are more complex and will not be introduced.

The types are as follows:
boolean - A variable is either set to TRUE or FALSE. You can consider this as also a YES or NO variable (TRUE for YES and FALSE for NO) but those values are not permitted. We will be using either TRUE or FALSE at all times.
integer - A number with no decimals or alpha characters.
float (or double) - A number with decimals but no alpha characters.
string - A series of numbers, letters, or symbols.
array - A variable with a series of variables inside of it
object (will not be introduced) - Similar to array but with different syntax.
resource (will not be introduced) - Typically created with a function, a resource variable is used to point certain functions toward an external source. For example, when writing to a file, a resource will be created so the functions know which file to write to.
A variable is declared like so:

$var_name = "This is a variable! It's name is var_name";

It is very similar to outputting the string except you use the equal to = sign to indicate you are declaring the variable.

Notice that I again used quotes to surround the string and a semicolon at the end to indicate I am done declaring the variable.

You can now access this variable throughout the rest of your script.

Code:

<?php$var_name = "This is a variable! It's name is var_name";echo $var_name;?>

Can you make any predictions as to what this will do? Quite simply, it will output This is a variable! It's name is var_name since that is the value of $var_name.

You will only want to use quotes when dealing with strings. Integers, floats, and boolean values do not use quotes.

For example, this is how you would declare a boolean variable:

Code:

$i_am_hungry = FALSE;

Boolean typically isn't used for outputting but is used for if-else statements which will be covered later.

You can put quotes around the FALSE part if you wanted but $i_am_hungry would instead be a string and not a boolean value. You will learn why that is important when if-else statements are introduced.

In regards to the boolean itself, it is case insensitive. Meaning you can do this:

Code:

$i_am_hungry = false;

and get the same result. The variables, however, are case sensitive.

Arrays

Arrays are variables with even more variables inside them. They look like so:

Code:

$array['value']

With an array, you access one of it's values by immediately following the variable name with a [ followed by the name of the variable inside the variable (can be an integer or string) followed by a ]. Other than that, they behave exactly like variables and can be set exactly like variables.

Except with an array, the name of the variable is not called the name but actually a key. In the above example, value is a key of the array.

Code:

$array['one'] = "This is a string inside an array!";
$array['two'] = 6;

Again, one would be one key within the array and so would two. The values of these keys are still called values.

Arrays can be defined also with the array function. You use it just like a typical function except it has it's own unique syntax.

Code:

$array = array( 'one' => "This is a string inside an array",
'two' => 6 );

You declare one array key and it's value by inputting the key followed by => followed by it's value. Each new key and value are separated with a comma as if adding a new key/value are arguments.

Like variables, an array's values can be string, integer, float, boolean, etc. and you access a particular key's value like so:

Code:

echo $array['value']

If you were to do this:

Code:

echo $array;

The output would be Array as the variable is in fact an array.

Functions

There are over 700 predefined PHP functions you can use to enhance your document even further. Since there are so many, I will only introduce some helpful ones with learning PHP.

Functions in PHP are strings immediately followed by an opening parenthesis followed by the arguments of the function followed by a closing parenthesis. Arguments are variables or variable-types (strings, integers, etc.) in between the parenthesis that are to be considered when doing the function. They are often separated with commas.

That may be confusing but some examples will most likely help.

I will first introduce the var_dump function which will output details about a variable.

Code:

<?php$ourvar = "This is a string";var_dump( $ourvar );?>

This will output string(16) "This is a string". This function begins by outputting the variable type. For strings, it then outputs the length of the string (number of characters) in parenthesis followed by the string. For anything else, it will print the variable's value inside the parenthesis and nothing more.

Some functions return certain results depending on the values put into them. number_format for example expects one variable that is an integer and will return a string that has it formatted. In other words, integer value 55670 will return as string 55,670.

To capture the value returned from the function, you do the same thing for declaring variables except you use the function instead of the value you want the variable to be.

Code:

$format = number_format( 55670 );

$format will then turn into a string 55,670. If you use var_dump on $format, you get this:

Code:

string(6) "55,670"

The number_format function also has some optional arguments you can use. For instance, the second argument is the number of decimals you want your result to have. As stated earlier, each argument is separated with a comma. You would tell the function you want two decimal places in the result like so:

Code:

$format = number_format( 55670, 2 );

Using var_dump on $format will return this:

Code:

string(9) "55,670.00"

Just an additional piece of information about the number_format function, if the number inserted in the first argument is a float with more than the number of decimals specified in the second argument, the function will round your number so it has the number of decimals in the second argument. If argument two is left empty, this function will simply round the number which will result in no decimals.

Each function has it's own number of arguments required. Some don't even need arguments. There are also optional arguments where if they're not specified in the function they will have a default value. In regards to the number_format function, the second argument is optional and set to integer 0 by default, thus the reason why the function doesn't include decimals in the result even if a float is provided in the function.

There are actually 4 possible arguments with this function

If-Else Statements

If-Else statements are used for conditions. It is PHP's way of saying If something is true then this will happen or else this will happen.

In PHP, the syntax of an if-else statement is like so:

Code:

if ( something is true ){ then this will happen or}else{ this will happen}

Brackets { } are used to surround the code after the statement to indicate which part of the code to do if the statement is true or false. Inside the parenthesis after the if statement is where the condition is set. If the condition you use is true then the code inside the first pair of brackets will be evaluated. Otherwise, the code in the second pair of brackets will be evaluated. Never will both codes be evaluated since the case cannot be true for both.

Here is an example:

Code:

if ( 1 == 1 ){ echo "One is equal to one!";}else{ echo "One is not equal to one!";}

Obviously, since one is always equal to one, the script will always output One is equal to one!.

Notice I used two equal signs instead of one. If you only use one, you will receive a PHP error. Using two compares their values, like in the above example if 1 is equal to 1. Using three === not only checks their values but checks to see if their variable type is the same as well. if ( 1 === '1' ) will return false since the first one is an integer and the second one is a string. If this is confusing, just use two equal signs as three are seldomly needed.

Code:

if ( 1 == 2 ){ echo "One is equal to two!";}else{ echo "One is not equal to two!";}

This code will always output One is not equal to two! since one is obviously not equal to two.

You can even use variables in the condition.

Code:

$var1 = 1;$var2 = 2;if ( $var1 == $var2 ){ echo "var1 is equal to var2!";}else{ echo "var1 is not equal to var2!";}

This if statement is exactly like the one above since it's seeing if integer 1 is equal to integer 2. Because it is not, the echo after the else statement will be evaluated thus var1 is not equal to var2! will always be outputted.

To determine if two values are not equal, you will use an exclamation mark followed by an equal to sign to signify not equal to.

Code:

$var1 = 1;$var2 = 2;if ( $var1 != $var2 ){ echo "var1 is not equal to var2!";}else{ echo "var1 is equal to var2!";}

Because $var1 is not equal to $var2, var1 is not equal to var1 will always be the result.

Comparing two things at once

With an if statement, you can check not one but an unlimited amount of conditions by using the AND and/or OR statement for your conditions.

Code:

$var1 = 1;$var2 = 2;if ( $var1 == 1 AND $var2 == 2 ){ echo "Both variables are equal";}else{ echo "Both variables are not equal!";}

Because $var1 is in fact equal to integer 1 and $var2 is indeed equal to integer 2, Both variables are equal! will be the outputted result.

You can also use the OR statement. The difference between AND and OR is either the condition to the left or the right could be true for the first echo to be evaluated.

Code:

$var1 = 1;$var2 = 2;if ( $var1 == 1 OR $var2 == 3 ){ echo "One or both of the variables are equal!";}else{ echo "Both of the variables are not equal!";}

Because $var1 is equal to integer one, One or both of the variables are equal! will be outputted despite the second condition being false since $var2, who's integer value is 2, is not equal to integer 3. However, if you were to instead us the AND statement, Both of the variables are not equal! would be the output since both conditions must be true in order for the first echo to be evaluated.

You can also use the left arrow < and/or the right arrow > to determine if one integer is less than or greater than another.

Code:

if ( 1 < 2 )

This if statement will be true thus any code within the first pair of brackets will be evaluated.

Code:

if ( 2 < 2 )

This if statement will be false since 2 is not less than itself but actually equal to, thus the code within the second pair of brackets will be evaluated and any code inside the first pair will be ignored.

You can also do this:

Code:

if ( 2 <= 2 )

to determine if the integers are less than or equal to each other. Because two is in fact equal to itself, this if statement will be true.

If you want to see if the first number is greater than or equal to, you may expect to do => but you instead have to do >= since => is used for declaring array keys and values as explained earlier in this tutorial.

Code:

if ( 3 >= 2 AND 2 >= 2 )

This if statement will be true since three is greater than two and two is equal to itself.

Simplifying If-Else statements

There are ways to checking if a variable exists, is set to TRUE or FALSE, is empty, and a few other ways by simply providing the variable in the condition and nothing more.

Code:

if ( $var )

If $var is true, the if statement will return true thus the code within the first set of brackets will be evaluated. If false, the code within the second pair will be evaulated.

If $var exists, the if statement returns true.

If $var is not a string with 0 characters, the if statement will return true.

If $var is a number or string that isn't 0, the if statement will return true.

And like before, you can check two variables at once by using the AND statement.

Code:

if ( $var1 AND $var2 )

This will check the same as above except for both variables. Remember you can also use OR for the if statement to return true if only one of the variables match the above.

Using Functions in If-Else statements

Functions can also be used inside if-else statements since some return either boolean TRUE or boolean FALSE.

Code:

$string = "Is there a dash in this string?";if ( strpos( $string, '?' ) ){ echo "A question mark has been found!";}else{ echo "A question mark was not found!";}

The strpos function will check the variable in the first function for the value of the second argument. If it is found, the function will return an integer which will be the position the character is inside the string. Otherwise, the function will return boolean FALSE.

In the above example, strpos is searching $string for a ?. Because there is one, integer 30 will be the number returned as that is it's position within the string. Because the if statement sees that there is a number, it returns true and evaluates echo "A question mark has been found!";.

There is one flaw in the above code that I do not expect any beginners to see. What if the character the function is searching for is at the very beginning? PHP does not begin at 1 when counting numbers, but at 0; thus 0 will be the value returned by the function. Because if statements see 0 as false, the code within the brackets after else will be evaluated even if the character exists.

To rectify that, you will want to do this:

Code:

if ( FALSE !== strpos( $string, '?' ) )

The above statement says If the function does not return FALSE then a character must have been found so the code within the first set of brackets will be evaluated. You will also need to use two equation marks instead of one as only using one would be If the function does not return FALSE, integer 0, a string with 0 characters, or NULL then a character must have been found so the code within the first set of brackets will be evaluated. This is one of those rare moments when using either one or two equation marks makes a difference.

If you understood the flaw and how it is rectified, you have passed this tutorial and my class if you were my student

Predefined Variables

There are eight variables already defined by PHP. They are $_POST, $_GET, $_SERVER, $_ENV, $_FILES, $_SESSION, $_COOKIE, $GLOBALS. $_POST and $_GET along with their unique functionability will be covered in this tutorial.

$_POST is used when a form is submitted and the action attribute is pointed toward your PHP document.

Code:

<form action="my_script.php" method="post">

All values within the form will be put into the $_POST variable. For example, if there was a textfield with the name field and it was setup like so:

Code:

<input type="text" name="field" />

then the value of this field when the form is submitted can be obtained by doing $_POST['field']. All fields within the array will be sent to $_POST even if they are empty.

$_GET has a similar behavior except forms are not involved. If you were to go to your document via an internet browser and type this in the URL:

Code:

http://www.domain.com/my_script.php?act=idx

$_GET would have a key named act and it's value would be idx. Inside the URL, you can add as many of these values as you want except you only being by using a question mark. To separate other keys with their values you use the & character.

Code:

http://www.domain.com/my_script.php?act=idx&logged_in=1

$_GET would now have two keys: act and logged_in with idx being the value of act and 1 being the value of logged_in.

Comments

Comments are little messages you can leave in your PHP document for others to read. They will be ignored by PHP.

There are three ways you can create a comment. One is by preceding the line with a #, like so:

Code:

<?php# This is a comment so PHP will ignore it?>

The comment ends with a new line.

Code:

<?php#This is a commentThis is not part of the comment so PHP will error.?>

You can do the exact same thing but instead of doing # you do //.

Code:

<?php// This is a comment?>

The third way is by surrounding your comment with /* and */. */ is used to end the comment so you can use multiple lines and still have it as part of the comment.

Code:

<?php/* This is a commentThis is also part of the comment since the ending has not been used.The comment ends here */

These are very helpful for leaving little notes for either yourself or anyone else who can open the file in notepad.

What is the difference between single quotes and double quotes?

The most significant difference is with double quotes you can use variables inside the string and PHP will actually replace it with the value of the variable. If you had this code:

Code:

$var = "This is a string";echo "Here is one string: $var";

The output would be Here is one string: This is a string. Using single quotes will not do that and you would instead get Here is one string: $var as a result.

This can also be done with arrays, except you must surround them with brackets inside the string, like so:

Code:

echo "Here is one string: {$array['var']}";

Some things you can do with your new found knowledge!

When someone submits this form:

Code:

<form action="my_script.php" method="post"> Age: <input type="text" name="age" /> <input type="submit" name="Submit" value="Submit" /></form>

You can capture the user's inputted age and echo it!

Code:

if ( $_POST['Submit'] ){ echo "Your age is: {$_POST['age']}";}else{ // This is a comment /* I need to tell you that the form hasn't been submitted because $_POST['Submit'] was not found */ echo "You cannot access this file directly!";}

Mentor
12-07-2007, 06:32 PM
By the looks of it you took some time makeing the script, although i would probabaly suggest doing a bit of reaserch before hand, only haveing read the first few paragraphs its quite apparnt you not aware what a function is?

function bob($food){
$string = "bob likes ".$food;
return $string;
}
echo bob("cake");

is a function. Note no semi-colon is needed at the end of it, php uses { } to enclose code. ; is what goes at the end of a line or statement. A very differnt thing from a fucntion
Secondly both echo and print are language constructs, not functions, hence no () are requred when useing em.

Secondly i really dont get why you went in to all that detail with varible types concidering to a php amiture its pointless, php being incredibly flexiable with data types and not even requreing you do declear them in almost all instances.

$thing = "23";
$thing1 = false;
$thing2 = "cake";
Thats set as a intiger, boolien and string.. but to a php novice who gives a crap? the first one stores 23, the second false, and the 3rd the word cake. The actul data types used are pretty irrelivent.

Just some quick observations :)

Splinter
12-07-2007, 07:34 PM
As Karl says datatypes arent relevant in php so may aswell remove that from your tutorial as you may confuse people becuase its needless information. Unlike say C php dosent require data types to be defined as int, bool, char etc a variable just holds a string.

I3rap
12-07-2007, 09:18 PM
I didn't write this. I used it and it helped me so I'm passing on a guide.

QuickScriptz
13-07-2007, 02:56 AM
By the looks of it you took some time makeing the script, although i would probabaly suggest doing a bit of reaserch before hand, only haveing read the first few paragraphs its quite apparnt you not aware what a function is?

function bob($food){
$string = "bob likes ".$food;
return $string;
}
echo bob("cake");

.......

Just some quick observations :)

Well you gotta learn the basics that go inside the function before making the function itself now don'tcha? :P

Dentafrice,
13-07-2007, 03:01 AM
you basicly copy and pasted it?
:\

Mentor
13-07-2007, 03:27 AM
Well you gotta learn the basics that go inside the function before making the function itself now don'tcha? :P

Indeed you do, but learn it as much as you like, a statement aint gonna become a function any more than a flashlight is gona become a duck now is it.

Want to hide these adverts? Register an account for free!