Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PHP Beginners guide
#1
Welcome and Enjoy!

First things first, I don't mean to steal Tim's readers so please check out his tutorial too.
http://www.supportforums.net/showthread.php?tid=335

Now after my series, 1 Tutorial per day, 7 days long, I've decided to change this to, 1 Tutorial per Week,
to make better Tutorials.

Since PHP is my Domain, I've been working on this tutorial in my free time over a period of 1 Week (5 work days) to make this Helpful as much as I can
PHP new comers to get started writing own PHP scripts.

The words in this tutorial that are bold, are those which you should also google if you don't understand them trought this tutorial.

If you don't understand something or have any questions, please post them here and I will try to answer them as soon as posiblle.

My first words to you are, don't stop learning and never think you've learned enough!

What is PHP
Since Wikipedia has this already I will just Quote for Truth!
http://www.wikipedia.com Wrote:PHP originally stood for personal home page.
PHP, or PHP: Hypertext Preprocessor, is a widely used, general-purpose scripting language that was originally designed for web development, to produce dynamic web pages.
It can be embedded into HTML and generally runs on a web server, which needs to be configured to process PHP code and create web page content from it.
It can be deployed on most web servers and on almost every operating system and platform free of charge. PHP is installed on over 20 million websites and 1 million web servers.
PHP was originally created by Rasmus Lerdorf in 1995 and has been in continuous development ever since.
The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.
PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) because of restrictions on the use of the term PHP.

PHP has evolved to include a command line interface capability and can also be used in standalone graphical applications.

Read before or after reading the below content!
http://en.wikipedia.org/wiki/PHP
http://en.wikipedia.org/wiki/Apache_server


PHP Enviroment
PHP is mostly used on an Apache Server, when the user requests a PHP written page, the request is sent to the server and the script is then handled by an,
PHP Interpreter, and after the execution the result is sent back to the server and outputed to the end-user in a form of an HTML file.

So for writing and using PHP scripts, you will need an Host that has PHP and mostly MySql installed/enabled, but writing and testing PHP on a host isn't the right way to go
when developing PHP applications, therefor it is recommended using an local Apache server which runs on your local system and it is not avalible to the public on the internet.
That way you can locally write and test your code, all your development should be don on a local server before published.


Setting up a Local Server
There are few ways to setup a local Apache Server, those variy depending on the Operational System you are using.

On Mac OS the Apache and PHP are already installed but in most cases not enabled, therefor I recommend you reading this tutorial if you are a Mac user.
http://foundationphp.com/tutorials/php_leopard.php

On Windows you will need a software that installs Apache, PHP and MySql on your system and makes it ready for use.
I'm using WAMP and can only recommend it.
http://www.wampserver.com/en/

When WAMP is installed, all PHP script you write are to be placed insde "wamp/www" directory.

http://www.apachefriends.org/en/xampp.html

XAMPP is avaliable for mulitple Systems, Linux, Windows, Mac OS and Solaris.
In XAMPP the dircetory for placing your script is called "htdocs".

On windows you will get an installer to install the above two software, in your first install you can just click on the NEXT button until it's installed.

On Linux there are more ways to enable Apache and PHP, so I recommend you to google your Linux distro and how to setup apache on it.
For Ubuntu, read this.
https://help.ubuntu.com/community/ApacheMySQLPHP


After you are done with setting up your local Server, open your Text editor of choise and input this.

PHP Code:
<?php

print "Localhost is ready and working!";

?>

Now save the file as "test.php" and place it in the right directory, like said for WAMP it is the WWW directoy inside your wamp installation folder.
Once your script is placed in the right spot, you can view it by opening your Web Browser and input in the Adrress bar "http://localhost/test.php". (without the quotes)
If you done everything right, you will see
Code:
Localhost is ready and working!

That means that you have successfully set up Apache and PHP on your System.


Starting with PHP
To let your Server know that the file is a PHP one, the first step is to save your files with the extension "*.php" (where * is the name of the file).
Second step is the content of the file, PHP commands are put between the starting tag "<?php" and the closing tag "?>".
That way the server know that there is a php code and needs to be sent to the PHP interpreter, and the parser only executes the code that is between the starting and closing tag.

PHP Code:
<?php

// This is the place to write your actual code.

