PHP Unit I Full
PHP Unit I Full
UNIT-1
PHP OVERVIEW
• PHP - Hypertext Preprocessor
• Developed by Rasmus Lerdorf in 1994
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML
• PHP files have extension ".php"
• PHP is a server scripting language, and 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.
• PHP 7 is the latest stable release.
• Functions:
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, 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 be used to control user-access
• PHP can encrypt data
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
• PHP supports 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.
Instead of lots of commands to output HTML (as seen
in C or Perl), PHP pages contain HTML with embedded
code that does "something" (like in the next slide, it
outputs "Hi, I'm a PHP script!").
The PHP code is enclosed in special start and end
processing instructions <?php and ?> that allow you to
jump into and out of "PHP mode."
It renders as HTML that looks like this:
PHP code is executed on the server, generating HTML
which is then sent to the client.
The client would receive the results of running that
script, but would not know what the underlying code
was.
PHP Introduction
•On windows, you can download and install WAMP. With one
installation and you get an Apache webserver, database server and php.
•http://www.wampserver.com
echo $oxo[1][2];
?>
Output: x
• Third element in the second row of the array
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
• Program:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output:
• Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
• Variable-naming rules:
• The variable name must start with a letter of the alphabet or the _
character.
• It can contain only the characters a-z, A-Z, 0-9 and _ character.
• It may contain spaces. If variable contains more than one word, it
should be separated with the _ character (e.g.$user_name)
• It is case sensitive.
OPERATORS
• The mathematical, string, comparison and logical commands such as
plus, minus, multiply and divide.
• PHP looks like a plain arithmetic.
• Ex: echo 6 + 2;
• TYPES:
• Arithmetic Operators:
• Four operations - +,-,/, modules
Operator Description Example
+ Addition $j + 1
- Subtraction $j - 6
* Multiplication $j * 11
/ Division $j/4
% Modulus (division remainder) $j%9
++ Increment ++$j
-- Decrement --$j
• Assignment Operators
• These operators are used to assign values to variables. They start with
simple = and move on to +=, -=, and so on.
• The operator += adds the value on the right side to the variable on
the left, instead of totally replacing the value on the left.
• Ex: $count +=1; sets count to 6. (If count value starts with value 5).
• Strings have their own operator, the period (.).
Operator Example Equivalent to
= $j = 15 $j = 15
+= $j += 5 $j = $j +5
-= $j - = 3 $j = $j -3
*= $j *=8 $j = $j * 8
/= $j /= 16 $j = $j / 16
.= $j .= $k $j = $j . $k
%= $j %= 4 $j = $j %4
• Comparison Operators:
• These operators are used inside a construct such as an if statement
for comparing two items.
•= - Assignment operator
• == - Comparison operator
Operator Description Example
== is equal to $j==4
!= is not equal to $j != 21
> is greater than $j > 3
< is less than $j < 100
>= is greater than or equal to $j > = 15
<= is less than or equal to $j <= 8
• Logical Operators:
Operator Description Example
&& and $j == 3 && $k ==2
and low-precedence and $j == 3 and $k == 2
|| or $j < 5 || $j > 10
or low-precedence or $j < 5 or $j > 10
! not ! ($j == $k)
xor exclusive or $j xor $k
• xor – exclusive OR returns a true value if either value is TRUE, but a
FALSE value if both inputs are TRUE or both inputs are FALSE.
• Variable Assignment: 2 syntax:
• 1. Variable = value
• 2. Other Variable = variable
• Variable Incrementing and Decrementing:
• Adding or subtracting 1 :
• ++$x;
• - -$y;
• Ex:
• If ( ++$x ==10) echo $x; (first increment and test)
• If ($y- - ==0) echo $y;
• Result: -1
• String Concatenation:
• It uses the period (.) to append one string of characters to another.
• Ex: echo “You have” . $msgs. ”messages”;
• Output: You have 5 messages
• To append one string with another, .=, like this
• $bulletin.=$newsflash;
• String types:
• Based on the type of quotation mark that we use, two types of strings
are supported.
• 1. If we wish to assign a literal string, preserving the exact contents, we
should use the single quotation mark(‘) like,
• $info = ‘Preface variables with a $ like this: $variable’;
• In this case, every character within the single-quoted string is assigned to
$info.
• If you had used double quotes, PHP would have attempted to
evaluate $variable as a variable.
• On the other hand, when you want to include the value of a variable
inside a string, you do so by using double-quoted strings.
• Echo “This week $count people have viewed your profile”;
•
O/P: This week 5 people have viewed your profile
• Escaping characters:
• Sometimes, a string needs to contain characters with special meanings
that might be interpreted incorrectly.
• Ex: $text = ‘My spelling’s atroshus’; // erroneous syntax
• The second quotation mark encountered in the word spelling’s will tell
the PHP parser that the string end has been reached. Consequently, the
rest of the line will be rejected as an error.
• To correct this, add a backslash character before the offending
quotation mark:
• $text = ‘My spelling\’s still atroshus’;
• Additionally we can use escape characters to insert various special
characters into strings such as tabs (\t), newlines(n) and carriage
returns(r).
• Ex:
• $heading = “Date\tName\tPayment”;
• Note:
• These special backslash-preceded characters work only in double-
quoted stings.
• In single-quoted strings, only the escaped apostrophe (‘\’) and escaped
backslash itself(\\) are recognized as escaped characters.
• Variable Typing:
• PHP is a loosely typed language.
• This means, that variables do not have to be declared before they are
used and PHP always converts variables to the type required by their
context when they are accessed.
• Ex:
• we can create a multiple-digit number and extract the nth digit from
it simply by assuming it to be a string.
• Ex: Automatic conversion from a number to a string
• <?php
• $number = 12345 * 67898;
• echo substr ($number,3,10);.
• ?>
• The PHP function substr asks for one character to be returned from
$number, starting at the fourth position (PHP offsets start from zero).
• Ex: Automatically converting a string to a number
<?php
$pi = “ 3.1415927”;
$radius = 5;
Echo $pi * ($radius * $radius);
?>
The variable $pi is set to a string value, which is then automatically
turned into a floating-point number in the third line by the equation for
calculating a circle’s area, which outputs the value 78.5398175.
CONSTANTS
• Similar to variables, holding information to be accessed later.
• To create a constant, use the define() function.
• Syntax
• define(name, value, case-insensitive)
define(“ROOT_LOCATION”, “/usr/local/www/”, True);
• Then to read the contents of the variable, just refer like a regular
variable (not preceded by the dollar sign).
• $directory = ROOT_LOCATION;
• Note:
• Use uppercase for constant variable names.
• Predefined Constants:
• Output:
• The current program line in the current file (including the path) being
executed to be output to the web browser.
• This is line 5 of file x.
Difference between echo and print
commands
• Print: It is a function-like construct that takes a single parameter and
has a return value (always 1), whereas echo is purely a PHP language
construct.
• Echo cannot be used as part of more complex expression, whereas
print can.
• Ex:
• $b ? Print “TRUE” : print “FALSE”;
Functions
• It is used to separate out sections of code that perform a particular task.
• Syntax:
• function functionName() {
code to be executed;
}
• Ex:
• <?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
• PHP Function Arguments:
• Information can be passed to functions through arguments. An
argument is just like a variable.
• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
• <?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
• Output:
• Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
• OUTPUT:
• Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
• Variable Scope:
• 1. Local variables
• 2. Global variables
• 3. Static variables
• 4. Superglobal variables
• Local variables:
• Variables created within and can be accessed only by a function.
• They are temporary variables that are used to store partially processed results
prior to the function’s return.
• One set of local variables is the list of arguments to a function.
• Ex:1
• <?php
• function longdate($timestamp)
• {
• $temp = date (“l F jS Y”, $timestamp); // l – day, F – month, jS-date, Y- year
• return “The date is $temp”;
• }
• ?>
• Here we have assigned the value returned by the date function to the
temporary variable $temp, which is then inserted into the string
returned by the function.
• As soon as the function returns, the value of $temp is cleared, as if it
had never been used at all.
• Ex:2
• <?php
• $temp=“The date is “; // error
• echo longdate(time());
• function longdate($timestamp)
•{
• return $temp.date(“l F jS Y”, $timestamp);
•}
• ?>
• $temp was neither created within the longdate function nor passed
to it as a parameter, longdate cannot access it.
• Therefore, this code snippet outputs only the date, not the preceding
text. In fact, it will first display the error message
• Notice: Undefined variable: temp
• Reason:
• By default, variables created within a function are local to that
function, and variables created outside of any functions can be
accessed only by non-function code.
Solutions
• EX:2 (temp as an reference)
• <?php
• $temp = “The date is “;
• echo $temp.longdate(time());
• function longdate($timestamp)
• {
• return date(“l F jS Y “, $timestamp);
• }
• ?>
• The reference to $temp is moved out of the function. The reference appears in the
same scope where the variable was defined.
• Ex:3 ($temp as an argument)
• <?php
• $temp = "The date is ";
• echo longdate($temp, time());
• while − loops through a block of code if and as long as a specified condition is true.
• do...while − loops through a block of code once, and then repeats the loop as long as
a special condition is true.