Learning PHP(credit to w3 School) – PHP Basic Collection-1


Have a Happy Learning PHP to all !!!!!!!!!!

today Guys I extracted data From :

Big Credit to W3 School For the Resources!!!!

Enjoy Reading this article, Learning Php Programming.I  extracted all this data, for all who does’nt wants  always to hook into internet connection, or either seldom to connect due to very poor connection. Maybe for some reason tired of online always, Especially to those who owns a tablet or maybe smartphones. Great to share this to y’all. For easy reading eventhought without internet connection you can read this article already. All you have to do is install Evernote onto your devices,laptops, PC desk, tablets, smartphones.. To download Evernote

EverNote Download – here’s the link :Source 1

But for those who got a very strong connection and rather read online here’s the link in w3 School: Click the Logo to jump into the Site:

 

 

 

 

PHP Tutorial

 

PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.

PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP.

Easy Learning with “Show PHP”

Our “Show PHP” tool makes it easy to learn PHP, it shows both the PHP source code and the HTML output of the code.

Example

<!DOCTYPE html>
<html>
<body>

<?php
echo “My first PHP script!”;
?>

</body>
</html>

Run example »

Click on the “Run example” button to see how it works.
 
 

PHP Introduction

PHP code is executed on the server.


What You Should Already Know

Before you continue you should have a basic understanding of the following:

  • HTML
  • CSS

If you want to study these subjects first, find the tutorials on our Home page.


What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use
lamp PHP is simple for beginners.

PHP also offers many advanced features for professional programmers.


What is a PHP File?

  • PHP files can contain text, HTML, JavaScript code, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have a default file extension of “.php”

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.


Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP has support for a wide range of databases
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

PHP Syntax

The PHP script is executed on the server, and the plain HTML result is sent back to the browser.


Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is “.php”.

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that sends the text “Hello World!” back to the browser:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo “Hello World!”;
?>

</body>
</html>

Run example »

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.

With PHP, there are two basic statements to output text in the browser: echo and print.


Comments in PHP

Example

<!DOCTYPE html>
<html>
<body>

<?php
//This is a PHP comment line

/*
This is
a PHP comment
block
*/
?>

</body>
</html>

Run example »

PHP Variables

Variables are “containers” for storing information:

Example

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

Run example »


Much Like Algebra

x=5
y=6
z=x+y

In algebra we use letters (like x) to hold values (like 5).

From the expression z=x+y above, we can calculate the value of z to be 11.

In PHP these letters are called variables.

Think of variables as containers for storing data.

PHP Variables

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must begin with a letter or the underscore character
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • A variable name should not contain spaces
  • Variable names are case sensitive ($y and $Y are two different variables)
Both PHP statements and PHP variables are case-sensitive.

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it:

$txt=”Hello world!”;
$x=5;

After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable xwill hold the value 5.

Note: When you assign a text value to a variable, put quotes around the value.


PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, we will have to declare (define) the type and name of the variable before using it.


PHP Variable Scopes

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has four different variable scopes:

  • local
  • global
  • static
  • parameter

Local Scope

A variable declared within a PHP function is local and can only be accessed within that function:

Example

<?php
$x=5; // global scope

function myTest()
{
echo $x; // local scope
}

myTest();
?>

Run example »

The script above will not produce any output because the echo statement refers to the local scope variable $x, which has not been assigned a value within this scope.

You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

Local variables are deleted as soon as the function is completed.


Global Scope

A variable that is defined outside of any function, has a global scope.

Global variables can be accessed from any part of the script, EXCEPT from within a function.

To access a global variable from within a function, use the global keyword:

Example

<?php
$x=5; // global scope
$y=10; // global scope

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // outputs 15
?>

Run example »

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

The example above can be rewritten like this:

Example

<?php
$x=5;
$y=10;

function myTest()
{
$GLOBALS[‘y’]=$GLOBALS[‘x’]+$GLOBALS[‘y’];
}

myTest();
echo $y;
?>

Run example »


Static Scope

