Author Topic: Introduction To PHP  (Read 2374 times)

0 Members and 5 Guests are viewing this topic.

Offline The Alchemist

  • Peasant
  • *
  • Posts: 100
  • Cookies: 18
  • Cult Of Personality
    • View Profile
    • Scriptings - Paste Tool
Introduction To PHP
« on: March 20, 2013, 03:16:46 pm »
Hello Evil Zone. I'm The Alchemist.. If you find anything wrong in it, please do leave a comment here or PM me. Anything you'd want me to add here or any doubts regarding the contents of this thread, you may leave a comment here and I'll surely help.
 
Introduction To PHP
 
What is PHP?
 
PHP stands for "PHP hypertext pre-processor".
It is predominantly a web programming language, so you can design and create web systems. It is a server-side language, which means that it doesn't run on the user's browser. It is an interpreted language and not a compiled language which means, the source code isn't converted to a form that can directly be run by the compiler. Every time a PHP acript is run, the script is re-interpreted.
It is an HTML embedded scripting language. You'll see that most of its syntax is like C, Java, etc.
 
Why learn PHP?
 
PHP is the most popular web programming language in the world. HTML is static, a web scripting language like PHP makes webpages dynamic in nature. There are other web-scripting languages like ASP, JSP, etc. but PHP is way better and popular than them.
PHP is used everywhere in the internet. You try loginng in to your Evil Zone or facebook account, a PHP script verified whether your username and password combination is valid or not. You go to your school's website to check your grades, a PHP script shows you your grades when you enter your roll number.
 
Advantages Of PHP
  • Open Source
  • Cross-Platform
  • Support(Its very popular, so you can easily get guidelines and tutorials)
  • High Returns(A site made in PHP has the potential of the site being visited a lot)
  • Huge Community(Lots of PHP developers around the world)
  • Embedding(Can be embedded in HTML)
  • Stability, Flexibility and Speed
  • Bright Future(A lot of good stuff can be made in the future)
  • Quick
  • Extensions(Extremely scalable)
  • Other Tools(Easy to access tools such as google maps)
  • Pre-Configured(Most hosting services have PHP pre-installed)
What do I need type scripts?
 
First of all, you'll need a text editor or an IDE. Its always better to use a text editor and hard code everything. But then, again there are hundreds of functions in PHP which are impossible to memorize. So, its upto you to decide. You may even use something as simple as notepad.
You may use either of these text editors :
Sublime Text
Notepad++
PSPad ----> My personal choice.
 
 
What do I need to run PHP scripts?
 
As PHP is server sided, its not as easy as running HTML scripts. You'll need to set up a PHP environment in your computer to run them. So, you'll need one of these softwares :
 
For Windows : XAMPP
For Linux   : LAMP
For MacOS   : MAMP
 
After you install one of these in your computer, go to the installation directory and navigate to the directory named htdocs. Now, paste your PHP script inside the htdocs folder and then, run Apache(your localhost webserver). For XAMPP, you need to open the file xampp_start.exe from the xampp folder.
Now, open your browser and type this on your address bar :
Code: [Select]
http://127.0.0.1/scriptname.phpAnd your, PHP script that you'd placed in the htdocs folder will get executed in the Apache server and the corresponding HTML code will be displayed in your browser.
Any doubts about running a PHP script? You're free to post your questions in on this thread or PM me.
 
Lets begin a bit of coding
 
NOTE : I'll be covering the very basics of PHP coding and I won't be going into details. I'll include enough information for you to understand simple PHP codes.
As I'd said earlier, PHP has a syntax very similar to C, Java and other similar languages. So, if you know any other programming language, it'll be very easy for you to learn and understand PHP.
 
Hello world
 
A PHP code begins with <?php and ends with ?>. Its the convention for writing PHP codes. A "Hello World" program would look like this :
Code: (php) [Select]
<?php
echo "Hello Evil Zone";
?>

As you can see, the code begins with <?php and ends with ?>. In PHP, echo is the equivalent of printf(or cout<< in C/C++) or System.out.print(in Java).
What this code does is, it displays "Hello Evil Zone"(without quotes) in your browser. The keyword echo is used for outputting text or variables.
And mind the semicolon, unlike VB or VB.NET, statements in PHP are terminated by a semicolon.
 
 
Comments
 