?>

PHP can also be embedded in regular HTML files.

PHP Code:
<html>
    <
head>
        <
title>PHP in HTML files</title>
    </
head>

    <
body>
        <?
php
        
        
// This is the place to write your actual code.

        
?>
    </body>
</html> 

I wouldn't recommend embedding PHP in HTML file, simply becasue you can use PHP to output HTML codes.

Commenting
When you develop Web applications your code can be small with only few lines, but in most cases it will be a long one and mostly spread into multiple files.
Therefor commenting is one big and important setp in writing any code, not only PHP .
You should learn to comment your code with right definitions, it will make your life easier when you need to go trought your code and finding a specific function or a variable.
Comments are ingored by PHP interpreter and will not be executed.

There are 2 types of comments "Singleline" and "Multiline", and are expressed with "//" or "/* */"

PHP Code:
<?php

// This is a single line comment

/*
This is a multiline comment
and can have more lines of
text
*/
?>

Output
First words, Every PHP statement ends with a semi-colon ";", and forgeting this is probably the mistake that occurs most.

There are two main commands used to output content to the actual web site, "echo" and "print".
The main difference between those two is, "echo" is a language construct and it accepts multiple expressions while "print" is also a function and it doesn't
except multiple expressions.

(10-16-2009, 08:34 AM)Spl3en Wrote: The biggest difference between them is the return value ; print can return true or false, whereas echo doesnt return anything.

But both are used for the same thing, to output content to the website.

PHP Code:
<?php

// simple echo
echo "This is a simple echo command";

/* multi expression echo
uses "," to split the values
*/
echo "This is the first"" and this is the second expression";

//print function
print "Using the print";

$t 1;

// will output I'm number $t
echo 'I\'m number $t';

//will output I'm number 1
echo "I'm number $t";

?>

The above code brings us to the:

Strings
A string is a collection of characters, like this sentence or "SupportForums".
In PHP stings must be enclosed within the Quotation marks, single (') or double (").
The difference between ' and " is, values that are enclosed in double quotes (") are being automatically parsed for specal characters, such as variables.
If the quotation marks used to enclose the string are also used within the sting itself, they must be ecaped with the "\" backslash.

PHP Code:
<?php

// will output This string uses " double quotes
print "This string uses \" double quotes";
// will output this uses ' single quotes
print 'this uses \' single quotes';

?>

If you don't escape the quotes you may encounter some errors.
You can escape everything you want when you need it.
Escaping is done with the "\" backslash.


Numrical values
The numbers dosn't need to be enclosed in quotation marks.

Integer:
Integer are whole Numbers: 1, 22, 452, -1238
PHP Code:
<?php

$int 
30;

?>

Boolean:
Boolean variable can hold only two values, 1 or 0 / TRUE or FALSE.
PHP Code:
<?php

$bool 
true;
// is same as 
$bool 1;

?>

Float:
Floating-points are numbers with decimal expansions, 0.5, 156.2 or -2.0
PHP Code:
<?php

$float 
0.5;

?>

More about data types can be found on
http://www.php.net/manual/en/language.types.php

Variables
In the above codes you've seen words that start with a dollar symbol ($), these are the so called variables.
In PHP variables are declared using $ symbol and following with the name of the specific variable, variables names must start with a character or underscores,
and can have multiple characters, underscores or numbers.
Assigning the value to a variable is done with the egaul operator "=", following by the value of the array.

PHP Code:
<?php

// valid variable names are
$one 1;
$_two 2;
$three_ 3;
$_4 4;

// non valid one
$1;

?>

When declaring variables the best way to choose a name is based on the value they hold or should hold, that way you won't have problems knowing what variable holds when reading your code.
In PHP variable names are case-sensitive, which in other words means that a variable declared with a name "var" is NOT as same as a variable with the name "Var".
Also in PHP you don't have to declare the type of an variable and which value it holds, you can define a variable as boolean and then later in your script change it's value to a string,
without the parser complaining about your decision.

You can also assign a value to multiple variables
PHP Code:
<?php

$var1 
$var2 "Both variables hold this string as their value!";

?>


Basics
Now that you know what variables are and how they are handled, let us go to calculations.
Many may say you need to know Math for programming, well in few languages that is the case but not really in PHP,
all you need to know are the basic forms of Mathematics.

PHP Code:
<?php

// will output 10
print 5;

// will output 25
print 5;

// will output 5
print 25 5;

// will output 20
print 25 5;
?>

As you can see it's simple, but there is more.
When doing calculations you will need the exact form of what you need calculated.

PHP Code:
<?php

// the following will calculate  2 + 10 first and then multiply by 2
print (10) * 2// result = 24

// the next will first multiply 10 by 2 and then add 2
print + (10 2); // result = 22
?>


Updating variables
There are ways to update your variables fast, with the concatenation operator (.) you can add values to your variables.

PHP Code:
<?php

$str 
"This is";

// $str contains now only "This is" text
print $str;

$add "full";
$str .= " ".$add;

// $str now contains "This is full" text
print $str;

?>

You can also increase and decrease integral variables.

PHP Code:
<?php

$int 
1;

print 
$int++; // will increase value of $int by 1

print $int--; // will decrease value of $int by 1

$new_int 5;

$int += $new_int// the value of $new_int will be added to $int and $int will now be equal to 6

$int -= $new_int// the value of $new_int will now be subtracted from $int and it will be 1 again
?>

There is one little thing you should see,
using "++" to increase the value of a variable by 1 can be done in two ways, those two ways are a bit different in output.

PHP Code:
<?php

$int 
1;

// output 2
print ++$i// this will first increase $int by 1 and then output it

$int 1;

// output 1
print $i++; // this method will first output the value and then increase it by 1

?>


Passing
The great power of PHP is the ability to pass your variables onto a different script, for example using a form where user can input his/her name.
Passing variables can be done in two ways, the POST and the GET method.
Here is a example of a post method:

HTML
Code:
<html>
<head>
</head>

<body>
  
  <form action="login.php" method="post">
   Username: <input type="text" name="usrname" /><br />
   <input type="submit" name="login" value="Login" />
  </form>

</body>
</html>

In the above code, we create a form which when submitted will redirect the user to "login.php" file, that is done with the attribute "action".
In the form tag you can see also a attribute called "method", this can be set to post or get, and based on which method you use you'll need the right variables to check and call.

login.php
PHP Code:
<?php

$usrname 
$_POST['usrname'];

print 
$usrname// will output the user input

?>

"$_POST" is a so called super-global variable, it holds the values of a HTML form that was sent using the "post" method.
So when the form in the above html code is sent (the submit button was pressed), all "<input>" fields are saved to our "$_POST" variable and we can access them with our PHP script
To access a specific value within the "$_POST" variable you need to call the right member.
In the above code we have created a input field for our users name.
Code:
<input type="text" name="usrname" />

Take a look at the "name" attribute, it' defined as "usrname".
So to access this input field with PHP you'll need to call it by it's name

PHP Code:
$_POST['usrname'

The other way is the "GET" method, the "GET" is used as same as "POST" but it works different.
Look at the url of this page and you will see a "GET" method.
Code:
http://www.supportforums.net/showthread.php?tid=01

As you can see you are currently viewing the "showthread.php" file, after that you see "?tid=01", that is the "GET".
? symbol is used to define the use of the "GET" method, after that variable names follow and "=" their value, so to access the variable "tid" your PHP
script will look like

PHP Code:
<?php

print $_GET['tid']; // will output 01

?>

Easy isn't it.
There are more way to pass variables and you will learn more about them when you start writing your PHP scripts.
Other two are $_COOKIE and $_SESSION.


Arrays
In the above code you've seen something new on our variables.
PHP Code:
$_GET['tid'

"['tid']", I bet you already wonder what that is, well it's a member of a so called Array.
http://www.wikipedia.com Wrote:An array is a systematic arrangement of objects, usually in rows and columns. Specifically, it may refer to several things.

PHP Code:
<?php

$user 
= array(
    
'name' => 'Ninja',
    
'age' => 21,
    
'lang' => 'PHP'
);

print 
$user['name']; // will output Ninja
print $user[1]; // will output 21

?>

When using array the first thing you should know is, they can be called by the name of the member or by the ID.
As seen in the above code "$user['name']" and "$user[1]", you might think why are the above outputs not the same since the first memebr of the array "name" is, well that's easy
Array count starts with "0", so you would need to call "$user[0]" to output the value of "name" member.


Checking
The arrays brings us to the checking of variable values.

PHP Code:
<?php

$admin 
"Geek";
$usrname $_POST['usrname'];

if(
$usrname == $admin) {
    print 
'Welcome back '.$admin// print out Welcome back Geek
}

?>

In the above code we use the if function to compare "$usrname" with "$admin", if both have the same value we print out a welcome message.
For that we use Comparison Operators, to be exact we use "==", which checks if the two values are equal.
More info: http://php.net/manual/en/language.operat...arison.php

But in the above code if "$usrname" isn't equal to "$admin" there will be no output, this we can change by using the else function.


PHP Code:
<?php

$admin 
"Geek";
$usrname $_POST['usrname'];

if(
$usrname == $admin) {
    print 
'Welcome back '.$admin// print out Welcome back Geek 
}else{
    print 
"I'm sorry, but this is not a place you want to be at!"// print out error message
}

?>

"Else" is used to execute a code block if the comparison didn't match, so if "4usrname" don't have the value that is same as "$admin" (Geek), the code in the "else" block will
be executed.

And what to do in a case you have two admins, for that PHP has a function elseif, "elseif" is used to run another compare between two or more items if the first failed.

PHP Code:
<?php
$admin 
= array(
    
=> 'Ninja',
    
=> 'Geek'
);

$usrname $_POST['usrname'];

if(
$usrname == $admin[0]) {
    print 
"Welcome back Ninja!";
}elseif(
$usrname == $admin[1]) {
    print 
"Welcome back Geek!";
}else{
    print 
"You are in the wrong place!";
}

?>

As you can see above we are first checking if "$usrname" is equal to "$admin[0]", if not we ust "elseif" to check if "$usrname" is equal to "$admin[1]".
And if there is no match we print out "You are in the wrong place!".

There is also a functions called switch, it it as same as using "if" and "elseif" mulitple times.

PHP Code:
<?php

$int 
1;

switch(
$int) {
    case 
0:
        print 
'$int = 0';
        break;
    case 
1:
        print 
'$int = 1';
        break;
    case 
'str':
        print 
'$int is a string';
        break;
    default:
        print 
'No matches occured!';
        break;
}

?>

We use switch to check the value of "$int" and then output the right message.
"case" is used to define a value that needs to be checked, so if our $int variable has a value of "0" it will output "$int = 0".
"default" is the default "case" that is executed if no matches occured during our switch execution.

Also not to forget break, as the words says, it breaks the execution of the switch function, if "break" isn't found the function will run until the end or the next matched "break"

Looping
There are times when you want your script to execute a code block more then one time, for this case you can use functions like for.

PHP Code:
<?php

for($i 0$i <= 10$i++) {
    print 
$i.'<br />';
}

?>

The first parameter "$i = 0" is used to define a variable that is used for counting the loops, the second parameter "$i <= 10" tells the function to run as long as
"$i" is under or equal "10" ( <= ), and as you learned in the begining "$i++" is used to increase the value of "$i" by 1 on the end of the loop.

The output of the above code will look like this.
Code:
0
1
2
3
4
5
6
7
8
9
10

Another way of looping things is the while function, this function does the same as "for" function but it only uses one parameter.

PHP Code:
<?php

$i 
0;

while(
$i <= 5) {
    print 
$i;
    
$i++; // if you don't increase the value of $i the while function will never stop running since $i then remain 0
}

?>

As you see it's pretty simple, but if you don't increase the value of "$i" the function will run endless.
Another way of using the "while" function is do function.
Basiclly it's definition is DO FIRST CHECK LATER.

PHP Code:
<?php

$i 
0;

do {
    print 
$i;
    
$i++;
}while(
$i <= 5);

?>


There is also a way to run loops throught a "array", a function used for this case is called foreach.
As the name says it exectues a code block "for each" memebr of the given array.

PHP Code:
<?php

//we create the array
$array = array(1234"end");

foreach(
$array as $index => $value) {
    print 
$array[$index];
    
// or
    
print $value;
}

?>

The "foreach" function runs trought the array until it reaches the "end" of the array, the id of the member is declared in the "as $index" and the value of the memebr is then put into "$value" variable.


Functions
So far so good, there is even more, often you'll need the same code to do something more then one time but without using one of the looping methods.
This can be done with the functions, functions are used to hold code blocks and excute them only when the function is called.

PHP Code:
<?php

function calculate($x$y) {
    print 
$x $y;
}

// do something here


// and now we call our function
calculate(55); 

?>

In this code we have created a function with the name "calculate", you can name your functions as you like but you should use a name that isn't already a PHP built in function, like for example "while".
The code inside of function is only executed when the function is called.
The above function accepts 2 parameter "$x" and "$y" those parameter can be set when the function is called.
PHP Code:
calculate(55); 

Since all that our function does is "print $x + $y" it will output "10", since 5 +5 is 10.


Variable scope
http://www.php.net Wrote:The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.


PHP Code:
<?php

// declare global variable
$i 5;

function 
print_i() {
    print 
$i;
}

?>

The above function is used to output the value of "$i", but because "$i" was declared outside of the function
the only thing the function will output is a "Undefined variable" error message.
Because "$i" was declared outside of the function it has a "global scope" nad must be declared within the function as global.

PHP Code:
<?php

// declare global variable
$i 5;

function 
print_i() {
    global 
$i;

    print 
$i;
}

?>

The function now when called will output "5", because the "$i" was declared as global.
All variables that are declared within the function have "local scope" and can only be accessed by the same function
Read more: http://php.net/manual/en/language.variables.scope.php


More Info
Reading tutorials is good but you shouldn't concentrate much on tutorials, you should rather download and read already writen PHP applications and try to understand
what the code is doing.
You should also try writing everything you can think of.

The best site to get help with PHP ist their own
http://www.php.net/docs



Thank you for reading and also check out my other tutorials

Debugging your PHP code
Securing Web Aplications
Create Newsletter subscription
Reply
#2
Good for starters... can you include classes??
I am your Father
Reply
#3
(10-16-2009, 03:52 AM)n1tr0b Wrote: Good for starters... can you include classes??

Thanks!
Yeah I was thinking about that and I tought to write another tutorial that is only about the classes.
Reply
#4
(10-16-2009, 03:53 AM)NinjaGeek Wrote: Thanks!
Yeah I was thinking about that and I tought to write another tutorial that is only about the classes.

classes are very useful for me.... always
I am your Father
Reply
#5
(10-16-2009, 04:59 AM)n1tr0b Wrote: classes are very useful for me.... always

Roflmao Not only for you, but a newbie doesn't need them....
I will do one totally about classes in PHP
Reply
#6
I know one thing.
I am a noob when it comes to programming and you are my teacher now.
Php doesn't looks hard, maybe because i know a little about c++ and they both have similars and close concepts but i remains a different language.

thx for the tut, i was looking for a similar one to help learning php
Reply
#7
(10-16-2009, 05:46 AM)tartou2 Wrote: I know one thing.
I am a complet noob when it comes to programming and you are my teacher now.

thx for the tut, i was looking for a similar one to help learning php

Thank you!
I'm glad it is helpful for you!
If you have any questions just PM me or post it here.
Reply
#8
Nice tutorial. Thanks for sharing Ninja ;)
Reply
#9
(10-16-2009, 06:32 AM)immi Wrote: Nice tutorial. Thanks for sharing Ninja ;)

Thank you too, for reading it.
Reply
#10
(10-16-2009, 05:00 AM)NinjaGeek Wrote: Roflmao Not only for you, but a newbie doesn't need them....
I will do one totally about classes in PHP

dude classes... for me... speeds up some coding job, and time...
I am your Father
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  PHP Framework List: An Ultimate Guide to 102 PHP Frameworks for Web Developers tk-hassan 0 534 07-27-2020, 11:26 PM
Last Post: tk-hassan
  PHP Video Tutorials (PHP For Beginners) Eleqtriq 4 2,789 10-10-2011, 01:00 PM
Last Post: Greyersting
  [Guide]The Absolute Bare Foundations Of PHP[Free] Poppins 6 1,016 12-14-2010, 05:53 PM
Last Post: Buzz Lightyear
  PHP OOP guide Gaijin 4 1,513 11-10-2009, 11:38 AM
Last Post: Gaijin

Forum Jump:


Users browsing this thread: 1 Guest(s)