Unit Iii
Unit Iii
Introduction to PHP, Support for Database, PHP Installation, working with PHP, Why PHP?,
Basic Syntax of PHP, PHP statement terminator and case insensitivity, Embedding PHP in
HTML, Comments, Variables, assigning value to a variable, Constants, Managing Variables.
Operators: Arithmetic Operators, Bit-wise
Operators, Comparison Operators, Logical Operators, Concatenation Operator,
Incrementing/Decrementing Operator, Ternary Operator, Operator Precedence, String
Manipulation: strtoupper (), strtolower (), ucfirst (), ucwords (), strcmp (), strlen (), substr (), trim
(). Functions: Functions in PHP, User-Defined function,
Function Definition, Function Call, Function with arguments, Function with return value, call by
value and call by references, understanding variable scope, Global Variables, Static Variables,
Include and Require, Built-in functions in PHP
Introduction to PHP?
Easy to learn
o Syntax is based on C and Perl allowing easy familiarity for those who know those
languages
Object Oriented
o Starting with PHP5
o Allow for classes and objects, inheritance, interfaces, access modification, class
and method abstraction, constructors and destructors, as well as many other useful
OO features
Portable
o Available for many different operating systems
o Code written for one system will work equally well on others
Source Code
o Access to the open source code means that is a problem exists or an improvement
could be made, you are free to do so.
o No worries about loss of support
Performance
o Allows for great performance even on simple cheap servers
(see http://www.zend.com for performance comparisons)
Database integration
o Allows native connections to many different database systems including MySQL,
PostgreSQL, mSQL, Oracle, dbm, FilePro, Hyperwave, Informix, Interbase,
SyBase, and allow simulated database access to flat files through the built in
SQlite interface
Built in libraries
o Many built in functions makes many tasks simple to perform with just a few lines
of code
Support
o Zend technologies, who maintain the engine that runs PHP, sell support to fund
PHP’s development.
Cost - PHP is free. (get it from http://www.php.net)
Allows for content of HTML pages to be dynamically built or altered on the server, after
a page request from a client, before the page is actually sent to the client.
PHP source code can be embedded inside HTML code or in a file by itself.
Either way PHP code should always be enclosed in PHP tags
The PHP code should never be seen by the client viewing a PHP page because the php
server will always execute the PHP codes inside the PHP tags, collect the output along
with any HTML code in the file, and then return the total output to the user.
<?PHP
//PHP code goes here
?>
These are the most common types of PHP tags and cannot be turned off by the system
administrator. RECOMMENDED!!!
A shorter style that is currently on by default but is often disabled by sysadmins because
it can interfere with XML processing
A style like that used with JavaScript which can be more IDE friendly but is disabled by
default
PHP Statements
<body>
<?php
/*
This dandy little script
will welcome someone to php
*/
Whitespace
o The php engine ignores whitespace so use as much as is needed to make the code
readable
Comments
o Several types
Block comments /* */
Single line comments // or #
Echo statements by themselves are not very interesting because they don’t at this point do
anything that html couldn’t do by itself
The whole point in a server side language like PHP is to be able to provide dynamic
content
// Example of Dynamic Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Welcome</title>
</head>
<body>
<?php
echo "<strong>Welcome to PHP!!!</strong><br/>";
echo "Today is " . date( 'l' ) . ", " . date( 'F' ) . " the " .date( 'dS, Y' ) . "<br/>";
echo "The current time is " . date( 'g:i:s a' );
?>
</body>
</html>
When placed between two strings, whether variable or literal, the two strings will be
joined.
Using Variables
Variables are abstractions for memory locations where data can be stored.
The values of variables can be easily changed.
The programmer can create variables and there are variables that are supplied by the php
system.
Identifiers are the names that are given to variables
o They can be of any length
o They can consist of numbers, letters, and underscores.
o They CANNOT begin with a digit
o They are case sensitive
o Variables can have the same name as a function but it can be confusing so should
be avoided.
When referring to variables in your code the variables identifier must always be prefaced
with a dollar sign
User defined variables do not need to be declared in most cases before they are used.
Instead they are created automatically when they are first referenced.
// PHP Document with Variables
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Welcome</title>
</head>
<body>
<?php
$first = "Hello";
$second = ", ";
$third = "World!";
// Variables Example
$first = "Hello";
$second = ", ";
$third = "World!";
echo $fourth;
Variables vs. Literals
Data Types
PHP is a weakly types language meaning that a variables data type (the type of data that
can be stored in it) is determined by the values that are assigned to it.
Data Types:
o Integer – whole numbers
o Float (aka double) – real numbers
o String – groups of quote delimited characters
o Boolean – true and false
o Array – Multiple data items in array format
o Object – instances of classes
o NULL – For variable that have not be given a value or have been unset
o Resource – external resources like DB connections or file pointers
There are numerous functions available for determining the data type of variables
o getType( )
o is_array( )
o is_double( ), is_float( ), is_real( )
o is_long( ), is_int( ), is_integer( )
o is_string( )
o is_object( )
o is_resource( )
ois_null( )
ois_scalar( ) – check for integer, Boolean, string, or float
ois_numeric( ) – check for number or numeric string
ois_callable( ) – checks for valid function name
Each of these takes a variable as an argument and returns true or false
There is also a settype( $var, ‘type’ ) function that can be used to set a specific type
Type can also be manipulated through the use of casting
// Casting
$totalamount = (float)$totalqty;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Data Types</title>
</head>
<body>
<?php
$name = "Victrola Firecracker";
$id = 123456789;
$age = 99.9;
Variable Status
Constants
Constants do not use the $ prefix when they are being referred to.
Constants can only store Boolean, integer, float, and string data (they are always scalar)
<?php
define( 'TOTALPOINTS', 800 );
echo TOTALPOINTS;
?>
Variable Variables
These are special types of variables whose identifiers are variable as is the variables value.
One variable is used as the identifier for another variables
<?php
$id = "id123456789";
//assign value
$$id = "Victrola Firecracker";
//see value
echo $id123456789;
?>
Variable Scope
At this point we know that all variables have an identifier, a data type, and a value.
All variables also have a scope.
o The scope of a variable refers to the places in a script where a variables can be
used.
PHP has 6 scopes that you should be aware of:
o Built in superglobal variables – can be used from anywhere
o Constants – can be used inside and outside functions
o Global variables – declared inside a script but outside a function can be used
anywhere in the script except inside the functions.
o Global variables declared specifically as global inside a function can be used
anywhere in the script
o Variables declared as static inside functions can be used from anywhere but will
retain there values from one execution of the function to the next
o Variables declared normally inside functions only exist inside that function and
cease to exists when the function ends.
Variable values can be passed from one page to another in PHP through HTTP’s normal
GET and POST behaviors.
o This is most often used when passing values from forms to be processed by PHP
but can be used in other ways.
A value is passed from one page to another by appending a question mark followed by
the variables name, an equal sign, and the variables value to the end of the URL for the
page that the value is being passed to as a normal hyperlink.
// receiver.php
echo $_GET[ 'fname' ];
Multiple value can be sent by separating each name/value pair with an ampersand (&)
The same thing can be accomplished while keeping the data dynamic (not hard coded) by
supplying the user with a form to complete.
The form should be standard (X)HTML with the action attribute set to the name of the
receiving page and the method set to either GET or POST.
o GET will allow the sent data to be seen in the address bar (insecure)
o POST will hind the data in the message request header (more secure)
The HTML form will automatically create the needed URL to send the data to the
receiving page if GET is used.
// receiver.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="receiver.php" method="GET">
<table>
<tr>
<td>First Name</td>
<td>
<input type="text" name="fname"/>
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input type="text" name="lname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Operators
Operators are symbols that can be used to manipulate values and variables by performing
operations on them.
The assignment operator (=) and the string concatenation operator (.) have already been
mentioned and used.
The values or variables that the operators work on are called operands
All operators are either unary, binary, or ternary
Arithmetic operators
+ Addition $a + $b
- Subtraction $a - $b or -$a
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
// compute distance
$distance = $lightspeed * $seconds;
The same idea but with variable data from a user form
// get_input.php
<form action="lightcalc.php" method="post">
Light travels at 186,000 miles per second in a vacuum. Enter a number of seconds in the field
below to see how far light would travel in that amount of time.<br/><br/>
<body>
In
<?php
echo $seconds;
echo ($seconds > 1 ? " seconds" : " second");
?>
<?php
$distance = $seconds * $lightspeed;
echo $distance;
?>
miles.
</body>
</html>
String Operators
The assignment and concatenation operators are the only ones used with strings.
Assignment Operators
The equals sign is the standard assignment operator used most of the time but there are
others
References
<?php
$a = 9;
$b = $a;
$a = 10;
echo "A: " . $a . "<br/>";
echo "B: " . $b . "<br/>";
?>
When a reference operator (&) is used along with the assignment operator a connection is
made between the two variables so that they both refer to the same value stored in
memory
<?php
$first = 9;
$second = &$first;
$first = 10;
echo "First: " . $first . "<br/>";
echo "Second: " . $second . "<br/>";
$second = 11;
echo "First: " . $first . "<br/>";
echo "Second: " . $second . "<br/>";
?>
The link between referenced variables can be broken by using the unset( ) function
PHP’s Combined Assignment Operators
+= $a += $b $a = $a + $b
-= $a -= $b $a = $a - $b
*= $a *= $b $a = $a * $b
/= $a /= $b $a = $a / $b
%= $a %= $b $a = $a % $b
.= $a .= $b $a = $a . $b
Equality Operator
The Equality operator (==) is used to determine if two variables contain the same value.
PHP supports a number of other equality and comparison operators besides that basic
(==).
PHP’s Comparison Operators
Operator Name
== Equals
!= Not Equal
Logical Operators
Logical operators are used to combine the results of other logical operations and
comparisons
PHP’s Logical Operators
Operator Name
! NOT
&& AND
|| OR
And AND
Or OR
Other Operators
Commas, -->, and the word new are also operators in PHP that will be covered later
Ternary Operator
o Condition ? value if true : value if false;
<?php
$number =24;
echo ($number>50 ? "That's a big number" : "Not so Big");
?>
$answer = @(9/0);
Execution Operator
<?php
$output = `ls -l`;
echo "<pre>" . $output . "</pre>";
?>
Precedence is the order in which operators are executed when they are found in a single
statement.
Operators also have an associativity that determines which order operators of the same
precedence will execute.
Covered in a million books, look it up.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)
^ (Bitwise XOR ) : This is also binary operator i.e. works on two operand. This is also
known as Exclusive OR operator. Bitwise XOR takes two numbers as operands and does
XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
Syntax:
$First ^ $Second
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)
~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise
NOT operator takes one number and inverts all bits of it.
Syntax:
~$number
Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)
<< (Bitwise Left Shift) : This is a binary operator i.e. works on two operand. Bitwise
Left Shift operator takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.
Syntax:
$First << $Second
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )
Note: Bitwise left shift with one bit is equivalent to multiplication with 2.
>> (Bitwise Right Shift) : This is also binary operator i.e. works on two operand.
Bitwise Right Shift operator takes two numbers, right shifts the bits of the first operand, the
second operand decides the number of places to shift.
Syntax:
$First >> $Second
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
Note: Bitwise right shift with one bit is equivalent to division with 2.
Below is the implementation of Bitwise Operators in PHP:
<?php
// PHP code to demonstrate Bitwise Operator.
// Bitwise AND
$First = 5;
$second = 3;
$answer = $First & $second;
print_r("\n");
// Bitwise OR
$answer = $First | $second;
print_r("Bitwise | of 5 and 3 is $answer");
print_r("\n");
// Bitwise XOR
$answer = $First ^ $second;
print_r("Bitwise ^ of 5 and 3 is $answer");
print_r("\n");
// Bitwise NOT
$answer = ~$First;
print_r("Bitwise ~ of 5 is $answer");
print_r("\n");
print_r("\n");
print_r("\n");
?>
Output:
Bitwise & of 5 and 3 is 1
Bitwise | of 5 and 3 is 7
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2
String Manipulation
Formatting Strings
PHP contains many functions and tools that allow strings to be manipulated and
formatted.
Reasons:
o Clean up user entered data
o Format strings for presentation
o …
Trimming Strings
o chop( ), rtrim( ), ltrim( ), and trim( )
All four of these functions are used to remove white space from strings.
They all take a string as parameters and return the modified strings.
They typically remove newlines, carriage returns, vertical and horizontal
tabs, and spaces.
o chop( ) and rtrim( )
Same function, different names
Remove whitespace only from the end of a string
o ltrim( )
Removes white space from the start of a string
o trim( )
Removes leading and trailing white space from a string
echo $longLine;
echo "<hr/>";
echo $formattedLine;
The print( ) function does the same thing as echo except that it returns a Boolean value
denoting success.
The printf( ) function allows a string to be formatted and then sends it to the browser
The sprintf( ) function allows formatting but then simply returns the string
The printf( ) function makes use of conversion specifications like %s that will represent a
variable values placement in a string.
The conversion specifications always take this form:
Type Meaning
d Integer as a decimal
o Integer as an octal
s String as a string
$num = 123.456789;
$othernum = 789.432;
Changing Case
Function Description
$match = false;
foreach( $tlds as $tld ) {
if( $domainParts[ 1 ] == $tld ) {
$match = true;
}
}
if( ! $match ) {
echo "The TLD for your domain appears invalid.<br/>";
}
Substrings
Comparing Strings
Functions available for comparing string can either compare entire strings or parts of
string
strcasecmp( )
o Identical to strcmp except that it is not case sensitive
strnatcmp( ) and strnatcasecmp( )
o Compares string using natural ordering
$s1 = "4";
$s2 = "100";
String Lengths
The strlen( ) function returns the number of characters in a string that is passed to it.
Matching and Replacing Substring
Replacing Substrings
str_replace( )
<body>
<?php
$name = $_POST[ 'name' ];
$email = $_POST[ 'email' ];
$message = $_POST[ 'message' ];
fclose( $fp );
?>
</body>
</html>
PHP | Functions
A function is a block of code written in a program to perform some specific task. We can relate
functions in programs to employees in a office in real life for a better understanding of how
functions work. Suppose the boss wants his employee to calculate the annual budget. So how
will this process complete? The employee will take information about the statistics from the
boss, performs calculations and calculate the budget and shows the result to his boss. Functions
works in a similar manner. They take informations as parameter, executes a block of
statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:
Built-in functions : PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so
on.
User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.
Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required. This
reduces the time and effort of repetition of a single code. This can be done both within a
program and also by importing the PHP file, containing the function, in some other
program
Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to maintain.
Creating a Function
While creating a user defined function we need to keep few things in mind:
function function_name(){
executable code;
}
Example:
PHP
<?php
function hello()
{
echo "Hello World";
}
// Calling the function
hello();
?>
Output:
Hello World
Function Parameters or Arguments
The information or variable, within the function’s parenthesis, are called parameters. These are
used to hold the values executable during runtime. A user is free to take in as many parameters
as he wants, separated with a comma(,) operator. These parameters are used to accept inputs
during runtime. While passing the values like during a function call, they are called arguments.
An argument is a value passed to a function and a parameter is used to hold those arguments.
In common term, both parameter and argument mean the same. We need to keep in mind that
for every parameter, we need to pass its corresponding argument.
Syntax:
PHP
<?php
?>
Output:
The product is 30
PHP
<?php
?>
Output:
PHP
<?php
?>
Output:
The product is 30
Pass by Value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.
Pass by Reference: On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually pass the
address of the value, where it is stored using ampersand sign(&).
Example:
PHP
<?php
// pass by value
function passVal($num) {
$num += 2;
return $num;
}
// pass by reference
function passRef(&$num) {
$num += 10;
return $num;
}
$n = 10;
passVal($n);
echo "The original value is still $n \n";
passRef($n);
echo "The original value changes to $n";
?>
Output:
<?php
$x = 300;
$y = 200;
function multiplication(){
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
Output :
60000
In the above code two global variables are declared $x and $y which are assigned some value
to them. Then a function multiplication() is defined to multiply the values of $x and $y and
store in another variable $z defined in the GLOBAL array.
$_SERVER : It is a PHP super global variable that stores the information about headers,
paths and script locations. Some of these elements are used to get the information from the
superglobal variable $_SERVER.
Below program illustrates the use of $_SERVER in PHP:
PHP
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo
$_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
echo "<br>"
?>
Output :
In the above code we used the $_SERVER elements to get some information. We get the
current file name which is worked on using ‘PHP_SELF’ element. Then we get server name
used currently using ‘SERVER_NAME’ element. And then we get the host name through
‘HTTP_HOST’.
$_REQUEST : It is a superglobal variable which is used to collect the data after
submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET
perform the same task and are widely used.
Below is the HTML and PHP code to explain how $_REQUEST works:
HTML
<!DOCTYPE html>
<html>
<body>
Output :
In the above code we have created a form that takes the name as input from the user and prints
it’s name on clicking of submit button. We transport the data accepted in the form to the same
page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we
manipulate the data in the same page using the PHP code. The data is retrieved using the
$_REQUEST superglobal array variable
$_POST : It is a super global variable used to collect data from the HTML form after
submitting it. When form uses method post to transfer data, the data is not visible in the
query string, because of which security levels are maintained in this method.
Below is the HTML and PHP code to explain how $_POST works:
HTML
<!DOCTYPE html>
<html>
<body>
Output :
In the above code we have created a form that takes name and age of the user and accesses the
data using $_POST super global variable when they submit the data. Since each superglobal
variable is an array it can store more than one values. Hence we retrieved name and age from
the $_POST variable and stored them in $nm and $age variables.
$_GET : $_GET is a super global variable used to collect data from the HTML form
after submitting it. When form uses method get to transfer data, the data is visible in the
query string, therefore the values are not hidden. $_GET super global array variable stores
the values that come in the URL.
Below is the HTML and PHP code to explain how $_GET works:
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="cyan">
<?php
$name = $_GET['name'];
$city = $_GET['city'];
echo "<h1>This is ".$name." of ".$city."</h1><br>";
?>
<img src = "2.jpg" alt = "nanilake" height = "400" width="500" />
</body>
</html>
We are actually seeing half of the logic just now. In the above code we have created a
hyperlink image of Nainital Lake which will take us to picture.php page and with it will also
take the parameters name=”Nainilake” and city=”Nainital”.
That is when we click on the small image of Nainital Lake we will be taken to the next page
picture.php along with the parameters. As the default method is get, these parameters will be
passed to the next page using get method and they will be visible in the address bar. When we
want to pass values to an address they are attached to the address using a question mark (?).
Here the parameter name=Nainilake is attached to the address. If we want to add more values,
we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is
added using ampersand after the name parameter. Now after clicking on the image of Nainital
Lake we want the picture.php page to be displayed with the value of parameter displayed along
with it.
Parameters are passed by value by default when sent to functions (a copy is passed)
You can specify something is to be passed by reference by placing an ampersand (&)
before the variables name in the function declaration
No change to the function call is required.
Reusing code
Is a good thing
Reduces costs
o Code can be reused so it doesn’t need to be rewritten and re tested
Increases reliability
o Because reused code has already been tested and debugged it can be assumed to
work correctly in the new project
Improves consistency
o Doing the same thing in the same way in multiple projects makes then easier to
understand and use
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>The Sample Company</title>
<style type="text/css">
body {
font-family: arial;
margin: 0px;
}
#banner {
background-color: #fc0;
height: 60px;
border-bottom: 1px solid black;
}
#banner img {
margin: 5px;
}
#banner #nav {
float: right;
width: 300px;
}
#banner #nav ul {
padding: 0px;
margin: 5px;
list-style: none;
}
#banner #nav ul li {
float: right;
width: 88px;
border: 1px solid black;
margin: -1px 0px 0px -1px;
text-align: center;
}
#banner #nav ul li a {
display: block;
text-decoration: none;
color: white;
padding: 3px;
}
#footer {
background-color: #fc0;
padding: 5px;
border-top: 1px solid black;
border-bottom: 3px solid black;
font-size: .5em;
}
#content {
margin: 10px;
}
</style>
</head>
<body>
<div id="banner">
<img alt="The Sample Company" src="images/banner.gif"/>
<div id="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Downloads</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Legal</a></li>
</ul>
</div>
</div>
<div id="content">
Pages Content
</div>
<div id="footer">
© Copyright 2005 The Sample Company
</div>
</body>
</html>
Becomes
<?php require( 'includes/header.inc' ); ?>
PHP codes can be included in the .inc pages but still require the php tags
</div>
<div id="footer">
© Copyright
<?php echo date( 'Y' ); ?> The Sample Company
<span id="date"><?php echo date( 'l, F jS Y' ); ?></span>
</div>
</body>
</html>
Include and require are identical except that when they fail the require construct give a
fatal error while include just gives a warning.
Same as the originals except that they ensure that things are only imported one time
This becomes important when libraries of functions are being imported that may
themselves import other libraries.
These are two settings that are setup for a server (in the php.ini file) that will
automatically import headers and footers for every file served.
If the settings are in php.ini they are put into every page, if the setting are in a .htaccess
file (using apache) they can be set for each directory.
php_value auto_prepend_file "includes/header.inc"
php_value auto_append_file "includes/footer.inc"
Built-in functions are the functions that are provided by PHP to make programming more
convenient.
Many built-in functions are present in PHP which can be employed in our code. These
functions are very helpful in achieving programming goals.
The built-in functions in PHP are very simple and easy to use. They make PHP powerful
and useful.
PHP is very rich in terms of Built-in functions. Some of the important Built-in functions
of PHP are as follows:
<?php
$file = fopen(“demo.txt”,'w');
?>
<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>
3) fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified, e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed,
e.g.,
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
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.
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit
button.
The PHP script that was specified as the form handler in the form's action attribute
checks that the file has arrived and then copies the file into an intended directory.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
The following HTM code below creates an uploader form. This form is having method attribute
set to post and enctype attribute is set to multipart/form-data
Live Demo
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
</body></html>
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value assigned to
the input's name attribute in uploading form was file, then PHP would create following five
variables −
Below example should allow upload images and gives back result as uploaded file information.
Live Demo
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}?><html>
<body>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</form>
</body></html>