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

Unit 4 PHP1

Uploaded by

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

Unit 4 PHP1

Uploaded by

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

Unit -4

PHP Functions and Objects


Function
• PHP function is a piece of code that can be
reused many times.
• It can take input as argument list and return
value.
• Types
• built-in functions
• User-defined Functions
Advantage of PHP Functions
• Code Reusability: PHP functions are defined
only once and can be invoked many times, like
in other programming languages.
• Less Code: It saves a lot of code because you
don't need to write the logic many times. By
the use of function, you can write the logic
only once and reuse it.
• String Functions
built-in functions
• Numeric Functions
PHP User-defined Functions
function return
• User defined function in following example
processes the provided arguments and returns
a value to calling environment
**Call By Value & Call By Reference
**PHP - Arrays
• An array is a data structure which is used to
hold multiple values of similar type in a single
variable.
• An array is a special variable, which can hold
more than one value at a time.
• For example if you want to store 100 numbers
then instead of defining 100 variables its easy
to define an array of 100 length.
**Types of Arrays
• In PHP, there are three types of arrays:
• Numerically Indexed Arrays
• Associative arrays
• Multidimensional Array
Numerically Indexed Arrays
• PHP index is represented by number
which starts from 0.
• We can store number, string and object
in the PHP array.
• All PHP array elements are assigned to an
index number by default.
There are two ways to create indexed
arrays:
• The index can be assigned automatically.
(index always starts at 0)
• Eg:
$cars = array("Volvo", "BMW", "Toyota");
• The index can be assigned manually.
• Eg:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Associative Arrays

• Associative arrays are arrays that use named


keys (strings) that you assign to them.
• PHP allows to associate name/label with each
array elements in PHP using => symbol.
There are two ways to create an
associative array :
• 1st Method
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
• 2nd Method
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Multidimensional Arrays
• PHP multidimensional array is also known as
array of arrays.
• A multidimensional array is an array
containing one or more arrays.
• It allows you to store tabular data in an array.
• PHP multidimensional array can be
represented in the form of matrix which is
represented by row * column.
$emp = array Example
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Array to display following tabular data
**Array Functions
• The array functions allow you to access and
manipulate arrays.
Types
Array()
• The array() function is used to create an array.
• It can be any of these
• Indexed arrays - Arrays with numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing
one or more arrays
array_change_key_case()
• The array_change_key_case() function changes all keys in an
array to lowercase or uppercase.
Eg:

Output:
array_chunk() Function
• The array_chunk() function splits an array into
chunks of new arrays. output
• Eg:
array_column()
• The array_column() function returns the
values from a single column in the input array
Eg: Output
array_combine()
This function is used to combine two
different arrays to combine them into
one array.
Example
array_count_values()
• The array_count_values() function counts all the values of an
array.
array_diff()
• The array_diff() function compares the values of two (or
more) arrays, and returns the differences.
**PHP date() Function

• The date() function formats a local date and


time, and returns the formatted date string.
• Types are mentioned below
getdate() Function

• Return date/time information of the current


local date/time(System date)
checkdate()

• The checkdate() function is used to validate a


Gregorian date
• Syntax
checkdate(month, day, year)
It Returns Value: TRUE if the date is valid. FALSE
otherwise
date_add() Function
• The date_add() function adds some days,
months, years, hours, minutes, and seconds to
a date.
• Syntax
date_add(object, interval)

O/P= Add 40 days to the 15th of March, 2013


date_create_from_format() Function
• It Return a new DateTime object formatted
according to the specified format
date_create() Function
• The date_create() function returns a new
DateTime object and then format the date.
• Syntax
date_create(variable, Format)
date_diff() Function
• This Function calculate the difference between
two dates
date_format() Function
• The date_format() function returns a date
formatted according to the specified format.
date_modify() Function

• The date_modify() function modifies the


current date as per specification.

Add15 days more to the existing date


date_sunrise() Function & date_sunset()

• The date_sunrise() function returns the


sunrise time & sunset time for a specified day
and location.
PHP time() Function
• The time() function returns the current time in
the number of seconds, then format it to a
date:
• Syntax
time()
microtime() Function
• Return the current timestamp with
microseconds.
mktime() Function
• Return the timestamp for a date. Then use it
to find the day of that date.
timezone_name_get() Function
• The timezone_name_get() returns the name
of the timezone.
timezone_version_get() Function

• The timezone_version_get() function returns


the version of the timezonedb.
PHP File Handling

• It is the process of creating a file, read file line


by line, read file character by character, write
file, append file, delete file and close file.
File Handling operations
• Opening a file
• Reading a file
• Writing
• Updating
• Append
• Closing
• Deleting
• Checking file properties- Size,type,When its modified,
whether file exists etc.
• Note: file_exists is the function to check whether the
file is exists in the server or not.
Create a file
• We can create a new file on the server’s file
system by using fopen,fwrite and fclose
functions.
• Steps
• 1. Open a file
2. Write to a file
3. Close the file
4. Error Handling
PHP Open File - fopen()/
• The fopen() function is used to create a new
file.
• The PHP fopen() function is also used to open
a file which is existing.
• If you use fopen() on a file that does not exist,
it will create it, given that the file is opened for
writing (w) or appending (a).
Write to a File: fwrite()
• fwrite() function is used to write content to a
newly created file.
• If it is ann existing file then, When a file is
opened in write mode, all the existing data in
the file is erased and new data can be written
to the file using the fwrite() function already
open in write mode.
• Eg: fwrite($myfile, $movie_name);
PHP Close File - fclose()

• The PHP fclose() function is used to close an


open file pointer
Error Handling
• It is the practice of checking if the file has
opened successfully before trying to write.
PHP Read File - fread()
• Reading content from a file in PHP can be accomplished in
two ways:
• Using readfile() function
• Using fread() to read content from an open file.
• The readfile() function reads the entire content of a file
and writes it to the output buffer.
• Eg:
<?php
echo readfile("studytonight-info.txt");
?>
• The contents of studytonight will be copied to a buffer.
using fread()
• We can read content from an already open file
using the fread() function. The fread() function
takes two arguments:
• first is the filename
• and the second argument specifies the size in
bytes for the content to be read.
Append to a File: fwrite()
• We can append or add data to a file by using
the "a" mode. The "a" mode appends text to
the end of the file.
Delete a File: unlink()

• The PHP unlink() function is used to delete file.


File Opening Modes
Modes Description Example
r Open a file for read only. File pointer starts Fopen(“file.txt”,”r”)
at the beginning of the file
w Open a file for write only. File pointer starts Fopen(“file.txt”,”w”)
at the beginning of the file
a Open a file for write only. File pointer starts Fopen(“file.txt”,”a”)
at the end of the file.
x Creates a new file for write only. . Fopen(“file.txt”,”x”)

r+ Open a file for read/write. File pointer starts Fopen(“file.txt”,”r+”)


at the beginning of the file
w+ Open a file for read/write. Erases the Fopen(“file.txt”,”w+”)
contents of the file or creates a new file if it
doesn't exist.
a+ Open a file for read/write. The existing data Fopen(“file.txt”,”a+”)
in file is preserved. File pointer starts at the
end of the file.
x+ Creates a new file for read/write. Returns Fopen(“file.txt”,”x+”)
FALSE and an error if file already exists
flock() Function

• The PHP Filesystem flock() function is used to


lock or release a file.
Working of flock()
Types of Locks
• LOCK_SH - A shared lock (reader). Allow other
processes to access the file
• LOCK_EX - An exclusive lock (writer). Prevent
other processes from accessing the file
• LOCK_UN - Release the lock
**Exception Handling
• What is an Exception?
An exception is an unexpected outcome of a program,
which can be handled by the program itself.
• An unexpected result of a program is an exception,
which can be handled by the program itself."
• An exception disrupts the normal flow of the
program. But it is different from an error because an
exception can be handled, whereas an error cannot
be handled by the program itself.
Exception Handling

• Exception handling is a powerful mechanism


of PHP, which is used to handle runtime errors
(runtime errors are called exceptions).
• So that the normal flow of the application can
be maintained.
• Eg: A most popular example of exception
handling is - divide by zero exception, which is
an arithmetic exception.
PHP offers the following keywords for
Exception handling
• Try
• Catch
• throw
• Finally
try
• The try block contains the code that may have
an exception or where an exception can arise.
• When an exception occurs inside the try block
during runtime of code, it is caught and
resolved in catch block.
• The try block must be followed by catch or
finally block.
• A try block can be followed by minimum one
and maximum any number of catch blocks.
catch -
• The catch block contains the code that
executes when a specified exception is
thrown.
• It is always used with a try block, not alone.
When an exception occurs, PHP finds the
matching catch block.
throw
• It is a keyword used to throw an exception.
• This is how we trigger an exception
• It also helps to list all the exceptions that a
function throws but does not handle itself.
• Each throw must have at least one "catch".
finally -
• The finally block contains a code, which is
used for clean-up activity in PHP.
• Basically, it executes the essential code of the
program.
Example
*Cookies
• A cookie is a tiny file placed on the user's(client )
machine by the server.
• It is a small text file that a website downloads to a
users device inorder to track the behaviour of the
file.
• It is used to recognize the user.
• Cookie is created at server side and saved to client
browser. Each time when client sends request to the
server, cookie is embedded with request. Such way,
cookie can be received at the server side
**Create Cookies With PHP
• A cookie is created with the setcookie() function.
• Syntax
setcookie( name, value, expire, path, domain, secure, httponly);
These are termed as the arguments for cookie
• Name: Required. Specifies the name of the cookie.
• Value: Optional. Specifies the value of the cookie.
• Expire: Optional. Specifies when the cookie will expires.
• Path: Optional. Specifies thepath of the server on which the
cookie will be available.
• Domain: Optional. Specifies the domain name of the cookie.
• Secure: Optional. Specifies whether or not the cookie should only
be transmitted over a secure HTTPS connection.
• Httponly: Optional. If set to TRUE the cookie will be accessible
only through the HTTP protocol
Example

• Here setcookie() function is to create a cookie


named username and assign the value John Carter to
it.
• A cookie will expire after 30 days.
• We also use the isset() function to find out if the cookie
is set or not.
• The setcookie() function must appear BEFORE the
<html> tag.
Types of Cookies
• Session Cookie: This type of cookies are
temporary and are expire as soon as the
session ends or the browser is closed.
• Persistent Cookie: To make a cookie persistent
we must provide it with an expiration time.
Then the cookie will only expire after the given
expiration time, until then it will be a valid
cookie.

You might also like