When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted.

To do this, use the static keyword when you first declare the variable:

Example

<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

?>

Run example »

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.


Parameter Scope

A parameter is a local variable whose value is passed to the function by the calling code.

Parameters are declared in a parameter list as part of the function declaration:

Example

<?php

function myTest($x)
{
echo $x;
}

myTest(5);

?>

Run example »

Parameters are also called arguments. We will discuss it in more details in our PHP functions chapter.

PHP String Variables

A string variable is used to store and manipulate text.


String Variables in PHP

String variables are used for values that contain characters.

After we have created a string variable we can manipulate it. A string can be used directly in a function or it can be stored in a variable.

In the example below, we create a string variable called txt, then we assign the text “Hello world!” to it. Then we write the value of the txt variable to the output:

Example

<?php
$txt=”Hello world!”;
echo $txt;
?>

Run example »

Note: When you assign a text value to a variable, remember to put single or double quotes around the value.

Now, lets look at some commonly used functions and operators to manipulate strings.


The PHP Concatenation Operator

There is only one string operator in PHP.

The concatenation operator (.)  is used to join two string values together.

The example below shows how to concatenate two string variables together:

Example

<?php
$txt1=”Hello world!”;
$txt2=”What a nice day!”;
echo $txt1 . ” ” . $txt2;
?>

Run example »

The output of the code above will be: Hello world! What a nice day!

Tip: In the code above we have used the concatenation operator two times. This is because we wanted to insert a white space between the two strings.


The PHP strlen() function

Sometimes it is useful to know the length of a string value.

The strlen() function returns the length of a string, in characters.

The example below returns the length of the string “Hello world!”:

Example

<?php
echo strlen(“Hello world!”);
?>

Run example »

The output of the code above will be: 12

Tip: strlen() is often used in loops or other functions, when it is important to know when a string ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).


The PHP strpos() function

The strpos() function is used to search for a character or a specific text within a string.

If a match is found, it will return the character position of the first match. If no match is found, it will return FALSE.

The example below searches for the text “world” in the string “Hello world!”:

Example

<?php
echo strpos(“Hello world!”,”world”);
?>

Run example »

The output of the code above will be: 6.

Tip: The position of the string “world” in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1.


Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

The PHP string reference contains description and example of use, for each function!

PHP Operators

The assignment operator = is used to assign values to variables in PHP.

The arithmetic operator + is used to add values together in PHP.


PHP Arithmetic Operators

Operator Name Description Example Result
x + y Addition Sum of x and y 2 + 2 4
x – y Subtraction Difference of x and y 5 – 2 3
x * y Multiplication Product of x and y 5 * 2 10
x / y Division Quotient of x and y 15 / 5 3
x % y Modulus Remainder of x divided by y 5 % 2
10 % 8
10 % 2
1
2
0
– x Negation Opposite of x – 2
a . b Concatenation Concatenate two strings “Hi” . “Ha” HiHa

PHP Assignment Operators

The basic assignment operator in PHP is “=”. It means that the left operand gets set to the value of the expression on the right. That is, the value of “$x = 5” is 5.

Assignment Same as… Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x – y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
a .= b a = a . b Concatenate two strings

PHP Incrementing/Decrementing Operators

Operator Name Description
++ x Pre-increment Increments x by one, then returns x
x ++ Post-increment Returns x, then increments x by one
— x Pre-decrement Decrements x by one, then returns x
x — Post-decrement Returns x, then decrements x by one

PHP Comparison Operators

Comparison operators allows you to compare two values:

Operator Name Description Example
x == y Equal True if x is equal to y 5==8 returns false
x === y Identical True if x is equal to y, and they are of same type 5===”5″ returns false
x != y Not equal True if x is not equal to y 5!=8 returns true
x <> y Not equal True if x is not equal to y 5<>8 returns true
x !== y Not identical True if x is not equal to y, or they are not of same type 5!==”5″ returns true
x > y Greater than True if x is greater than y 5>8 returns false
x < y Less than True if x is less than y 5<8 returns true
x >= y Greater than or equal to True if x is greater than or equal to y 5>=8 returns false
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true