Like every other programming language, PHP also supports comments. I recommend you to put lots of comments on your code as you write them. There are three ways in which you can comment PHP codes.
Code: (php) [Select]
<?php
// This is a single line comment
 
# This is another single line comment.
 
/* This
is a multi-line
comment */
?>

Variables and datatypes
 
There are four types of data in PHP. They are :
Integer --> Any whole number.
Float   --> Any whole number or real number.
String  --> Any character or a collection of characters.
Boolean --> Either true or false.
 
Declaring and initializing a variable
 
This is how we declare and initialize a variable in PHP :
Code: (php) [Select]
<?php
$varname1 
1// This is an integer
$varname2 100.5// This is a float
$varname3 "PHP"// This is a string
$varname4 true// This is a boolean
?>

PHP automatically recognizes the datatype of the variable as we initialize the value to it.
Hence, you don't need to do this :
Code: [Select]
int $var = 5;^^^ This is wrong. And not allowed in PHP.
 
Quotation Marks
 
You can declare strings with both the " ans well as ' marks.
The difference between them are :
You can use Escape sequences such as \n, \t, \r, etc within " but within ', these are treated as normal text.
You can output variables within " but not within '.
 
Example :
Code: (php) [Select]
<?php
echo "\n"// Goes to the next line
echo '\n'// Displays \n, treated as simple text
$acc 10;
echo 
"$acc"// Displays 10 (the value of $acc)
echo '$acc'// Displays $acc (treated as simple text)
echo "{$acc}with{$acc}"// The {} are used to separate the variables from the text inside the quotes
// ^^ this displays 10with10  
?>

Concatenation
 
In PHP, strings can easily be concatinated using the . operator.
 
Example :
Code: (php) [Select]
<?php
$v1   
"P";
$v2   "H";
$conc $v1.$v2."P";
echo 
$conc// Displays the concatinated result i.e. PHP
?>

Code: (php) [Select]
<?php
echo "First line"."<br />"."Next line";
?>
Here, have a look at "<br />". What this does is, it takes the output to the next line, i.e. it marks the end of the line. Don't be confused, remember what I'd said earlier? "PHP scripts are executed in the server and the output is displayed in your browser as HTML code".
So, the output of the above code will be like this :
Code: [Select]
First line
Second line

Escaping
 
Just like any other language, the \ is used for escaping characters.
To display ' within single quotes, we need to escape it.
To display " within double quotes, we need to escape it.
 
