Вы находитесь на странице: 1из 46

PHP

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>

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 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 INSTALLATION
WHAT DO I NEED? To start using PHP, you can:

Find a web host with PHP and MySQL support Install a web server on your own PC, and then install PHP and MySQL

USE A WEB HOST WITH PHP SUPPORT If your server has activated support for PHP you do not need to do anything.

Just create some .php files, place them in your web directory, and the server will automatically parse them for you. You do not need to compile anything or install any extra tools. Because PHP is free, most web hosts offer PHP support.

SET UP PHP ON YOUR OWN PC However, if your server does not support PHP, you must:

install a web server install PHP install a database, such as MySQL

The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/ en/install.php

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>

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>

PHP VARIABLES
Variables are "containers" for storing information: EXAMPLE
<?php $x=5; $y=6; $z=$x+$y; echo $z; ?>

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 casesensitive.

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 x will 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(); ?>

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 ?>

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; ?>

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();

?> 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); ?>

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; ?> 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; ?>

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!"); ?>

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"); ?>

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 x+y x-y x*y x/y Name Addition Subtraction Multiplication Division Description Sum of x and y Difference of x and y Product of x and y Quotient of x and y Remainder of x divided by y Opposite of x Example 2+2 5-2 5*2 15 / 5 5%2 10 % 8 10 % 2 -2 Result 4 3 10 3 1 2 0 HiHa

x%y

Modulus

-x a.b

Negation Concatenation

Concatenate two strings "Hi" . "Ha"

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... x=y x += y x -= y x *= y x /= y x %= y a .= b x=y x=x+y x=x-y x=x*y x=x/y x=x%y a=a.b Description The left operand gets set to the value of the expression on the right Addition Subtraction Multiplication Division Modulus Concatenate two strings

PHP INCREMENTING/DECREMENTING OPERATORS


Operator Name ++ x x ++ Description

Pre-increment Increments x by one, then returns x Postincrement Predecrement Postdecrement Returns x, then increments x by one

-- x

Decrements x by one, then returns x

x --

Returns x, then decrements x by one

PHP COMPARISON OPERATORS Comparison operators allows you to compare two values:
Operator x == y x === y x != y x <> y x !== y x>y x<y x >= y Name Equal Identical Not equal Not equal Not identical Greater than Less than Greater than or equal to Description True if x is equal to y Example 5==8 returns false

True if x is equal to y, and they are 5==="5" returns false of same type True if x is not equal to y True if x is not equal to y True if x is not equal to y, or they are not of same type True if x is greater than y True if x is less than y 5!=8 returns true 5<>8 returns true 5!=="5" returns true 5>8 returns false 5<8 returns true

True if x is greater than or equal to 5>=8 returns false y 5<=8 returns true

x <= y

Less than or equal True if x is less than or equal to y to

PHP LOGICAL OPERATORS


Operator Name Description Example x=6 y=3 (x < 10 and y > 1) returns true x=6 y=3 (x==6 or y==5) returns true

x and y

And

True if both x and y are true

x or y

Or

True if either or both x and y are true

x xor y

Xor

x=6 True if either x or y is true, but not y=3 both (x==6 xor y==3) returns false x=6 y=3 (x < 10 && y > 1) returns true x=6 y=3 (x==5 || y==5) returns false x=6 y=3 !(x==y) returns true

x && y

And

True if both x and y are true

x || y

Or

True if either or both x and y are true

!x

Not

True if x is not true

PHP ARRAY OPERATORS


Operator x+y x == y x === y Name Union Equality Identity Description Union of x and y True if x and y have the same key/value pairs True if x and y have the same key/value pairs in the same order and are of the same type

x != y x <> y x !== y

Inequality Inequality Non-identity

True if x is not equal to y True if x is not equal to y 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!"; } ?>

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!"; } ?>

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!"; }

?>

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!"; } ?>

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] . "."; ?>

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] . "."; ?>

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); ?>

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>"; } ?>

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."; ?>

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>"; } ?>

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); ?>

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); ?>

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); ?>

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); ?>

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); ?>

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); ?>

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); ?>

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); ?>

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("Stle","?"); ?> </body> </html>

Output:
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Stle 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:
http://www.w3schools.com/welcome.php?fname=Peter&age=37

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:
http://www.w3schools.com/welcome.php

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.

PHP 5 ARRAY FUNCTIONS


PHP 5 ARRAY FUNCTIONS The PHP array functions are part of the PHP core. No installation is required to use these functions.
Function array() Creates an array Description

array_change_key_cas Changes all keys in an array to lowercase or uppercase e() array_chunk() array_combine() array_count_values() array_diff() Splits an array into chunks of arrays Creates an array by using the elements from one "keys" array and one "values" array Counts all the values of an array Compare arrays, and returns the differences (compare values only)

array_diff_assoc() array_diff_key() array_diff_uassoc()

Compare arrays, and returns the differences (compare keys and values) Compare arrays, and returns the differences (compare keys only) Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function) Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function) Fills an array with values Fills an array with values, specifying keys Filters the values of an array using a callback function Flips/Exchanges all keys with their associated values in an array Compare arrays, and returns the matches (compare values only)

array_diff_ukey() array_fill() array_fill_keys() array_filter() array_flip() array_intersect()

array_intersect_assoc() Compare arrays and returns the matches (compare keys and values) array_intersect_key() Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc( Compare arrays, and returns the matches (compare keys and values, ) using a user-defined key comparison function) array_intersect_ukey() array_key_exists() array_keys() array_map() array_merge() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function) Checks if the specified key exists in the array Returns all the keys of an array Sends each value of an array to a user-made function, which returns new values Merges one or more arrays into one array