PHP Logical Operators

Operator Name Description Example
x and y And True if both x and y are true x=6
y=3
(x < 10 and y > 1) returns true
x or y Or True if either or both x and y are true x=6
y=3
(x==6 or y==5) returns true
x xor y Xor True if either x or y is true, but not both x=6
y=3
(x==6 xor y==3) returns false
x && y And True if both x and y are true x=6
y=3
(x < 10 && y > 1) returns true
x || y Or True if either or both x and y are true x=6
y=3
(x==5 || y==5) returns false
! x Not True if x is not true x=6
y=3
!(x==y) returns true

PHP Array Operators

Operator Name Description
x + y Union Union of x and y
x == y Equality True if x and y have the same key/value pairs
x === y Identity True if x and y have the same key/value pairs in the same order and are of the same type
x != y Inequality True if x is not equal to y
x <> y Inequality True if x is not equal to y
x !== y Non-identity True if x is not identical to y

PHP If…Else Statements

Conditional statements are used to perform different actions based on different conditions.


PHP Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement – executes some code only if a specified condition is true
  • if…else statement – executes some code if a condition is true and another code if the condition is false
  • if…else if….else statement – selects one of several blocks of code to be executed
  • switch statement – selects one of many blocks of code to be executed

PHP – The if Statement

The if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition)
{
code to be executed if condition is true
;
}

The example below will output “Have a good day!” if the current time is less than 20:

Example

<?php
$t=date(“H”);
if ($t<“20”)
{
echo “Have a good day!”;
}
?>

Run example »


PHP – The if…else Statement

Use the if….else statement to execute some code if a condition is true and another code if the condition is false.

Syntax

if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

The example below will output “Have a good day!” if the current time is less than 20, and “Have a good night!” otherwise:

Example

<?php
$t=date(“H”);
if ($t<“20”)
{
echo “Have a good day!”;
}
else
{
echo “Have a good night!”;
}
?>

Run example »


PHP – The if…else if….else Statement

Use the if….else if…else statement to select one of several blocks of code to be executed.

Syntax

if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
 }

The example below will output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the current time is less than 20. Otherwise it will output “Have a good night!”:

Example

<?php
$t=date(“H”);
if ($t<“10”)
{
echo “Have a good morning!”;
}
else if ($t<“20”)
{
echo “Have a good day!”;
}
else
{
echo “Have a good night!”;
}
?>

Run example »


PHP – The switch Statement

The switch statement will be explained in the next chapter.

PHP Switch Statement

The switch statement is used to perform different actions based on different conditions.


The PHP Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

Example

<?php
$favcolor=”red”;
switch ($favcolor)
{
case “red”:
echo “Your favorite color is red!”;
break;
case “blue”:
echo “Your favorite color is blue!”;
break;
case “green”:
echo “Your favorite color is green!”;
break;
default:
echo “Your favorite color is neither red, blue, or green!”;
}
?>

Run example »

PHP Arrays

An array stores multiple values in one single variable:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;
?>

Run example »


What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1=”Volvo”;
$cars2=”BMW”;
$cars3=”Toyota”;

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.


Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

  • Indexed arrays – Arrays with numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

$cars=array(“Volvo”,”BMW”,”Toyota”);

or the index can be assigned manually:

$cars[0]=”Volvo”;
$cars[1]=”BMW”;
$cars[2]=”Toyota”;

The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;
?>

Run example »


Get The Length of an Array – The count() Function

The count() function is used to return the length (the number of elements) of an array:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
echo count($cars);
?>

Run example »


Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo “<br>”;
}
?>

Run example »


PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);

or:

$age[‘Peter’]=”35″;
$age[‘Ben’]=”37″;
$age[‘Joe’]=”43″;

The named keys can then be used in a script:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);
echo “Peter is ” . $age[‘Peter’] . ” years old.”;
?>

