The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.
As a programming language for the Web, PHP is hard to ignore. Clean syntax, object-oriented fundamentals, an extensible architecture that encourages innovation, support for both current and upcoming technologies and protocols, and excellent database integration are just some of the reasons for the popularity it currently enjoys in the developer community.
Possibly the best thing about PHP is that it’s free—its source code is freely available on the Web, and developers can install and use it without paying licensing fees or investing in expensive hardware or software. Using PHP can thus significantly reduce the development costs of a software application, without compromising on either reliability or performance. The open-source approach also ensures faster bug fixes and quicker integration of new technologies into the core language, simply due to the much larger base of involved developers.
Audience:
This tutorial is designed for PHP programmers who are completely unaware of PHP concepts but they have basic understanding on computer programming. Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful.
|
|
PHP is a general-purpose scripting language originally standing for "Pretty Good Homepage" designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document. It also has evolved to include a command-line interface capability and can be used in standalone graphical applications. PHP can be deployed on most web servers and as a standalone interpreter, on almost every operating system and platform free of charge.PHP is installed on more than 20 million websites and 1 million web servers.
Features :
Simplicity :
Because PHP uses a consistent and logical syntax, and because it comes with a clearly written manual, even novices find it easy to learn. In fact, the quickest way to learn PHP is to step through the manual’s introductory tutorial, and then start looking at code samples off the Web. Within a few hours, you’ll have learned the basics and will be confident enough to begin writing your own scripts. This adherence to the KISS (Keep It Simple, Stupid) principle has made PHP popular as a prototyping and rapid application development tool for web applications. PHP can even access C libraries and take advantage of program
code written for this language, and the language is renowned for the tremendous flexibility it allows programmers in accomplishing specific tasks.
Portability :
With programming languages, portability—the ease with which a program can be made to work on different platforms—is an important factor. PHP users have little to fear here, because cross-platform development has been an important design goal of PHP since PHP 3.0. Today, PHP is available for a wide variety of platforms, including UNIX, Microsoft Windows, Mac OS, and OS/2. Additionally, because PHP code is interpreted and not compiled, PHP scripts written on one platform usually work as is on any other platform for which an interpreter exists. This means that developers can code on Windows and deploy on UNIX without any major difficulties.
Speed :
Out of the box, PHP scripts run faster than most other scripting languages, with numerous independent benchmarks putting the language ahead of competing alternatives like JSP, ASP.NET, and Perl. When PHP 4.0 was first released, it raised the performance bar with its completely new parsing engine. PHP 5.0 improves performance even further through the use of an optimized memory manager, and the use of object handles that reduce memory consumption and help applications run faster.
Open Source :
Possibly the best thing about PHP is that it’s free—its source code is freely available on the Web, and developers can install and use it without paying licensing fees or investing in expensive hardware or software. Using PHP can thus significantly reduce the development costs of a software application, without compromising on either reliability or performance. The open-source approach also ensures faster bug fixes and quicker integration of new technologies into the core language, simply due to the much larger base of involved developers.
Extensible :
Keeping future growth in mind, PHP’s creators built an extensible architecture that enables developers to easily add support for new technologies
to the language through modular extensions. This extensibility keeps PHP fresh and always at the cutting edge of new technology. To illustrate this, consider
what PHP lets you do through its add-on modules: dynamically create image, PDF, and SWF files; connect to IMAP and POP3 servers; interface with MySQL, Oracle, PostgreSQL, and SQLite databases; handle electronic payments; parse XML documents; and execute Perl, Java, and COM code through a PHP script. And as if all that wasn’t enough, there’s also an online repository of free PHP classes called PEAR, the PHP Extension and Application Repository, which provides a source of reusable, bug-free PHP components.
XML and Database Support :
Regardless of whether your web application sources its data from an XML file or a database, PHP has you covered. PHP 5.0 comes with an improved MySQL extension that enables you to take advantage of new features in the MySQL RDBMS (including sub queries, transactions, and referential integrity), and the language also supports DB2, PostgreSQL, Oracle, mSQL, MS-SQL, Informix, Sybase, and SQLite. Alternatively, if it’s XML you’re after, PHP 5.0 offers a completely redesigned XML API built around the libxml2 toolkit; this API supports SAX, DOM, and XSLT, as well as the new SimpleXML and SOAP extensions.
"Hello World" Script in PHP :
To get a feel for PHP, first start with simple PHP scripts. first we will create a friendly little "Hello, World!" script. As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML you'll have PHP statements like this:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!"; ?>
</body>
</html>
It will produce following result:
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is not present in the file sent from the server to yourWeb browser. All of the PHP present in the Web page is processed and stripped from the page; the only thing returned to the client from the Web server
is pure HTML output.
All PHP code must be included inside one of the three special markup tags recognised by the PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
|
|
This section will give you an idea about basic PHP syntax.
Escaping to PHP:
How does the PHP parser recognize PHP code inside your HTML document? The answer is that you tell the program when to spring into action by using special PHP tags at the beginning and end of each PHP section. This process is called escaping from HTML or escaping into PHP.
There are four styles of PHP tags and different rationales for using them. Part of the decision, however, is simply individual preference: what the individual programmer is comfortable with or what a team has decided upon for reasons of their own.
Canonical PHP tags :
The most universally effective PHP tag style is:
|
<?php ... ?> |
If you use this style, you can be positive that your tags will always be correctly interpreted.
Short-open (SGML-style) tags :
Short or short-open tags look like this:
<? .... ?>
Short tags are, as one might expect, the shortest option. Those who escape into and out of HTML frequently in each script will be attracted by the prospect of fewer keystrokes; however, the price of shorter tags is pretty high. You must do one of two things to enable PHP to recognize the tags:
- Choose the --enable-short-tags configuration option when you’re building PHP.
- Set the short_open_tag setting in your php.ini file to on. This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.
ASP-style tags :
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style tags look like this:
|
<% ... %> |
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
HTML script tags:
HTML script tags look like this:
|
<script language="PHP">...</script> |
Jumping in and out of PHP mode :
At any given moment in a PHP script, you are either in PHP mode or you’re out of it in HTML. There’s no middle ground. Anything within the PHP tags is PHP; everything outside is plain HTML, as far as the server is concerned. You can escape into PHP mode by using php tags as necessary. For example:
<?php $id = 1; ?>
<FORM METHOD=”POST” ACTION=”registration.php””>
<P>First name:
<INPUT TYPE=”TEXT” NAME=”firstname” SIZE=”20”>
<P>Last name:
<INPUT TYPE=”TEXT” NAME=”lastname” SIZE=”20”>
<P>Rank:
<INPUT TYPE=”TEXT” NAME=”rank” SIZE=”10”>
<INPUT TYPE=”HIDDEN” NAME=”serial number” VALUE=”<?php echo $id; ?>”>
<INPUT TYPE=”submit”SUBMIT” VALUE=”INPUT””>
</FORM>
Notice that things that happened in the first PHP mode instance — in this case, a variable being assigned — are still valid in the second.
Comments in PHP :
A comment is the portion of a program that exists only for the human reader and stripped out before displaying the programs result. There are two commenting formats in PHP:
Single-line comments:
They are generally used for short explanations or notes relevant to the local code. Here are the examples of single line comments.
|
<?php # This is a comment, and # This is the second line of the comment // This is a comment too. Each style comments only print "An example with single line comments"; ?>
They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here are the example of multi lines comments.
PHP is whitespace insensitive: Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent:
Yeah it is true that PHP is a case sensitive language. Try out following example:
|
Statements are expressions terminated by semicolons:
A statement in PHP is any expression that is followed by a semicolon (;).Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program. Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called $greeting:
|
$greeting = "Welcome to PHP!"; |
Expressions are combinations of tokens:
The smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159), strings (.two.), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like if, else, while, for and so forth
Braces make blocks:
Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go by enclosing them in a set of curly braces.
Here both statements are equivalent:
|
if (3 == 2 + 1) print("Good - I haven't totally lost my mind.<br>"); if (3 == 2 + 1) { print("Good - I haven't totally"); print("lost my mind.<br>"); } |
Running PHP Script from Command Prompt:
you can also run your PHP script on your command prompt. Assuming you have following content in test.php file
|
<?php echo "Hello world !!!"; ?> |
Now run this script as command prompt as follows:
|
$ php test.php |
It will produce following result:
|
Hello world!!! |
|
|
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
PHP has a total of eight data types which we use to construct our variables:
The first five are simple types, and the next two (arrays and objects) are compound - the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
We will explain only simple data type in this chapters. Array and Objects will be explained separately.
Integers:
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so:
|
$int_var = 12345; $another_int = -12345 + 12345; |
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles:
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code:
|
$many = 2.2888800; $many_2 = 2.2111200; $few = $many + $many_2; print(.$many + $many_2 = $few<br>.); |
It produces the following browser output:
|
2.28888 + 2.21112 = 4.5 |
Boolean:
They have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which can be used like so:
|
if (TRUE) print("This will always print<br>"); else print("This will never print<br>"); |
Interpreting other types as Booleans:
Here are the rules for determine the "truth" of any value not already of the Boolean type:
Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.
|
$true_num = 3 + 0.14159; $true_str = "Tried and true" $true_array[49] = "An array element"; $false_array = array(); $false_null = NULL; $false_num = 999 - 999; $false_str = ""; |
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
|
$my_var = NULL; |
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed:
|
$my_var = null; |
A variable that has been assigned NULL has the following properties:
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid examples of string
|
$string_1 = "This is a string in double quotes"; $string_2 = "This is a somewhat longer, singly quoted string"; $string_39 = "This string has thirty-nine characters"; $string_0 = ""; // a string with zero characters |
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
|
<?php $variable = "name"; $literally = 'My $variable will not print!\\n'; print($literally); $literally = "My $variable will print!\\n"; print($literally); ?> |
This will produce following result:
|
My $variable will not print!\n My name will print |
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:
The escape-sequence replacements are:
Here Document:
You can assign multiple lines to a single string variable using here document:
|
<?php $channel =<<<_XML_ <channel> <title>What's For Dinner<title> <link>http://menu.example.com/<link> <description>Choose what to eat tonight.</description> </channel> _XML_; echo <<<END This uses the "here document" syntax to output multiple lines with variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! <br /> END; print $channel; ?> |
This will produce following result:
|
This uses the "here document" syntax to output multiple lines with variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! <channel> <title>What's For Dinner<title> <link>http://menu.example.com/<link> <description>Choose what to eat tonight.</description> |
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
Local Variables:
A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function:
|
<?php $x = 4; function assignx () { $x = 0; print "\$x inside function is $x. } assignx(); print "\$x outside of function is $x. ?> |
This will produce following result.
|
$x inside function is 0. $x outside of function is 4. |
Function Parameters:
Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be:
|
<?php // multiply a value by 10 and return it to the caller function multiply ($value) { $value = $value * 10; return $value; } $retval = multiply (10); Print "Return value is $retval\n"; ?> |
This will produce following result.
|
Return value is 100 |
Global Variables:
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.
Consider an example:
|
<?php $somevar = 15; function addit() { GLOBAL $somevar; $somevar++; print "Somevar is $somevar"; } addit(); ?> |
This will produce following result.
|
Somevar is 16 |
Static Variables:
The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
|
<?php function keep_track() { STATIC $count = 0; $count++; print $count; print " } keep_track(); keep_track(); keep_track(); ?> |
This will produce following result.
|
1 2 3 |
Variable Naming:
Rules for naming a variable is:
There is no size limit for variables.
Constants in PHP:
A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default a constant is case-sensitiv. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically.
constant() function:
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.
constant() example:
|
<?php define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?> |
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables are:
Valid and invalid constant names:
|
// Valid constant names define("ONE", "first thing"); define("TWO2", "second thing"); define("THREE_3", "third thing") // Invalid constant names define("2TWO", "second thing"); define("__THREE__", "third value"); |
PHP Magic constants:
PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:
A few "magical" PHP constants ate given below:
|
Name |
Description |
|
__LINE__ |
The current line number of the file. |
|
__FILE__ |
The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances. |
|
__FUNCTION__ |
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
|
__CLASS__ |
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
|
__METHOD__ |
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive). |
|
|
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
Lets have a look on all operators one by one.
Arithmatic Operators:
There are following arithmatic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
|
Operator |
Description |
Example |
|
+ |
Adds two operands |
A + B will give 30 |
|
- |
Subtracts second operand from the first |
A - B will give -10 |
|
* |
Multiply both operands |
A * B will give 200 |
|
/ |
Divide numerator by denumerator |
B / A will give 2 |
|
% |
Modulus Operator and remainder of after an integer division |
B % A will give 0 |
|
++ |
Increment operator, increases integer value by one |
A++ will give 11 |
|
-- |
Decrement operator, decreases integer value by one |
A-- will give 9 |
Comparison Operators:
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
|
Operator |
Description |
Example |
|
== |
Checks if the value of two operands are equal or not, if yes then condition becomes true. |
(A == B) is not true. |
|
!= |
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
(A != B) is true. |
|
> |
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
(A > B) is not true. |
|
< |
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
(A < B) is true. |
|
>= |
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
(A >= B) is not true. |
|
<= |
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
(A <= B) is true. |
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
|
Operator |
Description |
Example |
|
and |
Called Logical AND operator. If both the operands are true then then condition becomes true. |
(A and B) is true. |
|
or |
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. |
(A or B) is true. |
|
&& |
Called Logical AND operator. If both the operands are non zero then then condition becomes true. |
(A && B) is true. |
|
|| |
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. |
(A || B) is true. |
|
! |
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
!(A && B) is false. |
Assignment Operators:
There are following assignment operators supported by PHP language:
|
Operator |
Description |
Example |
|
= |
Simple assignment operator, Assigns values from right side operands to left side operand |
C = A + B will assigne value of A + B into C |
|
+= |
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
C += A is equivalent to C = C + A |
|
-= |
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
C -= A is equivalent to C = C - A |
|
*= |
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
C *= A is equivalent to C = C * A |
|
/= |
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
C /= A is equivalent to C = C / A |
|
%= |
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
C %= A is equivalent to C = C % A |
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax:
|
Operator |
Description |
Example |
|
? : |
Conditional Expression |
If Condition is true ? Then value X : Otherwise value Y |
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
Precedence of PHP Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2;
Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
|
Category |
Operator |
Associativity |
|
Unary |
! ++ -- |
Right to left |
|
Multiplicative |
* / % |
Left to right |
|
Additive |
+ - |
Left to right |
|
Relational |
< <= > >= |
Left to right |
|
Equality |
== != |
Left to right |
|
Logical AND |
&& |
Left to right |
|
Logical OR |
|| |
Left to right |
|
Conditional |
?: |
Right to left |
|
Assignment |
= += -= *= /= %= |
Right to left |
|
|
Branching :
The two main structures for branching are if and switch. The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions. PHP supports following threedecision making statements:
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
Syntax
|
if (condition) code to be executed if condition is true; else code to be executed if condition is false; |
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
|
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } else { echo "Have a nice day!"; } ?> </body> </html>
If you want to execute some code if one of several conditions are true use the elseif statement
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lables match then statement will will execute any specified default code.
Looping : Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
The for statement is used when you know how many times you want to execute a statement or a block of statements.
|
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example 1 :
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
|
<html> <body> <?php $a = 0; $b = 0; for( $i=0; $i<5; $i++ ) { $a += 10; $b += 5; } echo ("At the end of the loop a=$a and b=$b" ); ?> </body> </html> |
This will produce following result:
|
At the end of the loop a=50 and b=25 |
Example 2 :
//The following code shows all prime numbers within the range of 1-100
<?php
$str=1;
$end=100;
$cntr=1;
$inr=1;
for($cntr=$str;$cntr<=$end;$cntr++)
{
for($inr=2;$inr<$cntr;$inr++)
{
if($cntr % $inr == 0)
{
echo "Not Prime No:= ".$cntr."<br/>";
break;
}
else if($inr == $cntr-1)
{
echo "<p style=color:Red;>Prime No:= ".$cntr."</p><br/>";
}
}
}
?>
The while loop statement
The while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Syntax
|
while (condition) { code to be executed; } |
Example 1 :
This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
|
<html> <body> <?php $i = 0; $num = 50; while( $i < 10) { $num--; $i++; } echo ("Loop stopped at i = $i and num = $num" ); ?> </body> </html> |
This will produce following result:
|
Loop stopped at i = 1 and num = 40 |
Example 2 :
// following code shows whether the given number is palindrome or not.
<?php
$pal_Num=552055;
$cp_Pal=$pal_Num;
$cal_Pal=0;
while($cp_Pal > 1)
{
$cal_Pal = $cal_Pal * 10;
$cal_Pal = $cal_Pal + ($cp_Pal % 10);
//echo "<p style=color:red>Y=".$cal_Pal."<p/>";
$cp_Pal = $cp_Pal / 10;
//echo "<br/>X=".$cp_Pal;
}
if($pal_Num == $cal_Pal)
{
echo "<p style=color:green>".$cal_Pal." is Palindrome</p>";
}
else
{
echo "<p style=color:Red>".$pal_Num." is not Palindrome</p>";
}
?>
The do...while loop statement
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
Syntax
|
do { code to be executed; }while (condition); |
Example :
$count = 45;
do
{
print(“count is $count<BR>”);
$count = $count + 1;
}
while ($count <= 10);
prints the single line:
count is 45
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Syntax
|
foreach (array as value) { code to be executed; } |
Example
Try out following example to list out the values of an array.
|
<html> <body> <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { echo "Value is $value <br />"; } ?> </body> </html> |
This will produce following result:
|
Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 |
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
|
<html> <body> <?php $i = 0; while( $i < 100) { $i++; if( $i == 25 )break; } echo ("Loop stopped at i = $i" ); ?> </body> </html> |
This will produce following result:
|
Loop stopped at i = 25 |
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
|
<html> <body> <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { if( $value == 3 )continue; echo "Value is $value <br />"; } ?> </body> </html> |
This will produce following result
|
Value is 1 Value is 2 Value is 4 Value is 5 |
|
|
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an index.
Numeric Array
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.
|
<html> <body> <?php /* First method to create array. */ $numbers = array( 1, 2, 3, 4, 5); foreach( $numbers as $value ) { echo "Value is $value <br />"; } /* Second method to create array. */ $numbers[0] = "one"; $numbers[1] = "two"; $numbers[2] = "three"; $numbers[3] = "four"; $numbers[4] = "five"; foreach( $numbers as $value ) { echo "Value is $value <br />"; } ?> </body> </html> |
This will produce following result:
|
Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 Value is one Value is two Value is three Value is four Value is five |
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
Example
|
<html> <body> <?php /* First method to associate create array. */ $salaries = array( "mohammad" => 2000, "qadir" => 1000, "zara" => 500 ); echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; echo "Salary of qadir is ". $salaries['qadir']. "<br />"; echo "Salary of zara is ". $salaries['zara']. "<br />"; /* Second method to create array. */ $salaries['mohammad'] = "high"; $salaries['qadir'] = "medium"; $salaries['zara'] = "low"; echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; echo "Salary of qadir is ". $salaries['qadir']. "<br />"; echo "Salary of zara is ". $salaries['zara']. "<br />"; ?> </body> </html> |
This will produce following result:
|
Salary of mohammad is 2000 Salary of qadir is 1000 Salary of zara is 500 Salary of mohammad is high Salary of qadir is medium Salary of zara is low |
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
|
<html> <body> <?php $marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ), "qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ), "zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) ); /* Accessing multi-dimensional array values */ echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />"; echo "Marks for qadir in maths : "; echo $marks['qadir']['maths'] . "<br />"; echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . "<br />"; ?> </body> </html> |
This will produce following result:
|
Marks for mohammad in physics : 35 Marks for qadir in maths : 32 Marks for zara in chemistry : 39 |
Simple Array Functions :
// following code will show you various functions of array
<?php
$x[0]=123;
$x['color']="green";
$x[40]="abc";
//$ary=array();
//echo $x[39];die();
$v=array(0=>123,'color'=>'green',40=>"abc");
$v1=array(12,13,14,15,16);
$t=array(3,5,7,9,0=>5,'color'=>"green",10,40=>"qbc",45);
//echo $t[41];die();
$a=range(2010,1990);
//print_r($a);
//die();
$tmp['fybca'][1][1]="ajay";
$tmp['fybca'][1][2]="sanjay";
$tmp['fybca'][2][10]="suuny";
$tmp['sybca'][1][2]="ravi";
$tmp['tybca'][1][3]="ajay";
print_r($tmp);die();
$tmp1=array('fybca'=>array(1=>array(1=>"ajay",2=>"sanjay"),2=>array(10=>"sunny")),"sybca"=>array(1=>array(2=>"ravi")));
//echo $tmp[0]mp1
//print_r($tmp);
//die();
// using array() construct
$a=array();
$a=array(1,2,"hqyxt",'d',5,8);
//echo $a[2];
$ary=array('color' => "green", 0 => "name" , 3 => 10);
echo $ary[3];
$t=array(0=>10, 1=> 20 , 30,40,50, 5=>60);
echo "<br>".$t[3];
$tmp['fruit']['red'][0]="apple";
$tmp['fruit']['red'][1]="lichhi";
$tmp['vegi'][0]="potato";
$tmp['vegi']['red'][1]="tometo";
echo $tmp['fruit'][0];
print_r($tmp);
//die();
$tmp1=array('fruit' => 0,'color'=>4);
echo "<br>";
print_r($tmp1);
//die();
// list()
$fruit_basket = array('apple', 'orange', 'banana',189,2,2);
list($red_fruit, $orange_fruit,$abc,$cc) = $fruit_basket;
//$red_fruit = $fruit_basket[0];
//$orange_fruit=$fruit_basket[1];
echo $cc."<br>";
//die();
echo "<br> Array status :".is_array($fruit_basket)."<br>";
//die();
echo count($fruit_basket)."<br>";
//die();
//unset($fruit_basket[0]);
//echo count($fruit_basket)."<br>";die();
$red_fruit1='orange';
print_r($fruit_basket);
echo count($fruit_basket)."<br>";
echo "in_array() -> ".in_array($red_fruit1, $fruit_basket);
//die();
//unset($fruit_basket);
//echo is_array($fruit_basket)." ss <br>";
//echo count($fruit_basket)."<br>";
//echo sizeof($fruit_basket)."<br>";
echo "<br> using current and next <br>";
echo "current() === > ".current($fruit_basket)."<br>";
echo "next() ===> ".next($fruit_basket)."<br>";
echo "current() === > ".current($fruit_basket)."<br>";
echo "prev() === > ".prev($fruit_basket)."<br>";
echo "end() === > ".end($fruit_basket)."<br><br>";//die();
reset($fruit_basket);
while ( $res = each($fruit_basket))
{
echo $res[0]." --> ".$res[1]."<br>";
}
reset($fruit_basket);
echo array_search("orange",$fruit_basket); // returns the key of specified value
die();
$tmp=range(1,10);
echo next($tmp)."<br>";
echo next($tmp)."<br>";
echo prev($tmp)."<br>";
echo end($tmp1)."<br>";
echo $fruit_basket;
// accessing array using foreach loop
foreach($fruit_basket as $d)
{
echo "<br>".$d;
}
?>
Advanced Array Functions :
<?php
// following is the list of some advanced array functions.
$ary1=array(1,2,3,4,5,0=>6);
$ary=array("name" => "xyz", "lname" => "abcd", "addr"=>"aaaa", "pin" => "009123",0=>4);
print_r($ary);
echo "<br>";
$n_ary=array_keys($ary); // returns array having all the keys of the specified array
print_r($n_ary);
echo "<br>";
$v_ary=array_values($ary); //returns array having all the values of the specified array
print_r($v_ary);
echo "<br>";
$v_ary=array_flip($ary); //returns array... it flips the key-values that is all the keys becomes values and all values
becomes keys
print_r($v_ary);
echo "<br>";
$v_ary=array_reverse($ary); //accept array as argument and return reverse array
print_r($v_ary);
echo "<br>";
//rand();
//$z=shuffle($ary1); //randomize the values
//echo $z;
print_r($ary1);
echo "<br>";
$v_ary=array_merge($ary,$ary1); //merge two array and returns new array
print_r($v_ary);
echo "<br>";
$str="this is php example";
$n_str=explode(" ",$str);// returns an array of specific string saparated by a given delimeter
print_r($n_str);
$o_str=implode("+",$n_str); //returns a string from the elements of an array
echo "<br>$o_str<br>";
$s_ary=array_slice($ary,1,-1); // same as substr excepts it operates on array
print_r($s_ary);
?>
|
|
Strings are sequences of characters that can be treated as a unit assigned to variables, given as input to functions, returned from functions, or sent as output to appear on your user’s Web page. The simplest way to specify a string in PHP code is to enclose it in quotes, whether single quotes (‘) or double quotes (“), like this:
$my_string = ‘A literal string’;
$another_string = “Another string”;
The difference between single and double quotes lies in how much interpretation PHP does of the characters between the quote signs before creating the string itself. If you enclose a string in single quotes, almost no interpretation will be performed; if you enclose it in double quotes, PHP will splice in the values of any variables you include, as well as make substitutions for certain special character sequences that begin with the backslash (\) character.
For example,
if you evaluate the following code in the middle of a Web page:
$statement = ‘everything I say’;
$question_1 =
“Do you have to take $statement so literally?\n<BR>”;
$question_2 =
‘Do you have to take $statement so literally?\n<BR>’;
echo $question_1;
echo $question_2;
It will give following output :
Do you have to take everything I say so literally?
Do you have to take $statement so literally?\n
The following example will give you an idea about various string functions used in php. Test it yourself, remove comment of die() function and test it section by section.
Example :
<?php
$sport='vollyball';
$a = "i will play $sport in the\t summer<br>";
echo $a;
//die();
//interpolation with curly braces
$sport1 = 'volly';
$b = "i will play {$sport1}ball in the summer<br>";
echo $b;
//die();
$c="i like cricket but ";
$c.=$b;
echo $c."<br>";
//die();
$my_string="Double";
echo $my_string[4]."<br>";
//die();
for($i=0;$i<6;$i++)
{
$s=$my_string{$i};
echo $s."<br>";
}
//die();
//------------------------------------------------------//
// heredoc in php
$str = <<<_AAAA
<br>
This is a
demo message
$my_string
with heredoc.
<h1>ashdfjasd</h1><br>
<b>a;sjdajsdajsdasd</b>
<table border="1">
<tr><td>adsfsd</td></tr><tr><td>sdfa</td></tr>
<table>
_AAAA;
$cnt=1;
if($cnt ==1)
{
echo $str;
}
else
{
echo 1;
}
//die();
//-----------------------------------------------------//
/* example of substr function */
$str = "hello world";
echo strlen($str)."<br>";
echo $str."<br>";
echo substr($str,4)."<br>";
//die();
echo substr($str,4,4)."<br>";
//die();
echo substr($str,-7)."<br>";
//die();
echo substr($str,4,-2)."<br>";
//die();
echo substr($str,-4,-2)."<br>";
//die();
// ------------------------------------ //
// examples of string searching //
$str1 = " example of string searching ";
echo $str1."<br>";
echo strrpos($str1,'s')."<br>";
//die();
echo strcmp("sbr","sar")."<br>";
//die();
echo strlen($str1)."<br>";
//die();
//-----------------------------------------------------//
/// string cleanup functions ///
$str2=chop($str1);
echo strlen($str2)."<br>";
//die();
$str3=trim($str1);
echo strlen($str3)."<br>";
//die();
$str4=ltrim($str1);
echo strlen($str4)."<br>";
//die();
$str5=rtrim($str1);
echo strlen($str5)."<br>";
//die();
////////////////////////////////////
// string replace functions //////
$str_replace1="burma is similer to rhodesia in at least one way.";
$edit1=str_replace("rhodesia","zimbabwe",$str_replace1);
$edit2=str_replace("burma","myanmar",$edit1);
echo $edit2."<br>";
//die();
echo "<br>example of substr_replace function...<br>";
echo substr_replace("abcdefg","-",2,1)."<br>";
//die();
echo "<br>example of str_repeat function...<br>";
echo str_repeat("-",50)."<br>";
//die();
echo strrev("abc")."<br>";
//die();
echo strtolower("ABC asdas asdDasdasd")."<br>";
echo ucwords("this is an example of title case ")."<br>";
//die();
echo ucfirst("sdfsdf sggf fgsds Wsdfds");
//die();
////////////////////////////////////////
echo "<br>email";
$a= 500.45555;
printf("%.2f",$a);
$email = 'name@example.com';
$domain = strstr($email, '@');
echo "<br>".$domain;
//die();
$t="<br>He said, \'i' m fine.\ These characters ($,*) are very special to me \n<br>";
echo "<br>".addslashes($t);
echo "<br>".stripslashes($t);
echo "<br>".quotemeta($t);
?>
|
|
There are two ways the browser client can send information to the web server.
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. Like,
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET Method :
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
|
http://www.sunnygajjar.com/index.html?name1=value1&name2=value2 |
The POST Method :
The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
Example :
//following code shows how to pass data between pages using php's superglobal
<?php
if(isset($_POST['submit']))
{
$name=$_POST['t1'];
$email=$_POST['t2'];
echo $name."<br>";
echo $email;
}
else
{
?>
<html>
<head></head>
<body>
<form action="" method="post">
Name: <input type="text" name="t1"><br>
E-mail: <input type="text" name="t2"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
}
?>
PHP Superglobal :
$_SERVER :-
The $_SERVER superglobal gives access to the WebSphere sMash Server attributes and a few HTTP request attributes. The complete list of
keys that are currently supported includes :
$_SERVER['HTTP_ACCEPT_CHARSET'] - The value of the Acccept-Charset header
$_SERVER['HTTP_USER_AGENT'] - The value of the User-Agent header
$_SERVER['REMOTE_ADDR'] - The IP address of the client making the request
$_SERVER['REMOTE_HOST'] - The host name of the client making the request
$_SERVER['REMOTE_PORT] - The port number of the client making the request
$_SERVER['SCRIPT_FILENAME'] - The file name of the script being invoked
$_SERVER['SCRIPT_NAME'] - The name of the script being invoked
$_SERVER['SERVER_PORT'] - The port number that the server accepted the request on
$_SERVER['REQUEST_METHOD'] - The HTTP method of the request
$_SERVER['REQUEST_URI'] - The URI associated with the HTTP request
$_SERVER['REQUEST_TIME'] - The time stamp when the request was dispatched to the script
$_GET :-
The $_GET variable is used to access URL query parameters associated with an HTTP request. URL query parameters are most commonly
used for HTTP GET requests, but they are in fact supported for all HTTP request types. For the following request:
/search?title=Rose&author=Eco
$_GET['title'] will have the value "Rose"
$_GET['author'] will have the value "Eco"
$_POST :-
The $_POST variable is similar to the $_GET variable except that it processes the body of the HTTP POST request if the content type
of the body is application/x-www-form-urlencoded.
$_COOKIE :-
The $_COOKIE variable allows the script developer to query the cookies that were sent by the client for the request. If the cookie
key uses the '[]' notation to denote an array accessor, the cookie values can be accessed through PHP arrays.
$_SESSION :-
An associative array containing session variables available to the current script.
$_REQUEST :-
The $_REQUEST variable provides the contents of the $_GET, $_POST, and $_COOKIE arrays. Note that if a parameter with the same name
appears in two (or three) of the individual arrays, the value for that parameter in $_REQUEST is undefined.
$_FILES :-
The $_FILES variable contains information about any files that were uploaded during the current HTTP request. Given the following HTML form:
<form action="http://localhost:8080/testupload.php">
<input type="file" name="myfile"/>
</form>
The $_FILES variable can be accessed by the following script:
<?php
echo $_FILES['myfile']['name'] . "\n"; // name of the file on the client
echo $_FILES['myfile']['type'] . "\n"; // content type - text/plain
echo $_FILES['myfile']['size'] . "\n"; // file length
echo $_FILES['myfile']['tmp_name'] . "\n"; // path to the temporary file on the server
echo $_FILES['myfile']['error'] . "\n"; // error code
?>
|
|
you can add PHP to your HTML is by putting it in a separate file and calling it by using PHP’s include functions. There are four include functions:
- include(‘/filepath/filename’)
- require(‘/filepath/filename’)
- include_once(‘/filepath/filename’)
- require_once(‘/filepath/filename’)
In previous versions of PHP, there were significant differences in functionality and speed between the include functions and the require functions. This is no longer true; the two sets of functions differ only in the kind of error they throw on failure. Include() and include_once() will merely generate a warning on failure, while require() and require_once() will cause a fatal error and termination of the script.
As suggested by the names of the functions, include_once() and require_once() differ from simple include() and require() in that they will allow a file to be included only once per PHP script. This is extremely helpful when you are including files that contain PHP functions, because redeclaring functions results in an automatic fatal error. In larger PHP systems, it’s quite common to include files which include other files which include other files — it can be difficult to remember whether you’ve included a particular function before, but with include_once() or require_once() you don’t have to.
Example :
<html>
<title>This is an example to show how to include PHP file! </title>
<body>
<div id="header">
<?php
include_once("menu.php");
?>
</div>
<div id="contant">
<?php
include_once("contant.php");
?>
</div>
<div id="foot">
<?php
include_once("footer.php");
?>
</div>
</body>
</html>
|
|
What is a function?
A function is a way of wrapping up a chunk of code and giving that chunk a name, so that you can use that chunk later in
just one line of code. Functions are most useful when you will be using the code in more than one place, but they can be helpful even
in one-use situations,because they can make your code much more readable.
syntax:
function function-name ($argument-1, $argument-2, ..)
{
statement-1;
statement-2;
...
}
That is, function definitions have four parts:
- The special word function
- The name that you want to give your function
- The function's parameter lists dollar-sign variables separated by commas
- The function body a brace-enclosed set of statements
Examples :
// following are the examples of user-defined functions
<?php
// this function is used to find factorial of a given number
function factorial($a)
{
$fact=1;
for($i=$a;$i>=1;$i--)
{
$fact = $fact * $i;
}
return $fact;
}
// --------------------------------------------------//
// This function is used to display fibonacci series
function fibonacci($fibo)
{
$a=1;
$b=0;
$c=0;
echo "Fibonacci No.:<br/>";
for($i=0;$i<=$fibo;$i++)
{
$c=$a+$b;
echo "$c<br/>";
$a=$b;
$b=$c;
}
}
$fac=factorial(5); // function call
echo"Factorial = ".$fac."<br/>";
fibonacci(10); // function call
// --------------------------------------------------//
// This function is used to calculate factorial of a given number using recursion
function fact_recursion($facto)
{
$fa=1;
if($facto == 0)
{
return $fa;
}
else
{
$fa=fact_recursion($facto-1) * $facto;
return $fa;
}
}
function val1() // function shows the return value
{
return 10;
}
$recur=fact_recursion(val1()); // function call
echo "Factorial No. :".$recur;
?>
// function with default values as parameter
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
// ------------------------------------------------//
// Passing arguments by reference
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
|
|
A cookie is a small piece of information that is retained on the client machine, either in the browser's application memory or as a small file written
to the user's hard disk.
It contains a name/value pair setting a cookie means associating a value with a name and storing that pairing on the client side. Getting or reading
a cookie means using the name to retrieve the value. each browser will typically accept only 20 cookies from each domain before it starts popping old cookie
values off the stack.
cookies are set using the setcookie() function, and cookies are read by superglobal array $_COOKIE, with the cookie name as an index, and the value
it indexes
Syntax :
setcookie(name,value,time,path,domain,secure)
name : The name of the cookie.
value : The value you want to store in the cookie.
time : Specifies when this cookie should expire.
path : In the default case, any page within the Web root folder would see and be able to set this named cookie. Setting the path to a subdirectory
(for example, "/forum/") allows distinguishing cookies that have the same name but are set by different sites or subareas of the Web server.
domain : In the default case, no check is made against the domain requested by the client. If this argument is nonempty, then the domain must match
secure : Defaults to 0. If this argument is 1, the cookie will only be sent over a secure socket (aka SSL or HTTPS) connection.
Example :
setcookie("name", "abcd", time() + (60 * 60), "/", "www.abc.com" , 1 );
Deleting cookies :
Deleting a cookie is easy. Simply call setcookie(), with the exact same arguments as when you set it, except the value, which should be set to an
empty string. This does not set the cookie's value to an empty strings it actually removes the cookie. Remember: If you used the path or domain arguments
to set the cookie, you need to use them to unset the cookie too.
setcookie(name,null,-1)
here, name is the name of the cookie, value set to null and time set to -1 this will delete a perticular cookie
Reading Cookie :
echo $_COOKIE['name'];
$_COOKIE['name'] = value;
$_COOKIE superglobal array is used to access and change the value stored in cookie.
Example of cookie:
This example shows how cookies are implemented in php.
// save the following file as "cookie1.php"
<?php
if(isset($_POST['submit']))
{
$user = $_POST['user'];
$color = $_POST['color'];
if( ( $user != null ) and ( $color != null ) )
{
setcookie( "firstname", $user , time() + 500); //set cookie firstname for 500 seconds
setcookie( "fontcolor", $color, time() + 500 );//set cookie fontcolor for 500 seconds
header( "Location: cookie2.php" ); //redirect to cookie2.php page
exit();
}
}
else
{
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Stuff by tedd</title>
</head>
<body>
<h1>cookie stuff</h1>
<hr>
<form action ="" method = "post">
Please enter your first name:
<input type = "name" name = "user"><br><br>
Please choose your favorite font color:<br>
<input type = "radio" name = "color" value = "Red">Red
<input type = "radio" name = "color" value = "Green">Green
<input type = "radio" name = "color" value = "Blue">Blue
<br><br>
<input type = "submit" value = "submit" name="submit">
</form>
<br/>
<hr>
</body>
</html>
</html>
<?php
}
?>
// save following code as "cookie2.php", this shows how to access cookie value
<?php
if (isset($_COOKIE['firstname']))
{
$user = $_COOKIE['firstname'];
$color= $_COOKIE['fontcolor'];
}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Stuff by tedd</title>
</head>
<body>
<h1>show cookie stuff</h1>
<hr>
<h2>Hello: <?php echo( $user ); ?> </h2>
<h2>Your color: <?php echo( $color ); ?> </h2>
<input type="password" value="<?php echo $user; ?>">
<hr>
<br/>
<?php
// Another way to debug/test is to view all cookies
echo ("<br/>");
echo ("<pre>");
echo ("Cookie info:\n");
print_r($_COOKIE);
echo("</pre>");
?>
<p>
<a><input type="button" value="back" onclick="history.go(-1)"></a>
</p>
</body>
</html>
|
|
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one
single user, and are available to all pages in one application.
PHP Session Variables :
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you
are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc).
However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store
the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
Starting a PHP Session:
Before you can store user information in your PHP session, you must first start up the session.
The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.
Storing a Session Variable :
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set.
If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session :
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
|
|
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
- make a file upload_file.php, used to submit the file
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
- now make upload.php file to handle the file upload.
- The code fragment below shows you how to upload a perticular file on server.
<?php
// this code can only accept gif,jpeg and pjpeg files and also having the length less then 50kb.
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 50000)
)
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("up/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"up/".$_FILES["file"]["name"]);
echo "Stored in : " . "up/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Notice the following about the HTML form above:
* The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form
requires binary data, like the contents of a file, to be uploaded
* The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be
a browse-button next to the input field
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
* $_FILES["file"]["name"] - the name of the uploaded file
* $_FILES["file"]["type"] - the type of the uploaded file
* $_FILES["file"]["size"] - the size in bytes of the uploaded file
* $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
* $_FILES["file"]["error"] - the error code resulting from the file upload
|
|