Example :
Code: (php) [Select]
<?php
echo """; // This is wrong if you want to display "
echo "\""// This is right if you want to display "
echo '"';  // This is also right if you want to display "
 
echo '''; // This is wrong if you want to display '
echo '\''// This is right if you want to display '
echo "'";  // This is also right if you want to display '
?>

Remember, to use escape sequences, use "" and not ''. I'd said this earlier.
 
 
Operators
 
Arithmetic Operators
These are use for performing arithmentic operations.
 
+  --> Addition operator
-  --> Subtraction operator
*  --> Multiplication operator
/  --> Division operator
%  --> Modulus operatot
++ --> Increment operator
-- --> Decrement operator
 
Example :
Code: (php) [Select]
<?php
$a 
9// Equals 10
$a 4// Equals 5
$a 9// Equals 9
$a 3// Equals 3
$a 2// Equals 1
echo $a++; // Displays the value of $a and then increases the value of $a by 1
echo ++$a// Increases the value of $a by 1 and then displays the value of $a
?>

Assignment operator
 
= is the assignment operator used for assigning values to variables
Example :
Code: (php) [Select]
<?php
$var 
1// $var is assigned 1
?>

Comparison Operators
These are used for comparing variables or values
 
==  --> Equals to operator
<   --> Lesser than operator
>   --> Greater than operator
<=  --> Lesser than or equal to operator
>=  --> Greater than or equal to operator
=== --> Equals to operator with datatype check
!=  --> Not equals operator
 
Example :
Code: (php) [Select]
<?php
$a 
= (== 5);    // Returns true
$a = (5);     // Returns false
$a = (1);     // Returns true
$a = (<= 5);    // Returns true
$a = (>= 7);    // Returns false
$a = (!= 5);    // Returns false
$a = (=== '5'); // Returns false
$a = (=== 5);   // Returns true
?>

Ternary operator
The ternary operator is used to initialize a value to a variable within a user defined condition.
The ? and : are the ternary operators.
 
Syntax is this :
Code: [Select]
$var = (condition) ? Value if condition is true : Value is condition is false ;Example :
Code: (php) [Select]
<?php
$val 
= (2) ? true false// $val assigned to true
$val = (2) ? true false// $val assigned to false
$val = (2) ? "yes" "no"// $val assigned with "no"
?>

Conditional Statements
Conditional statements are what control the logic of your application. They are If/Else statements. They are used to execute certain codes onlt when a certain condition is fulfilled.
 
Syantax for using conditional statements :
Code: (php) [Select]
<?php
if (condition)
{
    
// Code if condition is satisied
}
else
{
    
// Code if condition is not satisfied
}
?>

Example :
Code: (php) [Select]
<?php
$age 
18;
if (
$age > = 18)
{
    echo 
"You are adult";  // Displays this as condition is satisfied
}
else
{
    echo 
"You are not adult";
}
 
$age 5;
if (
$age > = 18)
{
    echo 
"You are adult";
}
else
{
    echo 
"You are not adult";  // Displays this as condition is not satisfied
}
?>

Now, suppose you have more than one condition to be checked. We then use the else if statement.
 
Example :
Code: (php) [Select]
<?php
$num 
100;
if(
$num 0)
{
    echo 
$num." is positive"// Displays this as this condition is satisfied
}
else if(
$num 0)
{
    echo 
$num." is negative";
}
else
{
    echo 
$num." is zero";
}
 
$num = -100;
if(
$num 0)
{
    echo 
$num." is positive";
}
else if(
$num 0)
{
    echo 
$num." is negative"// Displays this as this condition is satisfied
}
else
{
    echo 
$num." is zero";
}
 
$num 0;
if(
$num 0)
{
    echo 
$num." is positive";
}
else if(
$num 0)
{
    echo 
$num." is negative";
}
else
{
    echo 
$num." is zero"// Displays this as no conditions are satisfied
}
?>

Using else if statement, you can check for any number of conditions.
You can even perform nesting of conditional statements.
 
Example :
Code: (php) [Select]
<?php
if (condition1)
{
    if (
condition11)
    {
        
// Code if condition1 and condition11 is satisied
    
}
    else
    {
        
// Code if condition1 is satsfied and condition11 is not satisfied
    
}
}
else
{
    if (
condition22)
    {
        
// Code if condition1 not satisfied and condition 22 is satisied
    
}
    else
    {
        
// Code if condition1 and condition22 both are not satisfied
    
}
}
?>

Logical Operators
With logical operators, we can combine conditions.
Here are the logical operators :
&& --> LOGICAL AND operator, used to check if ALL the conditions are satisfied
|| --> LOGICAL OR operator, used to check if ANY ONE the conditions are satisfied
 
Example :
Code: (php) [Select]
<?php
$age1 
10;
$age2 20;
$age3 30;
 
if((
$age1 5) && ($age2 5) && ($age3 5)) // All the conditions are satisfied so, returns true
    
echo "Everyone is above 5 years of age";
if((
$age1 10) && ($age2 10) && ($age3 10)) // All the conditions are not satisfied so, return false
    
echo "Everyone is above 10 years of age";
if((
$age1 10) || ($age2 10) || ($age3 10)) // Two out of three conditions are true so returns true
    
echo "One or more out of the three is more than 10 years of age";
if((
$age1 20) || ($age2 20) || ($age3 20)) // One out of three conditions is true so returns true
    
echo "One or more out of the three is more than 20 years of age";
if((
$age1 90) || ($age2 90) || ($age3 90)) // No condition is satisfied so returns false
    
echo "One or more out of the three is more than 90 years of age";
?>

Iterative Statements
Like C, Java, PHP too has iterative statements. for, while, do while and foreach(I'll discuss foreach loop after I teach arrays)
They are used for executing a piece of code repeatedly.
 
Syntax of for :
Code: [Select]
for(initial value of loop variable ; condition for running ; modification of loop variable)
{
    // Code here
}

Example :
Code: (php) [Select]
<?php
for ($i $i <= 10 $i $i )
{
    echo 
$i."<br />";
}
?>

The output for the above code is :
Code: [Select]
0
2
4
6
8
10

Syntax of while :
Code: [Select]
initial value of loop variable
while(condition for running)
{
    // Code here
    // modification of loop variable
}

Example :
Code: (php) [Select]
<?php
$i 
1;
while (
$i <= 5)
{
    echo 
$i."<br />";
    
$i++;
}
?>

The output for the above code will be :
Code: [Select]
1
2
3
4
5

Syntax of do while :
Code: [Select]
initial value of loop variable
do
{
    // Code here
    // modification of loop variable
}while(condition for running);

Example :
Code: (php) [Select]
<?php
$i 
1;
do
{
    echo 
$i."<br />";
    
$i++;
}while(
$i <= 5);
?>

The output for the above code will be :
Code: [Select]
1
2
3
4
5

NOTE : As you can see, in a do while loop, the code inside the loop is executed and then, the condition is checked. This means that a do while loop will run atleast once even if the condition for running is initially not satisfied. This makes it a exit control loop. Whereas in case of for and while loop, if the condition for running is initially not satisfied, the loop will not execute. Hence, they are entry control loops.
 
Arrays
Arrays are variables that can contain a set of values. Arrays have two parts, values and their respective indexes.
Unlike C, Java, etc. in PHP an array can hold unlimited number of values. Also, an array in PHP can hold different types of values and you can name the indexes with strings unlike C, Java, etc.
 
Syntax for initializing arrays :
Code: [Select]
$arr = array(value1, value2, value3);OR
Code: [Select]
$arr = array(index1 => value1,
                   index2 => value2,
                   index3 => value3);

 
Examples :
Code: (php) [Select]
<?php
$arr1 
= array(10,20,30,40);
echo 
$arr1[0]."<br />"// Displays the value of index 0 i.e. 10
echo $arr1[1]."<br />"// Displays the value of index 1 i.e. 20
echo $arr1[2]."<br />"// Displays the value of index 2 i.e. 30
echo $arr1[3]."<br />"// Displays the value of index 0 i.e. 40
 
$arr2 = array("one" => 1,
              
"two" => 2,
              
"three" => 3,
              
"four" => 4);
echo 
$arr2["one"]."<br />"// Displays the value of index "one" i.e. 1
echo $arr2["two"]."<br />"// Displays the value of index "two" i.e. 2
echo $arr2["three"]."<br />"// Displays the value of index "three" i.e. 3
echo $arr2["four"]."<br />"// Displays the value of index "four" i.e. 4
?>

PHP supports multi-dimensional arrays too :
Example :
Code: (php) [Select]
<?php
$ar 
= array(array(1,2,3),array(4,5,6),array(7,8,9));
echo 
ar[0][0]; // Displays 1
echo ar[1][1]; // Displays 5
?>

Now suppose you don't know the dimension of an array, there's a special function in PHP to display all the values of an array.
Here is how we use it :
Code: (php) [Select]
<?php
$ar 
= array(array(1,2,3),array(4,5,6),array(7,8,9));
print_r($ar); // print_r is the function
?>

foreach loop
Suppose you do not know how many values an array contins or the name of the indexes of the array, but you need to print out all the values contained in the array, this is where the foreach loop comes into play.
Example :
Code: (php) [Select]
<?php
$arr 
= array(10,20,30,40);
foreach(
$arr as $temp_value// What this loop does is, it gets the next value of the array and store it in $temp_value variable
{
    echo 
$temp_value."<br />";
}
?>

The above code displays :
Code: [Select]
10
20
30
40

Another example :
Code: (php) [Select]
<?php
$arr 
= array("one" => 1,
              
"two" => 2,
              
"three" => 3,
              
"four" => 4);
foreach(
$arr as $key => $val// This loop gets the next index and store it in $key and its corresponding value is stored in $val variable
{
    echo 
$key." = ".$val."<br />";
}
?>

The above code displays :
Code: [Select]
one = 1
two = 2
three = 3
four = 4

Functions
A function is essentially a piece of code given an identifier. The main idea behind a function is for the reuseability of the piece of code.
PHP has hundreds of inbuilt functions which makes our work extremely easy.
Syntax for defining functions in PHP :
Code: [Select]
funcion function_name(arguments)
{
    // Piece of code
}

Syntax for calling a function in PHP :
Code: [Select]
function_name(arguments);
Example :
Code: (php) [Select]
<?php
function hello() // Function definition
{
    echo 
"Hello EZ";
}
hello(); // Function call
?>
The output of the above code would be :
Code: [Select]
Hello EZ
With the help of functions you can also return values.
Example :
Code: (php) [Select]
<?php
function greater($v1$v2// function definition
{
    if(
$v1 $v2)
        return 
$v1// return statement
    
else
        return 
$v2// return statement
}
echo 
greater(5,10); // function call
?>
The output of the above code would be :
Code: [Select]
10
Thats all.
I've covered the very basics of PHP in this thread, not in much detail but enough for general idea and understanding. And as I've said earlier, any doubt, any mistake you point out, put it to my notice by leaving a comment here.
 
Here are some ebooks I'd recommend :
PHP 6 And MYSQL Bible
PHP Solutions Dynamic Web Design Made Easy 2nd Edition
Just google them and you'll easily get their free download links.
 
If you want to learn PHP in detail, the best place would be : http://php.net
For video tutorials on PHP, go to http://thenewboston.org
 
Thanks for reading. Hope you enjoyed it.


~The Alchemist
« Last Edit: March 21, 2013, 02:31:45 pm by The Alchemist »
Defeat the best... To be the best...

Offline wookie

  • Peasant
  • *
  • Posts: 68
  • Cookies: -4
    • View Profile
Re: Introduction To PHP
« Reply #1 on: March 20, 2013, 11:55:41 pm »
+1 nice guide, good read for beginners.

Offline techb

  • Soy Sauce Feeler
  • Global Moderator
  • King
  • *
  • Posts: 2350
  • Cookies: 345
  • Aliens do in fact wear hats.
    • View Profile
    • github
Re: Introduction To PHP
« Reply #2 on: March 21, 2013, 03:11:36 am »
Yes great tutorial. Although there is one thing I disagree on and that's being similar syntax to C or Java. From vars to functions, very different. This is due to compiled VS interpreted and loosely typed VS strict typing.

But good intro non-the-less.
>>>import this
-----------------------------

Offline The Alchemist

  • Peasant
  • *
  • Posts: 100
  • Cookies: 18
  • Cult Of Personality
    • View Profile
    • Scriptings - Paste Tool
Re: Introduction To PHP
« Reply #3 on: March 21, 2013, 05:38:55 am »
+1 nice guide, good read for beginners.
Thanks for the appreciation.

Yes great tutorial. Although there is one thing I disagree on and that's being similar syntax to C or Java. From vars to functions, very different. This is due to compiled VS interpreted and loosely typed VS strict typing.

But good intro non-the-less.
Thanks for the feedback.
PHP's syntax is very similar to C, Java as my ebooks say... And I quite agree too.. The loops(for, while and do while) are the same, the conditional statements are the same, etc. etc. So, its quite similar. Yes, there are differences in functions and variables but the similarities can be seen.
So... Maybe I should've said "PHP syntax has some resemblance with C, Java, etc"
« Last Edit: March 21, 2013, 05:40:29 am by The Alchemist »
Defeat the best... To be the best...

Offline Stackprotector

  • Administrator
  • Titan
  • *
  • Posts: 2515
  • Cookies: 205
    • View Profile
Re: Introduction To PHP
« Reply #4 on: March 21, 2013, 11:09:46 am »
Quote
Security : Its open source so, people can easily look at the source codes and point out bugs and use them for bad.
Not Suitable For Large Applications : To make a large application, you need a lot of experience as you may face unwanted bugs
Weak Type :  Implicit conversion may surprise unwary programmers and lead to unexpected bugs.
Wrong
Wrong
And wrong
The first one is also the best thing. If you state that you would say "linux is bad because it's open sourced. and people can find bugs".
The last 2 are totally out of topic. Ofcourse you need alot of experience to create a large application, that is NOT a down side. That is the same with every programming language out there. It's even applicable to HTML/css. You need alot of experience to create large applications. That is why it is also a profession.
Weak type, is also something that only applies to the noobs. A real PHP programmer will always take var types in mind. And knows how PHP initialize variables and knows what kind of variable it holds.

Quote
Adobe Dreamweaver -----> This is an excellent IDE but its not free. You can easily get its cracked version all over the internet.
Dreamweaver is even worst than hitler.

Quote
A PHP code begins with <?php and ends with ?>. Its the convention for writing PHP codes. A "Hello World" program would look like this :
Never use ending ?> php tags in a PHP ONLY file, this way you are sure you never ever output any blank space before the header.

For the rest i will give you a +1, it might be hard to follow for a newbie because it's pretty raw but anyways good.
~Factionwars

Offline Stackprotector

  • Administrator
  • Titan
  • *
  • Posts: 2515
  • Cookies: 205
    • View Profile
Re: Introduction To PHP
« Reply #5 on: March 21, 2013, 11:15:45 am »
Also take in mind some extra things that can be in a newbie tutorial:
var_dump(); -- will boost all your understandings of PHP debugging
Basic $_POST, $_GET, $_SERVER usage ?

You might also use the new Array short syntax, its nice ['evilzone' => 'iscuwl'] instead of array('evilzone' => 'iscuwl')
« Last Edit: March 21, 2013, 11:16:34 am by Factionwars »
~Factionwars

Offline The Alchemist

  • Peasant
  • *
  • Posts: 100
  • Cookies: 18
  • Cult Of Personality
    • View Profile
    • Scriptings - Paste Tool
Re: Introduction To PHP
« Reply #6 on: March 21, 2013, 02:37:45 pm »
Thanks for the feedback Factionwars, I removed whatever you said was wrong. And yes, I'll add a few things about $_POST, $_GET and $_SERVER too.


And this thread isn't good for noobs?? :'(
I didn't go into much detail so that noobs can do something like a crash course through this... :-[
« Last Edit: March 21, 2013, 02:40:59 pm by The Alchemist »
Defeat the best... To be the best...

Offline Stackprotector

  • Administrator
  • Titan
  • *
  • Posts: 2515
  • Cookies: 205
    • View Profile
Re: Introduction To PHP
« Reply #7 on: March 21, 2013, 06:38:19 pm »
Thanks for the feedback Factionwars, I removed whatever you said was wrong. And yes, I'll add a few things about $_POST, $_GET and $_SERVER too.


And this thread isn't good for noobs?? :'(
I didn't go into much detail so that noobs can do something like a crash course through this... :-[

No its perfect:)
~Factionwars

Offline Code.Illusionist

  • Royal Highness
  • ****
  • Posts: 687
  • Cookies: 39
  • Compile or die trying
    • View Profile
Re: Introduction To PHP
« Reply #8 on: April 15, 2013, 01:16:10 pm »
Amazing tutorial. All important basic things in one place. Great work there man. Keep making now advanced tutorials :P .
Vae Victis - suffering to the conquered

Offline The Alchemist

  • Peasant
  • *
  • Posts: 100
  • Cookies: 18
  • Cult Of Personality
    • View Profile
    • Scriptings - Paste Tool
Re: Introduction To PHP
« Reply #9 on: April 16, 2013, 07:49:03 pm »
Amazing tutorial. All important basic things in one place. Great work there man. Keep making now advanced tutorials :P .
Thanks man.
Yeah, I'll be making more if I get time.
Defeat the best... To be the best...