Run example »


Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);

foreach($age as $x=>$x_value)
{
echo “Key=” . $x . “, Value=” . $x_value;
echo “<br>”;
}
?>

Run example »


Multidimensional Arrays

Multidimensional arrays will be explained in the PHP advanced section.


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!

PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.


PHP – Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

  • sort() – sort arrays in ascending order
  • rsort() – sort arrays in descending order
  • asort() – sort associative arrays in ascending order, according to the value
  • ksort() – sort associative arrays in ascending order, according to the key
  • arsort() – sort associative arrays in descending order, according to the value
  • krsort() – sort associative arrays in descending order, according to the key

Sort Array in Ascending Order – sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
sort($cars);
?>

Run example »

The following example sorts the elements of the $numbers array in ascending numerical order:

Example

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>

Run example »


Sort Array in Descending Order – rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
rsort($cars);
?>

Run example »

The following example sorts the elements of the $numbers array in descending numerical order:

Example

<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>

Run example »


Sort Array in Ascending Order, According to Value – asort()

The following example sorts an associative array in ascending order, according to the value:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);
asort($age);
?>

Run example »


Sort Array in Ascending Order, According to Key – ksort()

The following example sorts an associative array in ascending order, according to the key:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);
ksort($age);
?>

Run example »


Sort Array in Descending Order, According to Value – arsort()

The following example sorts an associative array in descending order, according to the value:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);
arsort($age);
?>

Run example »


Sort Array in Descending Order, According to Key – krsort()

The following example sorts an associative array in descending order, according to the key:

Example

<?php
$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);
krsort($age);
?>

Run example »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!

PHP Looping – While Loops

Loops execute a block of code a specified number of times, or while a specified condition is true.


PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In PHP, we have the following looping statements:

  • while – loops through a block of code while a specified condition is true
  • do…while – loops through a block of code once, and then repeats the loop as long as a specified condition is true
  • for – loops through a block of code a specified number of times
  • foreach – loops through a block of code for each element in an array

The while Loop

The while loop executes a block of code while a condition is true.

Syntax

while (condition)
{
  code to be executed;
}

Example

The example below first sets a variable i to 1 ($i=1;).

Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>

<?php
$i=1;
while($i<=5)
{
echo “The number is ” . $i . “<br>”;
$i++;
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The do…while Statement

The do…while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.

Syntax

do
{
  code to be executed;
}
while (condition);

Example

The example below first sets a variable i to 1 ($i=1;).

Then, it starts the do…while loop. The loop will increment the variable i with 1, and then write some output. Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run as long as i is less than, or equal to 5:

<html>
<body>

<?php
$i=1;
do
{
$i++;
echo “The number is ” . $i . “<br>”;
}
while ($i<=5);
?>

</body>
</html>

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

The for loop and the foreach loop will be explained in the next chapter.

PHP Looping – For Loops

Loops execute a block of code a specified number of times, or while a specified condition is true.


The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init; condition; increment)
{
code to be executed;
}

Parameters:

  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)

Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas).

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo “The number is ” . $i . “<br>”;
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The foreach Loop

The foreach loop is used to loop through arrays.

Syntax

foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array value.

Example

The following example demonstrates a loop that will print the values of the given array:

<html>
<body>

<?php
$x=array(“one”,”two”,”three”);
foreach ($x as $value)
{
echo $value . “<br>”;
}
?>

</body>
</html>

Output:

one
two
three

PHP Functions

The real power of PHP comes from its functions.

In PHP, there are more than 700 built-in functions.


PHP Built-in Functions

For a complete reference and examples of the built-in functions, please visit our PHP Reference.


PHP Functions

In this chapter we will show you how to create your own functions.

To keep the script from being executed when the page loads, you can put it into a function.

A function will be executed by a call to the function.

You may call a function from anywhere within a page.


Create a PHP Function

A function will be executed by a call to the function.

Syntax

function functionName()
{
code to be executed;
}

PHP function guidelines:

  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)

Example

A simple function that writes my name when it is called:

<html>
<body>

<?php
function writeName()
{
echo “Kai Jim Refsnes”;
}

echo “My name is “;
writeName();
?>

</body>
</html>

Output:

My name is Kai Jim Refsnes

PHP Functions – Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses.

Example 1

The following example will write different first names, but equal last name:

<html>
<body>

<?php
function writeName($fname)
{
echo $fname . ” Refsnes.<br>”;
}

echo “My name is “;
writeName(“Kai Jim”);
echo “My sister’s name is “;
writeName(“Hege”);
echo “My brother’s name is “;
writeName(“Stale”);
?>

</body>
</html>

Output:

My name is Kai Jim Refsnes.
My sister’s name is Hege Refsnes.
My brother’s name is Stale Refsnes.

Example 2

The following function has two parameters:

<html>
<body>

<?php
function writeName($fname,$punctuation)
{
echo $fname . ” Refsnes” . $punctuation . “<br>”;
}

echo “My name is “;
writeName(“Kai Jim”,”.”);
echo “My sister’s name is “;
writeName(“Hege”,”!”);
echo “My brother’s name is “;
writeName(“Ståle”,”?”);
?>

</body>
</html>

Output:

My name is Kai Jim Refsnes.
My sister’s name is Hege Refsnes!
My brother’s name is Ståle Refsnes?

PHP Functions – Return values

To let a function return a value, use the return statement.

Example

<html>
<body>

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo “1 + 16 = ” . add(1,16);
?>

</body>
</html>

Output:

1 + 16 = 17

PHP Forms and User Input

The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.


PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

Example

The example below contains an HTML form with two input fields and a submit button:

<html>
<body>

<form action=”welcome.php” method=”post”>
Name: <input type=”text” name=”fname”>
Age: <input type=”text” name=”age”>
<input type=”submit”>
</form>

</body>
</html>

When a user fills out the form above and clicks on the submit button, the form data is sent to a PHP file, called “welcome.php”:

“welcome.php” looks like this:

<html>
<body>

Welcome <?php echo $_POST[“fname”]; ?>!<br>
You are <?php echo $_POST[“age”]; ?> years old.

</body>
</html>

Output could be something like this:

Welcome John!
You are 28 years old.

The PHP $_GET and $_POST variables will be explained in the next chapters.


Form Validation

User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load.

You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

PHP $_GET Variable

In PHP, the predefined $_GET variable is used to collect values in a form with method=”get”.


The $_GET Variable

The predefined $_GET variable is used to collect values in a form with method=”get”

Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send.

Example

<form action=”welcome.php” method=”get”>
Name: <input type=”text” name=”fname”>
Age: <input type=”text” name=”age”>
<input type=”submit”>
</form>

When the user clicks the “Submit” button, the URL sent to the server could look something like this:

The “welcome.php” file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array):

Welcome <?php echo $_GET[“fname”]; ?>.<br>
You are <?php echo $_GET[“age”]; ?> years old!

When to use method=”get”?

When using method=”get” in HTML forms, all variable names and values are displayed in the URL.

Note: This method should not be used when sending passwords or other sensitive information!

However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.

PHP $_POST Function

In PHP, the predefined  $_POST variable is used to collect values in a form with method=”post”.


The $_POST Variable

The predefined $_POST variable is used to collect values from a form sent with method=”post”.

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

Example

<form action=”welcome.php” method=”post”>
Name: <input type=”text” name=”fname”>
Age: <input type=”text” name=”age”>
<input type=”submit”>
</form>

When the user clicks the “Submit” button, the URL will look like this:

The “welcome.php” file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

Welcome <?php echo $_POST[“fname”]; ?>!<br>
You are <?php echo $_POST[“age”]; ?> years old.

When to use method=”post”?

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.


The PHP $_REQUEST Variable

The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.

The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.

Example

Welcome <?php echo $_REQUEST[“fname”]; ?>!<br>
You are <?php echo $_REQUEST[“age”]; ?> years old.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s