array_merge_recursive( Merges one or more arrays into one array ) array_multisort() array_pad() Sorts multiple or multi-dimensional arrays Inserts a specified number of items, with a specified value, to an array

array_pop() array_product() array_push() array_rand() array_reduce() array_replace()

Deletes the last element of an array Calculates the product of the values in an array Inserts one or more elements to the end of an array Returns one or more random keys from an array Returns an array as a string, using a user-defined function Replaces elements from passed arrays into the first array

array_replace_recursive Replaces elements from passed arrays into the first array recursively () array_reverse() array_search() array_shift() array_slice() array_splice() array_sum() array_udiff() array_udiff_assoc() Returns an array in the reverse order Searches an array for a given value and returns the key Removes the first element from an array, and returns the value of the removed element Returns selected parts of an array Removes and replaces specified elements of an array Returns the sum of the values in an array Compares array values in a user-made function and returns an array Compares array keys, and compares array values in a user-made function, and returns an array Compares array keys and array values in user-made functions, and returns an array Compares array values in a user-made function and returns an array

array_udiff_uassoc() array_uintersect()

array_uintersect_assoc( Compares array keys, and compares array values in a user-made ) function, and returns an array array_uintersect_uasso Compares array keys and array values in user-made functions, and c() returns an array array_unique() Removes duplicate values from an array

array_unshift() array_values() array_walk()

Adds one or more elements to the beginning of an array Returns all the values of an array Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an array arsort() asort() compact() count() current() each() end() extract() in_array() key() krsort() ksort() list() natcasesort() natsort() next() pos() prev() range() reset() Sorts an associative array in descending order, according to the value Sorts an associative array in ascending order, according to the value Create array containing variables and their values Returns the number of elements in an array Returns the current element in an array Returns the current key and value pair from an array Sets the internal pointer of an array to its last element Imports variables into the current symbol table from an array Checks if a specified value exists in an array Fetches a key from an array Sorts an associative array in descending order, according to the key Sorts an associative array in ascending order, according to the key Assigns variables as if they were an array Sorts an array using a case insensitive "natural order" algorithm Sorts an array using a "natural order" algorithm Advance the internal array pointer of an array Alias of current() Rewinds the internal array pointer Creates an array containing a range of elements Sets the internal pointer of an array to its first element

rsort() shuffle() sizeof() sort() uasort() uksort() usort()

Sorts an indexed array in descending order Shuffles an array Alias of count() Sorts an indexed array in ascending order Sorts an array by values using a user-defined comparison function Sorts an array by keys using a user-defined comparison function Sorts an array using a user-defined comparison function

PHP 5 CALENDAR FUNCTIONS


PHP CALENDAR INTRODUCTION The calendar extension contains functions that simplifies converting between different calendar formats. It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C. Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice. Note: The Julian Day Count is not the same as the Julian Calendar!

INSTALLATION For these functions to work, you have to compile PHP with --enable-calendar. The Windows version of PHP has built-in support for this extension.

PHP 5 CALENDAR FUNCTIONS


Function cal_days_in_month() Description Returns the number of days in a month for a specified year and calendar

cal_from_jd() cal_info() cal_to_jd() easter_date()

Converts a Julian Day Count into a date of a specified calendar Returns information about a specified calendar Converts a date in a specified calendar to Julian Day Count Returns the Unix timestamp for midnight on Easter of a specified year Returns the number of days after March 21, that the Easter Day is in a specified year Converts a French Republican date to a Julian Day Count Converts a Gregorian date to a Julian Day Count Returns the day of the week Returns a month name Converts a Julian Day Count to a French Republican date Converts a Julian Day Count to a Gregorian date Converts a Julian Day Count to a Jewish date Converts a Julian Day Count to a Julian date Converts Julian Day Count to Unix timestamp Converts a Jewish date to a Julian Day Count Converts a Julian date to a Julian Day Count Converts Unix timestamp to Julian Day Count

easter_days() frenchtojd() gregoriantojd() jddayofweek() jdmonthname() jdtofrench() jdtogregorian() jdtojewish() jdtojulian() jdtounix() jewishtojd() juliantojd() unixtojd()

PHP 5 PREDEFINED CALENDAR CONSTANTS


Constant CAL_GREGORIAN CAL_JULIAN CAL_JEWISH Integer Integer Integer Type PHP Version PHP 4 PHP 4 PHP 4

CAL_FRENCH CAL_NUM_CALS CAL_DOW_DAYNO CAL_DOW_SHORT CAL_DOW_LONG

Integer Integer Integer Integer Integer

PHP 4 PHP 4 PHP 4 PHP 4 PHP 4 PHP 4

CAL_MONTH_GREGORIAN_SH Integer ORT CAL_MONTH_GREGORIAN_LO Integer NG CAL_MONTH_JULIAN_SHORT Integer CAL_MONTH_JULIAN_LONG CAL_MONTH_JEWISH CAL_MONTH_FRENCH CAL_EASTER_DEFAULT CAL_EASTER_ROMAN Integer Integer Integer Integer Integer

PHP 4 PHP 4 PHP 4 PHP 4 PHP 4 PHP 4.3 PHP 4.3 PHP 4.3

CAL_EASTER_ALWAYS_GREG Integer ORIAN CAL_EASTER_ALWAYS_JULIA Integer N CAL_JEWISH_ADD_ALAFIM_G Integer ERESH CAL_JEWISH_ADD_ALAFIM Integer

PHP 4.3

PHP 5.0 PHP 5.0 PHP 5.0

CAL_JEWISH_ADD_GERESHA Integer YIM

variable.string,array,type of key data send karne ki method.post me aur get me diffrence 4 type ki query hoti hai wo insert,select,update,delete,mainly insert aur select ki qoery..... aur session.......... and thoda bahut basis html

Вам также может понравиться