0% found this document useful (0 votes)
50 views

Unit Iii

Uploaded by

Poonam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Unit Iii

Uploaded by

Poonam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

UNIT-III: PHP Basics 12 hours

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?

 A server side scripting language created in 1994 by Ramus Lerdorf


 PHP codes can be embedded inside an html document allowing for dynamic web content
 As of April 2007, PHP had an install base of almost 21 million domains
(see http://www.php.net/usage.php)
 PHP is open source and free
 Originally stood for Personal Home Page but was later changed to PHP Hypertext
Processor

PHP's Strengths (Why 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)

Working with PHP

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

1. Client requests a php page from a web server


2. The web server, on receiving the request recognizes that the needed page is php based
3. The web server passes the request along with any additional request information to the
php server
4. The php server locates the code for the requested page and executes the php statements
located in that file and collects the output.
5. The output is then returned to the web server as a standard html page, which is then sent
to the client.

Basic Syntax with PHP tags

 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!!!

// PHP Short Tags


<?
//PHP code goes here
?>

 A shorter style that is currently on by default but is often disabled by sysadmins because
it can interfere with XML processing

// PHP Script Tags


<script language="php">
//php codes go here
</script>

 A style like that used with JavaScript which can be more IDE friendly but is disabled by
default

// PHP with ASP style tags


<%
//php codes go here
%>

 ASP like style, disabled by default

PHP Statements

 PHP statements go between the PHP tags


 These statements are what tell the php engine what to do
 All php statement must end with a semicolon just like in C and java.

// Example PHP Document


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Welcome</title>
</head>

<body>
<?php
/*
This dandy little script
will welcome someone to php
*/

//we are going to output something!!!


echo "Welcome to PHP!!!";
#All done outputting
?>
</body>
</html>

 The echo statement simply outputs whatever follows the command.


 Can be used to output plain text or HTML

// Simple Output with PHP


echo "<strong>Welcome to PHP!!!</strong><br/>";

 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 #

Embedding PHP in HTML

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

echo $first . $second . $third;


?>
</body>
</html>

Assigning values to Variables

 Values are assigned to variables by using the assignment operator (=)


 Variables can be assigned literal values or values from other variables

// Variables Example
$first = "Hello";
$second = ", ";
$third = "World!";

$fourth = $first . $second . $third;

echo $fourth;
Variables vs. Literals

 Variables values can change while literal values never change.


 When dealing with strings the quotation marks used become important
 Single quotes (hard quotes) around a variables identifier will stop the value from the
variable from being accessed and instead the variables identifier will be used as if it were
a string.
 Double quotes (soft quotes) used around a variable name will still allow the variables
value to be access in place of the variables actual name.

// Duoble vs. Single Quotes


$first = "Hello";
$second = ", ";
$third = "World!";

$fourth = $first . $second . $third;

//change to single to see what happens


echo "I would like to say $fourth";

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;

 Type can also be changed by using reinterpretation functions


o intval( $var )
o floatval( $var )
o strval( $var )

// Examples of Different type of data

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

echo "Name value: " . $name . "<br/>";


echo "Name type: " . getType( $name ) . "<br/>";
echo "<hr/>";
echo "ID value: " . $id . "<br/>";
echo "ID type: " . getType( $id ) . "<br/>";
echo "Is ID an integer? " . is_int( $id ) . "<br/>";
echo "<hr/>";
echo "Age value: " . $age . "<br/>";
echo "Age type: " . getType( $age ) . "<br/>";
echo "Is age real? " . is_real( $age ) . "<br/>";
?>
</body>
</html>

Variable Status

 isset( ) and empty( )

Constants

 Constants are variables whose value cannot be changed once it is set

define( ‘CONSTANT’, value );

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

Passing Variables Between Pages

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

// Example URL for Requesting a page


<a href="receiver.php?fname=victrola">Send name</a>
 The value can then be accessed from the receiving page three different ways depending
on the PHP servers setup.
o Short Method
 $fname, if the server allows the name and value that are passed to the page
will take the form of a normal PHP variable.
 It allows simple quick access to the variable and it’s value but can cause
security problems so this is normally turned of (default)
o Medium Method
 An array of global variables that are always accessible called $_GET and
$_POST are available that each passed variable will be assigned to.
 This is the preferred method used today.
o Long Method
 Another global array called either $HTTP_GET_VARS or
$HTTP_POST_VARS can also be used.
 This method is acceptable but can also be turned off.

// receiver.php
echo $_GET[ 'fname' ];

 Multiple value can be sent by separating each name/value pair with an ampersand (&)

// updated url and receiver.php


<a href="receiver.php?fname=victrola&lname=firecracker">
Send name
</a>

echo "First name received is " . $_GET[ 'fname' ] ."<br/>";


echo "Last name received is " . $_GET[ 'lname' ];

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

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code

PHP supports several ways of commenting:

Example

Syntax for single-line comments:

<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment


?>

</body>
</html>

Example

Syntax for multiple-line comments:

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

 All binary except subtraction which can also be unary

PHP’s Arithmetic Operators

Operator Name Example

+ Addition $a + $b

- Subtraction $a - $b or -$a

* Multiplication $a * $b
/ Division $a / $b

% Modulus $a % $b

// The basic calculation


<?php
// approximate speed of light in miles per second
$lightspeed = 186000;
$days = 1000; // specify number of days here

$seconds = $days * 24 * 60 * 60; // convert to seconds

// compute distance
$distance = $lightspeed * $seconds;

echo "In " . $days;


echo " days light will travel about ";
echo $distance . " miles.";
?>

 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/>

<input type="text" name="seconds"/>


<input type="submit" value="Calculate"/>
</form>
// lightcalc.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Light Calc</title>
<?php
$seconds = $_POST[ 'seconds' ];
$lightspeed = 186000;
?>
</head>

<body>
In

<?php
echo $seconds;
echo ($seconds > 1 ? " seconds" : " second");
?>

light would travel

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

 The reference operator is used in conjunction with the assignment operator


 With a normal assignment a copy of one variables value is made in another variable

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

Operator Use Equivalent to

+= $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

Pre and Post Increment and Decrement Operators

 Increment operator (++)


 Decrement operator (- -)

Equality Operator

 The Equality operator (==) is used to determine if two variables contain the same value.

Other Comparison Operators

 PHP supports a number of other equality and comparison operators besides that basic
(==).
PHP’s Comparison Operators

Operator Name

== Equals

=== Identical (equal and the same type)

!= Not Equal

!== Not Identical

<> Not Equal

< Less than

> Greater than

<= Less that or equal to

>= Greater than or equal to

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

 Error suppression operator


o At sign (@) suppresses errors from the line where it is used.

$answer = @(9/0);
Execution Operator

 Back quotes (`)

<?php
$output = `ls -l`;
echo "<pre>" . $output . "</pre>";
?>

Precedence and Associativity

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

PHP | Bitwise Operators


The Bitwise operators is used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then calculation is performed on the operands. The
mathematical operations such as addition , subtraction , multiplication etc. can be performed at
bit-level for faster processing. In PHP, the operators that works at bit level are:
 & (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise AND
operator in PHP takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
Syntax:

$First & $Second

This will return another number whose bits are


set if both the bit of first and second are set.

Example:

Input: $First = 5, $Second = 3

Output: The bitwise & of both these value will be 1.


Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)

 | (Bitwise OR) : This is also binary operator i.e. works on two operand. Bitwise OR
operator takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
Syntax:

$First | $Second

This will return another number whose bits are


set if either the bit of first or second are set.

Example:

Input: First = 5, Second = 3

Output: The bitwise | of both these value will be 7.

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

This will return another number whose bits are


set if one of the bit in first or second is
set but not both.

Example:

Input: First = 5, Second = 3

Output: The bitwise ^ of both these value will be 6.

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

This will invert all the bits of $number.



Example:

Input: number = 5

Output: The bitwise '~' of this number will be -6.

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

This will shift the bits of $First towards the


left. $Second decides the number of time the
bits will be shifted.

Example:

Input: First = 5, Second = 1

Output: The bitwise << of both these value will be 10.

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

This will shift the bits of $First towards the


right. $Second decides the number of time the
bits will be shifted.

Example:

Input: First = 5, Second = 1

Output: The bitwise >> of both these value will be 2.

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("Bitwise & of 5 and 3 is $answer");

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

// Bitwise Left shift


$second = 1;
$answer = $First << $second;
print_r("5 << 1 will be $answer");

print_r("\n");

// Bitwise Right shift


$answer = $First >> $second;
print_r("5 >> 1 will be $answer");

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

$s1 = " this has leading whitespace";

$s1 = chop( $s1 );

echo "after chop: '" . $s1 . "'" . "<br/>";

$s1 = rtrim( $s1 );

echo "after rtrim: '" . $s1 . "'" . "<br/>";

$s1 = ltrim( $s1 );

echo "after ltrim: '" . $s1 . "'" . "<br/>";

$s2 = "This has trailing whitespace ";

$s2 = chop( $s2 );

echo "after chop: '" . $s2 . "'" . "<br/>";

Formatting Strings for Presentation

 Functions used to reformat string in different ways


o nl2br( ), print( ), printf( ), sprintf( )
 The nl2br( ) function takes a string and replaces all of the newline
characters (\n) with XHTML breaks (<br/>).
$longLine = "Is this a dagger I see before me\n handle toward my
hand?\nCome, let me clutch thee!";

$formattedLine = nl2br( $longLine );

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

void printf( string format [, mixed args…] )

 The sprintf( ) function allows formatting but then simply returns the string

string printf( string format [, mixed args…] )

 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:

%[ ‘padding_character ] [ - ] [ width ] [ .precision ] type

 And have these options:

Type Meaning

b Integer printed as a binary


c Integer printed as a character

d Integer as a decimal

f Double as a floating point

o Integer as an octal

s String as a string

u Integer as unsigned decimal

x (lower) Integer as a hexadecimal with lowercase letters

X (upper) Integer as a hexadecimal with upper case letters

$num = 123.456789;

echo "the number is $num<br/>";


printf( "the number is %s <br/>", $num );
$output = sprintf( "the number is %s <br/>", $num );
echo $output;

$othernum = 789.432;

printf( "two numbers are %s and %s<br/>", $num, $othernum );


printf( "the number with 2 decimal places is %.2f <br/>", $num );
printf( "the number in hex %x <br/>", $num );
printf( "the number in octal %o<br/>", $num );
printf( "the number in binary %b <br/>", $num );

Changing Case

 PHP has functions that change the case of a string

Function Description

strtoupper( ) Converts all characters in the string into uppercase

strtolower( ) Converts all characters in the string into lowercase

ucfirst( ) Capitalizes the first letter of the string

ucwords( ) Capitalizes the first letter of every word in the string

Joining and Splitting String

 explode( ), implode( ), and join( )


 explode( )

array explode( string seperator, string input [ , int limit ] )

 Splits a string based on a delimiter and returns the parts as an array

 implode( ) and join( )


o Same function, different names
o Takes an array of strings and joins them together into a single string with a
delimiter between them
<?php
$tlds = array( "com", "org", "edu", "gov", "mil", "net" );
?>
<body>
<?php
if( isset( $_POST[ 'email' ] ) ) {
$email = $_POST[ 'email' ];

$parts = explode( "@", $email );

if( count( $parts ) != 2 ) {


echo "The email address contain to me @ signs<br/>";
}

echo "Email name: " . $parts[ 0 ] . "<br/>";


echo "Full Domain name: " . $parts[ 1 ] . "<br/>";

$domainParts = explode( ".", $parts[ 1 ] );

$match = false;
foreach( $tlds as $tld ) {
if( $domainParts[ 1 ] == $tld ) {
$match = true;
}
}

if( ! $match ) {
echo "The TLD for your domain appears invalid.<br/>";
}

echo "Domain Identifier: " . $domainParts[ 0 ] . "<br/>";


echo "TLD: " . $domainParts[ 1 ] . "<br/>";
$newEmail = implode( "@", $parts );

echo "The reconstituted email address is: " . $newEmail .


"<br/>";
}
?>

<form action="splittingAndJoining.php" method="POST">


Email Address: <input type="text" name="email"/>
<input type="submit" value="Check Email"/>
</form>
</body>

Substrings

 The substr( ) function is used to extract a substring from a longer string.

String substr( string string, int start [ , length ] )

 substr( ) returns a copy of the substring from the original string.


 Called with a negative start (only) will start copying that many characters back from the
end of the string to the end of the string.

Comparing Strings

 Functions available for comparing string can either compare entire strings or parts of
string

 Entire String Compares


o strcmp( ), strcasecmp( ), and strnatcmp( ).
 strcmp( )

int strcmp( string str1, string str2 )


 Takes 2 strings as parameters which are then compared
o 0 is returned if they are equal
o > 0 is returned if str1 comes after str2
o < 0 is returned is str2 comes after str1
 strcmp is case sensitive

 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";

$return = strcmp( $s1, $s2 );

echo "4 comes after 100: ";


if( $return > 0 ) {
echo "true<br/>";
} else {
echo "false<br/>";
}

$return = strnatcmp( $s1, $s2 );

echo "4 comes after 100: ";


if( $return > 0 ) {
echo "true<br/>";
} else {
echo "false<br/>";
}

String Lengths

 The strlen( ) function returns the number of characters in a string that is passed to it.
Matching and Replacing Substring

 Finding Strings in Strings


o strstr( ), strchr( ), strrchr( ), and stristr( )
 strstr( ) and strchr( )
o Same function

string strstr( string haystack, string needle )

o Find a string or character match in a longer string


 strrchr( )
o Same but returns the haystack from the last needle found
 stristr( )
o Non-case sensitive version of strstr( )

Finding the Position of a Substring

 strpos( ) and strrpos( )


o Similar to strstr( ) but return the position of the needle instead of the needle itself.
o Returns false if no needle found (test for with === or by 0)

int strpos( string haystack, string needle, int [, offset ] )

Replacing Substrings

 str_replace( )

mixed str_replace( mixed needle, mixed new_needle, mixed haystack


[, &count ] )

$badwords = array( "microsoft", "windows", "office" );


$message = str_replace( $badwords, '@#$%&*', $message );

 Replaces all occurrences of needle in haystack with new_needle


o Can take an array as almost any part
 substr_replace( )
o Replaces a particular substring based on its position
string substr_replace( string string, string replacement,
int start, int [length] )

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">


<head>
<title>Signed????</title>
</head>

<body>
<?php
$name = $_POST[ 'name' ];
$email = $_POST[ 'email' ];
$message = $_POST[ 'message' ];

if( empty($name) || empty($email) || empty($message) ) {


echo 'You did not complete the form.<br/>Please
<a href="guestBookSign.php">try again</a>
</body></html>';
exit;
}

$fp = fopen( "guestBook.txt", 'ab' );


if( !$fp ) {
echo "The guest book file could not be
opened.</body></html>";
exit;
}

$message = nl2br( trim($message) );

$message = str_replace( "\n", "", $message );


$fileoutput = date( 'H:i m-d-Y' )
. "\t"
. $name
. "\t"
. $email
. "\t"
. $message
. "\n";

fwrite( $fp, $fileoutput );

echo 'The guestbook has been signed.<br/>


<a href="guestBookView2.php">View the Guest Book</a>';

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.

Why should we use functions?

 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:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.
Syntax:

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:

function function_name($first_parameter, $second_parameter) {


executable code;
}
Example:

 PHP

<?php

// function along with three parameters


function multiplication($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Calling the function


// Passing three arguments
multiplication(2, 3, 5);

?>
Output:

The product is 30

Setting Default Values for Function parameter


PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:

 PHP

<?php

// function with default parameter


function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}

// Calling the function


defGeek("Ram", 15);

// In this call, the default value 12


// will be considered
defGeek("Adam");

?>

Output:

Ram is 15 years old


Adam is 12 years old
In the above example, the parameter $num has a default value 12, if we do not pass any value
for this parameter in a function call then this default value 12 will be considered. Also the
parameter $str has no default value , so it is compulsory.

Returning Values from Functions


Functions can also return values to the part of program from where it is called.
The return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The return
statement also marks the end of the function and stops the execution after that and returns the
value.
Example:

 PHP

<?php

// function along with three parameters


function mul($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = mul(2, 3, 5);
echo "The product is $retValue";

?>

Output:

The product is 30

Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function:

 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:

The original value is still 10


The original value changes to 20
PHP | Superglobals
These are specially-defined array variables in PHP that make it easy for you to get information
about a request or its context. The superglobals are available throughout your script. These
variables can be accessed from any function, class or any file without doing any special task
such as declaring any global variable etc. They are mainly used to store and get information
from one page to another etc in an application.
Below is the list of superglobal variables available in PHP:
1. $GLOBALS
2. $_SERVER
3. $_REQUEST
4. $_GET
5. $_POST
6. $_SESSION
7. $_COOKIE
8. $_FILES
9. $_ENV
Let us now learn about some of these superglobals in detail:
 $GLOBALS : It is a superglobal variable which is used to access global variables from
anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[]
where index holds the global variable name, which can be accessed.
Below program illustrates the use of $GLOBALS in PHP:
 PHP

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

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


NAME: <input type="text" name="fname">
<button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if(empty($name)){
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

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>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


<label for="name">Please enter your name: </label>
<input name="name" type="text"><br>
<label for="age">Please enter your age: </label>
<input name="age" type="text"><br>
<input type="submit" value="Submit">
<button type="submit">SUBMIT</button>
</form>
<?php
$nm=$_POST['name'];
$age=$_POST['age'];
echo "<strong>".$nm." is $age years old.</strong>";
?>
</body>
</html>

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.

Dealing with Scope

 Variable scope defines where a declared variable can be accessed in a program.

 Function scope and local variables


o Variables declared inside a function are in scope from the point where they are
declared in a function until the end of that function
 Global scope and global variables
o Variables declared outside a function are in scope from the point where they are
declared until the end of the file, EXCEPT inside functions
 Super global variables are available inside and outside functions. (those variables defined
by the server like $_POST)
o Using require( ) and include( ) does not effect scope.
 Using the global keyword allows variables declared inside functions to take on global
scope.
 Any variable can be deleted using the unset( ) function

Passing by Reference Versus Passing by Value

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

Functions and Reusing Code

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

Using require( ) and include( )

 Both allow external files to be included/imported into other code.


 Allows for code in those external files to be shared between multiple files and projects

 require( string filename )


o Require does not care about the filename extension so anything can be used
but .inc or .php are most commonly used
o .php may be the best option because if the user finds a way to call the file directly,
a file with a php extension will be processed by the PHP server and the contents
not shown in clear text, a file with an .inc extension would be shown in clear text
so it would be important to store it outside the directory tree.
o The php tags still need to be used in these external files if you want the php to be
processed.

Using require( ) for Website Templates

 The require( ) function is often used to templatize website layouts.


o It allows for common parts of a page to be stored separately and then imported
into each actual web page that needs them.
o This allows for site wide layout changes to be made in a single place.

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

#banner #nav ul li a:hover {


background-color: #ff9;
color: black;
}

#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">
&copy; Copyright 2005 The Sample Company
</div>
</body>
</html>

 Becomes
<?php require( 'includes/header.inc' ); ?>

This is the home page

<?php require( 'includes/footer.inc' ); ?>

 PHP codes can be included in the .inc pages but still require the php tags

</div>

<div id="footer">
&copy; Copyright
<?php echo date( 'Y' ); ?> The Sample Company
<span id="date"><?php echo date( 'l, F jS Y' ); ?></span>
</div>
</body>
</html>

The include( ) Construct

 Include and require are identical except that when they fail the require construct give a
fatal error while include just gives a warning.

Using require_once( ) and include_once( )

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

Using auto_prepend_file( ) and auto_append_file( )

 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 of PHP

 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 Array Functions


These functions allow interacting with and manipulating arrays in various ways. Arrays are
essential for storing, managing, and operating on sets of variables.

 array() - Create an array


 array_chunk() - Splits an array into chunks of arrays
 array_diff() - Compares array values, and returns the differences
 array_fill() - Fills an array with values
 array_intersect() - Compares array values, and returns the matches
 array_merge() - Merges one or more arrays into one array

PHP Calender Functions


The calendar extension presents a series of functions to simplify converting between different
calendar formats.

 cal_from_jd() - Returns information about a given calendar.


 cal_from_jd() - Converts a Julian day count into a date of a specified calendar.
 JDMonthName() - Returns a month name.
 JDDayOfWeek() - Returns the day of a week.
 jdtounix() - Converts a Julian day count to a Unix timestamp.
 unixtojd() - Converts a Unix timestamp to a Julian day count.

PHP Character Functions


The functions provided by this extension check whether a character or string falls into a certain
character class according to the current locale.
 ctype_alnum() - Check for alphanumeric character(s).
 ctype_alpha() - Check for alphabetic character(s).
 ctype_digit() - Check for numeric character(s).
 ctype_space() - Check for whitespace character(s).
 ctype_upper() - Check for uppercase character(s).
 ctype_lower() - Check for lowercase character(s).

PHP Date & Time Functions


These functions allow getting the date and timing from the server where PHP scripts are running.
These functions are used to format the date and time in many different ways.

 date_date_set() - Sets the date.


 date_default_timezone_get() – Returns the default time zone.
 date_default_timezone_set() - Sets the default time zone.
 date_format() - Returns date formatted according to given format.
 date_time_set() - Sets the time.
 getdate() - Returns an array that contains date and time information for a Unix timestamp.
 time() - Returns the current time as a Unix timestamp.

PHP Directory Functions


These functions are provided to manipulate any directory. PHP needs to be configured with --
enable-chroot-func option to enable chroot() function.

 chdir() - Changes current directory.


 chroot() - Change the root directory.
 dir() - Opens a directory handle and returns an object.
 closedir() - Closes a directory.
 getcwd() - Gets the current working directory.
 opendir() - Open directory handle.

PHP Error Handling Functions


These are functions dealing with error handling and logging. They allow user to define their own
error handling rules, as well as modify the way the errors can be logged. This allows user to
change and enhance error reporting to suit their needs.
Using these logging functions, user can send messages directly to other machines, to an email, to
system logs, etc. So user can selectively log and monitor the most important parts of their
applications and websites.

 error_log() - Sends an error to the server error-log, to a file or to a remote destination.


 error_reporting() - Specifies which errors are reported.
 set_error_handler()- Sets a user-defined function to handle errors.
 set_exception_handler() - Sets a user-defined function to handle exceptions.
 error_get_last() - Gets the last error occurred.
 trigger_error() - Creates a user-defined error message.

PHP MySQL Function


PHP MySQLi functions gives to access the MySQLi database servers. PHP works with MySQLi
version 4.1.13 or newer.

 mysqli connect - It opens a connection to a MySQLi Server.


 mysqli create db - It is used to create MySQLi connection.
 mysqli close - It is used to close MySQLi connection.
 mysqli ping - It is used to pings a server connection and reconnect to server if connection
is lost.
 mysqli query - It performs a query against the database.
 mysqli real connect - This function opens a new connection to the MySQLi.
 mysqli refresh - This function refreshes tables or caches, or resets the replication server
information.
 mysqli_stat - This function returns the current system status.
 mysqli rollback - This function rolls back the current transaction for the specified
database connection.

PHP File System Functions


The file system functions are used to access and manipulate the file system. PHP provides all the
possible functions may need to manipulate a file.

 chmod() - Changes file mode.


 file_exists() - Checks whether a file or directory exists.
 file_get_contents() - Reads entire file into a string.
 file_put_contents() - Write a string to a file.
 file() - Reads entire file into an array.
 basename() - Returns filename component of path.

PHP String Functions


PHP string functions are the part of the core. It manipulate strings in almost any possible way.

 chop() - It is used to removes whitespace.


 chunk_split() - It is used to split a string into chunks.
 crypt() - It is used to hashing the string.
 str_split() - It is used to convert a string to an array.
 strchr() - It is used to searches for the first occurrence of a string inside another.
 trim() - It used to remove the white-spaces and other characters.

PHP Network Functions


PHP Network functions give access to internet from PHP.

 fsockopen() - It is used to open internet or Unix domain socket connections.


 gethostbyname() - It is used to get the internet host name which has given by IP Address.
 gethostname() - It is used to get the host name.
 header() - It is used to send the row of HTTP Headers.
 openlog() - It used to open connection to system logger.
 setcookie() - It used to set the cookies.

Basics of File Handling


File handling is needed for any application. For some tasks to be done file needs to be processed.
File handling in PHP is similar as file handling is done by using any programming language like
C. PHP has many functions to work with normal files. Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in which file needs
to be opened, e.g.,

<?php
$file = fopen(“demo.txt”,'w');
?>

Files can be opened in any of the following modes :


 “w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
 “r” – File is opened for read only.
 “a” – File is opened for write only. File pointer points to end of file. Existing data in file
is preserved.
 “w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
 “r+” – File is opened for read/write.
 “a+” – File is opened for write/read. File pointer points to end of file. Existing data in file
is preserved. If file is not there then new file is created.
 “x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It
takes two arguments. One is file pointer and another is file size in bytes, e.g.,

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

PHP - File Uploading

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 process of uploading a file follows these steps −

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 selected file is sent to the temporary directory on the server.

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.

The PHP script confirms the success to the user.

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.

An uploaded file could be a text file or image file or any document.

Creating an upload form

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

if($file_size > 2097152){


$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}?><html>
<body>

<form action="" method="POST" enctype="multipart/form-data">


<input type="file" name="image" />
<input type="submit"/>
</form>

</body></html>

It will produce the following result −

Creating an upload script

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 −

$_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web


server.

$_FILES['file']['name'] − the actual name of the uploaded file.

$_FILES['file']['size'] − the size in bytes of the uploaded file.

$_FILES['file']['type'] − the MIME type of the uploaded file.

$_FILES['file']['error'] − the error code associated with this file upload.


Example

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($file_size > 2097152) {


$errors[]='File size must be excately 2 MB';
}

if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}?><html>
<body>

<form action = "" method = "POST" enctype = "multipart/form-data">


<input type = "file" name = "image" />
<input type = "submit"/>

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

It will produce the following result −

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy