SlideShare a Scribd company logo
1 of 101
PHP
• Amol Gharpure-13
• Apurva Bharatiya-17
• Annujj Agarwal-06
• Nirmiti Dhurve-30
Background
• Started as a Perl hack in 1994 by Rasmus Lerdorf (to handle his
resume), developed to PHP/FI 2.0
• By 1997 up to PHP 3.0 with a new parser engine by Zeev Suraski and
Andi Gutmans
• Version 5.2.4 is current version, rewritten by Zend (www.zend.com) to
include a number of features, such as an object model
• Current is version 5
• php is one of the premier examples of what an open source project
can be
Why PHP?
• You can build dynamic pages with just the information in a php script
• But where php shines is in building pages out of external data
sources, so that the web pages change when the data does
• Most of the time, people think of a database like MySQL as the
backend, but you can also use text or other files, LDAP, pretty much
anything….
INTRODUCTION
• HYPERTEXT PREPROCESSOR (PHP) is a server side scripting language
that is embedded in HTML.
• Used to manage dynamic content, databases, sessions tracking, even
built entire e-commerce site.
• It is integrated with a number of popular databases, including MySQL,
Oracle, Microsoft SQL Server, etc.
• Can also be used as general-purpose programming language.
• PHP code can be simply mixed with HTML code, or it can be used in
combination with various templating engines and web frameworks.
Continued…
• PHP code is usually processed by a PHP interpreter, which is usually
implemented as a web server’s native module.
• After the PHP code is interpreted and executed, the web server sends
resulting output to its client, usually in form of a part of the generated
web page; for example, PHP code can generate a web page’s HTML
code, an image, or some other data.
• PHP has also evolved to include a command-line interface(CLI)
capability and can be used in standalone graphical applications.
PHP Scripts
• Typically file ends in .php--this is set by the web server configuration
• Separated in files with the <?php ?> tag
• php commands can make up an entire file, or can be contained in html--this is a choice….
• Program lines end in ";" or you get an error
• Server recognizes embedded script and executes
• Result is passed to browser, source isn't visible
• <P>
• <?php $myvar = "Hello World!";
• echo $myvar;
• ?>
• </P>
Parsing
• We've talk about how the browser can read a text file and process it,
that's a basic parsing method
• Parsing involves acting on relevant portions of a file and ignoring
others
• Browsers parse web pages as they load
• Web servers with server side technologies like php parse web pages
as they are being passed out to the browser
Two Ways
• You can embed sections of php inside html:
<BODY>
<P>
<?php $myvar = "Hello World!";
echo $myvar;
</BODY>
• Or you can call html from php:
<?php
echo "<html><head><title>Howdy</title>
…
?>
How to run a PHP file?
• PHP files first need to be processed in a web server before sending
their output to the web browser.
• Therefore before running PHP files, they should be placed inside the
web folder of a web server and then make a request to desired PHP
file by typing its URL in the web browser. If you installed a web server
in your computer, usually the root of its web folder can be accessed
by typing http://localhost in the web browser. So, if you placed a file
called hello.php inside its web folder, you can run that file by
calling http://localhost/hello.php.
Basic Syntax
• Syntax based on Perl, Java, and C
• The PHP parsing engine needs a way to differentiate PHP code from other elements. The
mechanism for doing so is known as ‘encapsing to PHP’’. There are four ways to do it:
• Canonical PHP tags:
<?php..?>
• Short-Open(SGML-style) tags:
<?....?>
• ASP-style tags:
<%...%>
• HTML script tags:
• <script language=“PHP”>…</script>
Comments
• There are two commenting formats in PHP:
1. Single-line comments
2. Multi-line comments
<?
#This is a comment
//So is this a comment
/*This is the second line of comment
This is a comment too*/
print ”An example with single line comments”;
?>
Continued(Basic Syntax)…
• PHP is case sensitive.
• For example
<html>
<body>
<?
$capital=67;
print(“Variable capital is $capital<br>”);
print(“Variable capiTal is $capiTal<br>”);
?>
Output:
Variable capital is 67
Variable capiTal is
Three-tiered Web Site: LAMP
Client
User-agent: Firefox
Server
Apache HTTP Server
example request
GET / HTTP/1.1
Host: www.tamk.fi
User-Agent: Mozilla/5.0 (Mac..)
...
response
Database
MySQL
PHP
Variables
• Variables in PHP are represented by a dollar sign
• PHP supports eight types:
• boolean, integer, float, double, array, object, resource and NULL
Example (php.net)
<?php
$a_bool = TRUE; // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
$an_int += 4;
}
// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>
Naming Variables
• Case-sensitivity
• Start with letter or _
• After that you can have numbers, letters and _
• $var = 'Barney';
• $Var = ‘MiaKhalifa';
• print "$var, $Var";
• $4site = ‘Legendary';
• $_4site = ‘LAMP';
Constants
• You cannot alter the value of constant after declaration
• define(CONSTANT, "value");
• print CONSTANT;
Example
<?php
$a = “Paul ";
print ”For " . $a;
?>
<?php
$a = “Batman";
function Test() {
print $a;
}
print ”Bruce Wayne is ”;
Test();
?>
Example
Control Structures
• If, else, elseif, switch
• while, do-while, for
• foreach
• break, continue
•
Statements
• Every statement ends with ;
• $a = 5;
• $a = function();
• $a = ($b = 5);
• $a++; ++$a;
• $a += 3;
Operators
• Arithmethic: +,-,*,%
• Setting variable: =
• Bit: &, |, ^, ~, <<, >>
• Comparison: ==, ===, !=, !==, <, > <=, >=
Logical Operators
• $a and $b
• $a or $b
• $a xor $b
• !$a;
• $a && $b;
• $a || $b;
IF
<?php
if ($a > $b) {
echo "a is bigger than b";
} else {
echo "a is NOT bigger than b";
}
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
While and Do-While
<?php
$a=0;
while($a<10){
print $a; $a++;
}
$i = 0;
do {
print $i;
} while ($i > 0);
?>
For
for ($i = 1; $i <= 10; $i++) {
print $i;
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo $value;
}
Switch
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
PHP COOKIES
What is a cookie?
A cookie is a small text file that is stored on a user’s computer.
Each cookie on the user’s computer is connected to a particular domain.
Each cookie can be used to store upto 4kB of data.
A maximum of 20 cookies can be stored on a user’s pc per domain.
Example(1)
• User sends a request for page at www.example.com for the first time.
PAGE REQUEST
Example (2)
• Server sends back the page xhtml to the browser AND stores some
data in a cookie on the user’s pc.
XHTML
COOKIE DATA
Example(1)
• At the next page request for domain www.example.com, all the
cookie data associated with this domain is sent too.
Page request
Cookie data
Set a cookie
• setcookie (name [,value [,expire [,path [,domain [,secure]]]]])
name = cookie name
value = data to store (string)
expire = UNIX timestamp when the cookie expires.
Default is that cookie expires when the browser is closed.
path = path on the server within and below which the cookie is available on.
domain = domain at which the cookie is available on.
secure = If cookie should be sent over HTTPS connection only. Default false.
Set a cookie-examples
• setcookie (‘name’, ‘Robert’)
• This command will set the cookie called name on the user’s PC
containing the data Robert. It will be available to all pages in the same
directory or subdirectory of the page that set it(the default path and
domain). It will expire and be deleted when the browser is closed
(default expire).
Set a cookie-examples
• setcookie (’age’, ‘20’, time () +60*60*24*30)
• This command will set the cookie called age on the user’s PC
containing the data 20. It will be available to all pages in the same
directory or subdirectory of the page that set it (the default path and
domain). It will expire and be deleted after 30 days.
Set a cookie-examples
• setcookie ( ‘gender’ , ’male’ , 0 , ’/’ )
• This command will set the cookie called gender on the user’s PC
containing the data male. It will be available within the entire domain
that set it. It will expire and be deleted when the browser is closed.
Read cookie data
• All cookie data is available through the superglobal $_COOKIE:
• $variable = $_COOKIE[‘cookie_name’]
• OR
• $variable = $HTTP_COOKIE_VARS[‘cookie_name’] ;
e.g.
$age = $_COOKIE[‘age’]
Storing an array..
• Only strings can be stored in Cookie files.
• To store an array in a cookie, convert it to a string by using the
serialize() PHP function.
• The array can be reconstructed using the unserialize() function once it
had been read back in.
• Remember cookie size is limited.
Delete a cookie
• To remove a cookie, simply overwrite the cookie with a new one with
an expiry time in the past..
• setcookie (‘cookie_name’, ‘’, time () -6000)
• Note that theoretically any number taken away from the time()
function should do, but due to variations in local computer times, it is
advisable to use a day or two.
Malicious Cookie Usage
• There is a bit of a stigma attached to cookies – and they can
be maliciously used (e.g. set via 3rd party banner ads).
• The important thing is to note is that some people browse
with them turned off.
e.g. in FF, Tools>Options>Privacy
The USER is in control
• Cookies are stored client-side, so never trust them completely: They
can be easily viewed, modified or created by a 3rd party.
• They can be turned on and off at will by the user.
PHP WEB CONCEPTS
User
Profile
Server
web serverweb serverWeb Server
Scripts
LoadBalancer
Ad
Server
Web
Services
Apache
Server Architecture
Three-tiered Web Site: LAMP
Client
User-agent: Firefox
Server
Apache HTTP Server
example request
GET / HTTP/1.1
Host: www.tamk.fi
User-Agent: Mozilla/5.0 (Mac..)
...
response
Database
MySQL
PHP
Server Side Techniques
• Server side scripting requires installation on the server side
• Typically client siis only xhtml and it unaware that the xhtml was
produced by a server side script
• Does not require any installations or add-ons on the client
Server Side Techniques
• PHP
• Java EE: Servlet, JSP
• .NET
• CGI / Perl (Very old)
• Ruby
• …
Client Side Techniques
• Requires that the client supports the technique
• JavaScript, Applet, Flash…
Web Application Frameworks
• A web application framework is a software framework that is
designed to support the development of dynamic websites, Web
applications and Web services.
• Numerous frameworks available for many languages
Web App vs. Web Site?
• What’s the difference between Web App and Web Site?
• Rich Internet Application?, AJAX?, Thin Client?
• Full application running in your browser or just a web site?
Server Variables
The $_SERVER array variable is a reserved variable that contains all server information.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
<?php
echo "<br/><br/><br/>";
echo "<h2>All information</h2>";
foreach ($_SERVER as $key => $value)
{
echo $key . " = " . $value . "<br/>";
}
?>
</body>
</html>
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
$_SERVER info on
php.net
PHP functions
• PHP functions are similar to other programming languages. (A function is
a piece of code which takes one more input in the form of parameter
and does some processing and returns a value.)
• PHP has built-in functions but it gives you an option to create your own
functions as well.
• There are two parts:
• Creating a PHP Function
• Calling a PHP Function
• In fact you hardly need to create your own PHP function because there
are already more than 1000 of built-in library functions created for
different area and you just need to call them according to your
requirement.
Array functions
Function Description
array() Creates an array
Array chunk() Splits an array into chunks of arrays
Array count values() Returns an array with the number of occurrences for
each value
Array flip() Exchanges all keys with their associated values in an
array
Array map() Sends each value of an array to a user-made function,
which returns new values
Array pop() Deletes the last element of an array
Array push() Inserts one or more elements to the end of an array
Class and object functions
Function Description
get_class_vars() Get the default properties of the class
get_class() Returns the name of the class of an object
get_declared_classes() Returns an array with the name of the defined classes
get_object_vars() Gets the properties of the given object
get_parent_class() Retrieves the parent class name for object or class
method_exists() Checks if the class method exists
property_exists() Checks if the object or class has a property
Creating a PHP Function
• Its very easy to create your own PHP function. Suppose you want to
create a PHP function which will simply write a simple message on
your browser when you will call it. Following example creates a
function called writeMessage() and then calls it just after creating it.
• Note that while creating a function its name should start with
keyword function and all the PHP code should be put inside { and
} braces as shown in the following example below:
Sample code<html>
<head>
<title>Writing a PHP function</title>
</head>
<body>
<?php
/*Defining a functions*/
function writeMessage()
{
echo"Hello";
}
?>
</body>
Passing parameters
• We can pass as many parameters as we want.
• They act like variables inside the function.
• The following example takes 2 integer parameters and adds them.
• <?php
• function addFunction($num1,$num2)
• {
• $sum=$num1+$num2;
• echo "Sum of the 2 numbers is:$sum";
• }
• addFunction(10,20);
• ?>
• </body>
• </html>
Passing Parameters by reference
• It is possible to pass arguments by reference.
• A reference to the variable is manipulated rather than modifying its
copy.
• An ampersand has to be added to the variable name.
• We have to pass parameters by reference when multiple values have
to be returned.
• <?php
• function addFive($num)
• {
• $num += 5;
• }
• function addSix(&$num)
• {
• $num += 6;
• }
• $orignum = 10;
• addFive( &$orignum );
• echo "Original Value is $orignum<br />";
• addSix( $orignum );
• echo "Original Value is $orignum<br />";
• ?>
• </body>
• </html>
• <?php
• function addFunction($num1, $num2)
• {
• $sum = $num1 + $num2;
• return $sum;
• }
• $return_value = addFunction(10, 20);
• echo "Returned value from the function : $return_value";
• ?>
Form handling
• The PHP superglobals $_GET and $_POST are used to collect form-
data. (Superglobals can be accessed by any function.)
• When the user fills out the form above and clicks the submit button,
the form data is sent for processing to a PHP filenamed
"welcome.php". The form data is sent with the HTTP POST method.
• To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
• <html>
• <body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
• </body>
• </html>
When to use GET?
• Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL).
GET also has limits on the amount of information to send. The
limitation is about 2000 characters. However, because the variables
are displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases.
• GET may be used for sending non-sensitive data.
• Note: GET should NEVER be used for sending passwords or other
sensitive information!
When to use POST?
• Information sent from a form with the POST method is invisible to
others (all names/values are embedded within the body of the HTTP
request) and has no limits on the amount of information to send.
• Moreover POST supports advanced functionality such as support for
multi-part binary input while uploading files to server.
• However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
Sessions
• An alternative way to make data accessible across the various pages of an
entire website is to use php sessions.
• A session creates a file in a temporary directory on the server where
registered session variables and their values are stored.
• This data will be available to all the pages on the site during that visit.
• The location of the temporary file is determined by setting it in the php.ini
file called session.save_path
• Before using session variables we have to set this path.
• A session ends after the user loses the browser or after leaving the site, the
server will terminate the session after a predetermined time, usually 30
mins.
What happens when a session is created?
• PHP first creates a unique identifier for that particular session which
is a random string of 32hexadecimal string.
• A cookie called PHPSESSID is automatically sent to the user’s
computer to store unique identification string.
• A file is automatically created on the server in the designated
temporary directory and bears the name of the unique identifier
prefixed by sess_ followed by the 32hex string.
Starting a PHP session
• A PHP session is started by calling session_start(), it checks if a session
has already started, if not, it starts on. This is usually done at the
beginning of the page.
• Session variables are stored in an array called $_SESSION, these
variables are accessible during the lifetime of the session.
• In the example, a variable counter is registered which increments
each time the page is visited during the session.
<?php
Session_start();
If(isset($SESSION[‘counter’]))
{$_SESSION[‘counter’]+=1;}
Else
$_SESSION[‘counter’]=1;
$msg=“You have visited this page”,$_SESSION[‘counter’];
?>
<?php echo($msg);?>
Destroying a session
• A PHP session can be destroyed by session_destroy() function which
does not need any argument and a single call can destroy the session.
• Unsetting a single variable :
<?php
Unset($_SESSION[‘counter’])
?>
Call that destroys all the session variables:
<?php
Session_destroy()
?>
• PHP must be configured correctly in the php.ini file with the details of
how your system sends an email.
• Open php.ini file available in /etc/ directory and find the section
headed [mail function].
• For windows, 2 directives must be supplied.
• SMTP : Defines your email server address
• sendmail_from which defines your own address
• [mail function]
• ;For Win32 only.
• SMTP = smtp.secureserver.net
• ; For win32 only
• Sendmail_from = abc@xyz.com
Emails in PHP
The mail() function allows you to send emails directly from a script.
Syntax: (to,subject,message,headers,parameters)
To : Required, specifies the receivers of the email (receipient’s email
address)
Subject : Required, Cannot contain new line charachters
• Message:Required,Lines should not exceed 70 characters
• Headers:Optional, Specifies additional headers like cc, bcc
• Parameters: Optional, specifies an additional parameter to the
sendmail program
• As soon as the mail function is called, PHP will attempt to send the
email then it will return true if it is successful or false if it fails.
• Multiple recipients can be specified as the first argument to the mail()
function in a comma separated list.
<?php
$to = xyz@abc.com
$subject = “Subject”;
$message = “First php email”;
$header = “From : abc@xyz.com”;
$retval = mail($to,$subject,$message,$hearder)
If(retval==true)
Echo”Message sent successfully”;
Else
Echo”Message could not be sent”;
?>
PHP CODING STANDARD
Coding standard is required because there may be many developers working on
different modules so if they will start inventing their own standards then source
will become very un-manageable and it will become difficult to maintain that
source code in future.
Here are several reasons why to use coding specifications:
• Your peer programmers have to understand the code you produce. A coding
standard acts as the blueprint for all the team to decipher the code.
• Simplicity and clarity achieved by consistent coding saves you from common
mistakes.
• If you revise your code after some time then it becomes easy to understand that
code.
• Its industry standard to follow a particular standard to being more quality in
software.
There are few guidelines which can be followed while coding in PHP.
• Indenting and Line Length - Use an indent of 4 spaces and don't use any tab because different
computers use different setting for tab. It is recommended to keep lines at approximately 75-85
characters long for better code readability.
• Control Structures - These include if, for, while, switch, etc. Control statements should have one space
between the control keyword and opening parenthesis, to distinguish them from function calls. You
are strongly encouraged to always use curly braces even in situations where they are technically
optional.
Examples:
if ((condition1) || (condition2))
{ action1;
} elseif ((condition3) && (condition4))
{ action2;
} else
{ default action;
}
• Function Calls - Functions should be called with no spaces between the function
name, the opening parenthesis, and the first parameter; spaces between commas
and each parameter, and no space between the last parameter, the closing
parenthesis, and the semicolon. Here's an example:
$var = foo($bar, $baz, $quux);
• Function Definitions - Function declarations follow the "BSD/Allman style":
function fooFunction($arg1, $arg2 )
{
if (condition)
{ statement;
}
return $val;
}
• Comments - C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell
style comments (#) is discouraged.
• PHP Code Tags - Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required
for PHP compliance and is also the most portable way to include PHP code on differing operating
systems and setups.
• Variable Names -
• Use all lower case letters
• Use '_' as the word separator.
• Global variables should be prepended with a 'g'.
• Global constants should be all caps with '_' separators.
• Static variables may be prepended with 's'.
• Make Functions Re-entrant - Functions should not keep static variables that prevent a function from
being re-entrant.
• Alignment of Declaration Blocks - Block of declarations should be aligned.
PHP - Predefined Variables
PHP provides a large number of predefined variables to any script
which it runs.PHP provides an additional set of predefined arrays
containing variables from the web server the environment, and user
input. These new arrays are called superglobals:
All the following variables are automatically available in every scope.
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.
• enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply,
without this encoding the files cannot be sent through POST. If you want to allow a user to upload a file via a
form, you must use this enctype.
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.
• The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page
to /var/www/html directory which is document root of your PHP server and it will display all the file's detail
upon completion.
• Here is the code of uploader.php script which will take care of uploading a file.
• MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail protocol that lets people use
the protocol to exchange different kinds of data files on the Internet: audio, video, images, application programs, and other
kinds
PHP Files & I/O
• Opening a file
• Reading a file
• Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Reading a file
• Once a file is opened using fopen() function it can be read with a function called fread(). This function
requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
• The file's length can be found using the filesize() function which takes the file name as its argument
and returns the size of the file expressed in bytes.
• So here are the steps required to read a file with PHP.
1. Open a file using fopen() function.
2. Get the file's length using filesize() function.
3. Read the file's content using fread() function.
4. Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents on
the web page.
PHP for C Developers
The simplest way to think of PHP is as interpreted C that you can embed in HTML documents.
The language itself is a lot like C, except with untyped variables, a whole lot of Web-specific
libraries built in, and everything hooked up directly to your favorite Web server.
The syntax of statements and function definitions should be familiar, except that variables are
always preceded by $, and functions do not require separate prototypes.
Here we will put some similarities and diferences in PHP and C
• Similarities:
• Syntax: Broadly speaking, PHP syntax is the same as in C: Code is blank insensitive, statements are
terminated with semicolons, function calls have the same structure (my_function(expression1,
expression2)), and curly braces ({ and }) make statements into blocks. PHP supports C and C++-style
comments (/* */ as well as //), and also Perl and shell-script style (#).
• Operators: The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the
comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave
in PHP as they do in C.
• Control structures: The basic control structures (if, switch, while, for) behave as they do in C, including
supporting break and continue. One notable difference is that switch in PHP can accept strings as case
identifiers.
• Function names: As you peruse the documentation, you.ll see many function names that seem
identical to C functions.
Differences:
• Dollar signs: All variables are denoted with a leading $. Variables do not need to be declared in
advance of assignment, and they have no intrinsic type.
• Types: PHP has only two numerical types: integer (corresponding to a long in C) and double
(corresponding to a double in C). Strings are of arbitrary length. There is no separate character type.
• Type conversion: Types are not checked at compile time, and type errors do not typically occur at
runtime either. Instead, variables and values are automatically converted across types as needed.
• Arrays: Arrays have a syntax superficially similar to C's array syntax, but they are implemented
completely differently. They are actually associative arrays or hashes, and the index can be either a
number or a string. They do not need to be declared or allocated in advance.
• No structure type: There is no struct in PHP, partly because the array and object types together make
it unnecessary. The elements of a PHP array need not be of a consistent type.
• No pointers: There are no pointers available in PHP, although the typeless variables play a similar role.
PHP does support variable references. You can also emulate function pointers to some extent, in that
function names can be stored in variables and called by using the variable rather than a literal name.
• No prototypes: Functions do not need to be declared before their implementation is defined, as long
as the function definition can be found somewhere in the current code file or included files.
• Memory management: The PHP engine is effectively a garbage-collected environment (reference-
counted), and in small scripts there is no need to do any deallocation. You should freely allocate new
structures - such as new strings and object instances. IN PHP5, it is possible to define destructors for
objects, but there is no free or delete. Destructors are called when the last reference to an object goes
away, before the memory is reclaimed.
• Compilation and linking: There is no separate compilation step for PHP scripts.
• Permissiveness: As a general matter, PHP is more forgiving than C (especially in its type system) and so
will let you get away with new kinds of mistakes. Unexpected results are more common than errors.
Common uses of PHP
• PHP performs system functions, i.e. from files on a system it can
create, open, read, write, and close them.
• PHP can handle forms, i.e. gather data from files, save data to a file,
thru email you can send data, return data to the user.
• You add, delete, modify elements within your database thru PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your
website.
• It can encrypt data.
Advantages:
• Open source: It is developed and maintained by a large group of PHP developers,
this will helps in creating a support community, abundant extension library.
• Speed: It is relative fast since it uses much system resource.
• Easy to use: It uses C like syntax, so for those who are familiar with C, it’s very
easy for them to pick up and it is very easy to create website scripts.
• Powerful library support: You can easily find functional modules you need such as
PDF, Graph etc.
• Built-in database connection modules: You can connect to database easily using
PHP, since many websites are data/content driven, so we will use database
frequently, this will largely reduce the development time of web apps.
• Can be run on many platforms, including Windows, Linux and Mac, it’s easy for
users to find hosting service providers.
Disadvantages:
• Security : Since it is open sourced, so all people can see the source
code, if there are bugs in the source code, it can be used by people to
explore the weakness of PHP
• Not suitable for large applications: Hard to maintain since it is not
very modular.

More Related Content

What's hot

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Studyhernanibf
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8rajkumar2011
 
Pragmatische Plone Projekte
Pragmatische Plone ProjektePragmatische Plone Projekte
Pragmatische Plone ProjekteAndreas Jung
 
Pragmatic plone projects
Pragmatic plone projectsPragmatic plone projects
Pragmatic plone projectsAndreas Jung
 
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...Michael Pirnat
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Doing more with LESS
Doing more with LESSDoing more with LESS
Doing more with LESSjsmith92
 
Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)julien pauli
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsEnrico Zimuel
 
Linux, Apache, Mysql, PHP
Linux, Apache, Mysql, PHPLinux, Apache, Mysql, PHP
Linux, Apache, Mysql, PHPwebhostingguy
 

What's hot (18)

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Sa
SaSa
Sa
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
 
Pragmatische Plone Projekte
Pragmatische Plone ProjektePragmatische Plone Projekte
Pragmatische Plone Projekte
 
Pragmatic plone projects
Pragmatic plone projectsPragmatic plone projects
Pragmatic plone projects
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
 
Introduction to php web programming - get and post
Introduction to php  web programming - get and postIntroduction to php  web programming - get and post
Introduction to php web programming - get and post
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Doing more with LESS
Doing more with LESSDoing more with LESS
Doing more with LESS
 
Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applications
 
Linux, Apache, Mysql, PHP
Linux, Apache, Mysql, PHPLinux, Apache, Mysql, PHP
Linux, Apache, Mysql, PHP
 
PHP Profiling/performance
PHP Profiling/performancePHP Profiling/performance
PHP Profiling/performance
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 

Viewers also liked

An incremental and distributed inference methodfor large scale ontologies bas...
An incremental and distributed inference methodfor large scale ontologies bas...An incremental and distributed inference methodfor large scale ontologies bas...
An incremental and distributed inference methodfor large scale ontologies bas...LeMeniz Infotech
 
Digi pack evaluation
Digi pack evaluationDigi pack evaluation
Digi pack evaluationCarly Davis
 
A hybrid cloud approach for secure authorized deduplication
A hybrid cloud approach for secure authorized deduplicationA hybrid cloud approach for secure authorized deduplication
A hybrid cloud approach for secure authorized deduplicationLeMeniz Infotech
 
Wave 1 - Web 2.0 The Global Impact | UM | Social Media Tracker
Wave 1 - Web 2.0 The Global Impact | UM | Social Media TrackerWave 1 - Web 2.0 The Global Impact | UM | Social Media Tracker
Wave 1 - Web 2.0 The Global Impact | UM | Social Media TrackerUM Wave
 
June 1 announcements
June 1 announcementsJune 1 announcements
June 1 announcementsEarl Oswalt
 
Наука и инновации ИНЭК-Поволжье
Наука и инновации ИНЭК-ПоволжьеНаука и инновации ИНЭК-Поволжье
Наука и инновации ИНЭК-Поволжьеdvdanilov
 
Discontinuous modulation scheme for a differential mode cuk inverter
Discontinuous modulation scheme for a differential mode cuk inverterDiscontinuous modulation scheme for a differential mode cuk inverter
Discontinuous modulation scheme for a differential mode cuk inverterLeMeniz Infotech
 
Hadoop recognition of biomedical named entity using conditional random fields...
Hadoop recognition of biomedical named entity using conditional random fields...Hadoop recognition of biomedical named entity using conditional random fields...
Hadoop recognition of biomedical named entity using conditional random fields...LeMeniz Infotech
 
Topology review and derivation methodology of single phase transformerless ph...
Topology review and derivation methodology of single phase transformerless ph...Topology review and derivation methodology of single phase transformerless ph...
Topology review and derivation methodology of single phase transformerless ph...LeMeniz Infotech
 
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)SergioPrezFelipe
 
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)SergioPrezFelipe
 
Stress analysis cover.ipt
Stress analysis cover.iptStress analysis cover.ipt
Stress analysis cover.iptwalid elsibai
 
Ncc technology presentation
Ncc technology presentationNcc technology presentation
Ncc technology presentationjowilson615
 
Darien Project: Solar Energy in the Wouman Village
Darien Project: Solar Energy in the Wouman VillageDarien Project: Solar Energy in the Wouman Village
Darien Project: Solar Energy in the Wouman VillageThe Solar Biz
 
Dominating set and network coding based routing in wireless mesh netwoks
Dominating set and network coding based routing in wireless mesh netwoksDominating set and network coding based routing in wireless mesh netwoks
Dominating set and network coding based routing in wireless mesh netwoksLeMeniz Infotech
 
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anni
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anniPresentazione mostra immigrazione madiba - per le scuole bambini di 8-10anni
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anniEros Campofiloni
 
Retouched pictures
Retouched picturesRetouched pictures
Retouched picturesmdrouet44
 

Viewers also liked (19)

An incremental and distributed inference methodfor large scale ontologies bas...
An incremental and distributed inference methodfor large scale ontologies bas...An incremental and distributed inference methodfor large scale ontologies bas...
An incremental and distributed inference methodfor large scale ontologies bas...
 
Digi pack evaluation
Digi pack evaluationDigi pack evaluation
Digi pack evaluation
 
A hybrid cloud approach for secure authorized deduplication
A hybrid cloud approach for secure authorized deduplicationA hybrid cloud approach for secure authorized deduplication
A hybrid cloud approach for secure authorized deduplication
 
The middle ages
The middle ages The middle ages
The middle ages
 
Q3
Q3Q3
Q3
 
Wave 1 - Web 2.0 The Global Impact | UM | Social Media Tracker
Wave 1 - Web 2.0 The Global Impact | UM | Social Media TrackerWave 1 - Web 2.0 The Global Impact | UM | Social Media Tracker
Wave 1 - Web 2.0 The Global Impact | UM | Social Media Tracker
 
June 1 announcements
June 1 announcementsJune 1 announcements
June 1 announcements
 
Наука и инновации ИНЭК-Поволжье
Наука и инновации ИНЭК-ПоволжьеНаука и инновации ИНЭК-Поволжье
Наука и инновации ИНЭК-Поволжье
 
Discontinuous modulation scheme for a differential mode cuk inverter
Discontinuous modulation scheme for a differential mode cuk inverterDiscontinuous modulation scheme for a differential mode cuk inverter
Discontinuous modulation scheme for a differential mode cuk inverter
 
Hadoop recognition of biomedical named entity using conditional random fields...
Hadoop recognition of biomedical named entity using conditional random fields...Hadoop recognition of biomedical named entity using conditional random fields...
Hadoop recognition of biomedical named entity using conditional random fields...
 
Topology review and derivation methodology of single phase transformerless ph...
Topology review and derivation methodology of single phase transformerless ph...Topology review and derivation methodology of single phase transformerless ph...
Topology review and derivation methodology of single phase transformerless ph...
 
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
 
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
Strong Nuclear Force and Quantum Vacuum as Gravity (FUNDAMENTAL TENSOR)
 
Stress analysis cover.ipt
Stress analysis cover.iptStress analysis cover.ipt
Stress analysis cover.ipt
 
Ncc technology presentation
Ncc technology presentationNcc technology presentation
Ncc technology presentation
 
Darien Project: Solar Energy in the Wouman Village
Darien Project: Solar Energy in the Wouman VillageDarien Project: Solar Energy in the Wouman Village
Darien Project: Solar Energy in the Wouman Village
 
Dominating set and network coding based routing in wireless mesh netwoks
Dominating set and network coding based routing in wireless mesh netwoksDominating set and network coding based routing in wireless mesh netwoks
Dominating set and network coding based routing in wireless mesh netwoks
 
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anni
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anniPresentazione mostra immigrazione madiba - per le scuole bambini di 8-10anni
Presentazione mostra immigrazione madiba - per le scuole bambini di 8-10anni
 
Retouched pictures
Retouched picturesRetouched pictures
Retouched pictures
 

Similar to PHP language presentation

HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.jssouridatta
 
Introduction to PHP.pptx
Introduction to PHP.pptxIntroduction to PHP.pptx
Introduction to PHP.pptxSherinRappai
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilitiesDefconRussia
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersMohammed Mushtaq Ahmed
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckrICh morrow
 
Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Mohd Harris Ahmad Jaal
 
Securing Your Webserver By Pradeep Sharma
Securing Your Webserver By Pradeep SharmaSecuring Your Webserver By Pradeep Sharma
Securing Your Webserver By Pradeep SharmaOSSCube
 
php fundamental
php fundamentalphp fundamental
php fundamentalzalatarunk
 

Similar to PHP language presentation (20)

Php reports sumit
Php reports sumitPhp reports sumit
Php reports sumit
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
php 1
php 1php 1
php 1
 
Introduction to PHP.pptx
Introduction to PHP.pptxIntroduction to PHP.pptx
Introduction to PHP.pptx
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
 
INTRODUCTION to php.pptx
INTRODUCTION to php.pptxINTRODUCTION to php.pptx
INTRODUCTION to php.pptx
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1
 
Php unit i
Php unit iPhp unit i
Php unit i
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Securing Your Webserver By Pradeep Sharma
Securing Your Webserver By Pradeep SharmaSecuring Your Webserver By Pradeep Sharma
Securing Your Webserver By Pradeep Sharma
 
php fundamental
php fundamentalphp fundamental
php fundamental
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 

PHP language presentation

  • 1. PHP • Amol Gharpure-13 • Apurva Bharatiya-17 • Annujj Agarwal-06 • Nirmiti Dhurve-30
  • 2. Background • Started as a Perl hack in 1994 by Rasmus Lerdorf (to handle his resume), developed to PHP/FI 2.0 • By 1997 up to PHP 3.0 with a new parser engine by Zeev Suraski and Andi Gutmans • Version 5.2.4 is current version, rewritten by Zend (www.zend.com) to include a number of features, such as an object model • Current is version 5 • php is one of the premier examples of what an open source project can be
  • 3. Why PHP? • You can build dynamic pages with just the information in a php script • But where php shines is in building pages out of external data sources, so that the web pages change when the data does • Most of the time, people think of a database like MySQL as the backend, but you can also use text or other files, LDAP, pretty much anything….
  • 4. INTRODUCTION • HYPERTEXT PREPROCESSOR (PHP) is a server side scripting language that is embedded in HTML. • Used to manage dynamic content, databases, sessions tracking, even built entire e-commerce site. • It is integrated with a number of popular databases, including MySQL, Oracle, Microsoft SQL Server, etc. • Can also be used as general-purpose programming language. • PHP code can be simply mixed with HTML code, or it can be used in combination with various templating engines and web frameworks.
  • 5. Continued… • PHP code is usually processed by a PHP interpreter, which is usually implemented as a web server’s native module. • After the PHP code is interpreted and executed, the web server sends resulting output to its client, usually in form of a part of the generated web page; for example, PHP code can generate a web page’s HTML code, an image, or some other data. • PHP has also evolved to include a command-line interface(CLI) capability and can be used in standalone graphical applications.
  • 6. PHP Scripts • Typically file ends in .php--this is set by the web server configuration • Separated in files with the <?php ?> tag • php commands can make up an entire file, or can be contained in html--this is a choice…. • Program lines end in ";" or you get an error • Server recognizes embedded script and executes • Result is passed to browser, source isn't visible • <P> • <?php $myvar = "Hello World!"; • echo $myvar; • ?> • </P>
  • 7. Parsing • We've talk about how the browser can read a text file and process it, that's a basic parsing method • Parsing involves acting on relevant portions of a file and ignoring others • Browsers parse web pages as they load • Web servers with server side technologies like php parse web pages as they are being passed out to the browser
  • 8. Two Ways • You can embed sections of php inside html: <BODY> <P> <?php $myvar = "Hello World!"; echo $myvar; </BODY> • Or you can call html from php: <?php echo "<html><head><title>Howdy</title> … ?>
  • 9. How to run a PHP file? • PHP files first need to be processed in a web server before sending their output to the web browser. • Therefore before running PHP files, they should be placed inside the web folder of a web server and then make a request to desired PHP file by typing its URL in the web browser. If you installed a web server in your computer, usually the root of its web folder can be accessed by typing http://localhost in the web browser. So, if you placed a file called hello.php inside its web folder, you can run that file by calling http://localhost/hello.php.
  • 10. Basic Syntax • Syntax based on Perl, Java, and C • The PHP parsing engine needs a way to differentiate PHP code from other elements. The mechanism for doing so is known as ‘encapsing to PHP’’. There are four ways to do it: • Canonical PHP tags: <?php..?> • Short-Open(SGML-style) tags: <?....?> • ASP-style tags: <%...%> • HTML script tags: • <script language=“PHP”>…</script>
  • 11. Comments • There are two commenting formats in PHP: 1. Single-line comments 2. Multi-line comments <? #This is a comment //So is this a comment /*This is the second line of comment This is a comment too*/ print ”An example with single line comments”; ?>
  • 12. Continued(Basic Syntax)… • PHP is case sensitive. • For example <html> <body> <? $capital=67; print(“Variable capital is $capital<br>”); print(“Variable capiTal is $capiTal<br>”); ?> Output: Variable capital is 67 Variable capiTal is
  • 13. Three-tiered Web Site: LAMP Client User-agent: Firefox Server Apache HTTP Server example request GET / HTTP/1.1 Host: www.tamk.fi User-Agent: Mozilla/5.0 (Mac..) ... response Database MySQL PHP
  • 14. Variables • Variables in PHP are represented by a dollar sign • PHP supports eight types: • boolean, integer, float, double, array, object, resource and NULL
  • 15. Example (php.net) <?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool"; } ?>
  • 16. Naming Variables • Case-sensitivity • Start with letter or _ • After that you can have numbers, letters and _ • $var = 'Barney'; • $Var = ‘MiaKhalifa'; • print "$var, $Var"; • $4site = ‘Legendary'; • $_4site = ‘LAMP';
  • 17. Constants • You cannot alter the value of constant after declaration • define(CONSTANT, "value"); • print CONSTANT;
  • 18. Example <?php $a = “Paul "; print ”For " . $a; ?>
  • 19. <?php $a = “Batman"; function Test() { print $a; } print ”Bruce Wayne is ”; Test(); ?> Example
  • 20. Control Structures • If, else, elseif, switch • while, do-while, for • foreach • break, continue •
  • 21. Statements • Every statement ends with ; • $a = 5; • $a = function(); • $a = ($b = 5); • $a++; ++$a; • $a += 3;
  • 22. Operators • Arithmethic: +,-,*,% • Setting variable: = • Bit: &, |, ^, ~, <<, >> • Comparison: ==, ===, !=, !==, <, > <=, >=
  • 23. Logical Operators • $a and $b • $a or $b • $a xor $b • !$a; • $a && $b; • $a || $b;
  • 24. IF <?php if ($a > $b) { echo "a is bigger than b"; } else { echo "a is NOT bigger than b"; } if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?>
  • 25. While and Do-While <?php $a=0; while($a<10){ print $a; $a++; } $i = 0; do { print $i; } while ($i > 0); ?>
  • 26. For for ($i = 1; $i <= 10; $i++) { print $i; }
  • 27. Foreach $arr = array(1, 2, 3, 4); foreach ($arr as $value) { echo $value; }
  • 28. Switch switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; }
  • 30. What is a cookie? A cookie is a small text file that is stored on a user’s computer. Each cookie on the user’s computer is connected to a particular domain. Each cookie can be used to store upto 4kB of data. A maximum of 20 cookies can be stored on a user’s pc per domain.
  • 31. Example(1) • User sends a request for page at www.example.com for the first time. PAGE REQUEST
  • 32. Example (2) • Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s pc. XHTML COOKIE DATA
  • 33. Example(1) • At the next page request for domain www.example.com, all the cookie data associated with this domain is sent too. Page request Cookie data
  • 34. Set a cookie • setcookie (name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when the browser is closed. path = path on the server within and below which the cookie is available on. domain = domain at which the cookie is available on. secure = If cookie should be sent over HTTPS connection only. Default false.
  • 35. Set a cookie-examples • setcookie (‘name’, ‘Robert’) • This command will set the cookie called name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it(the default path and domain). It will expire and be deleted when the browser is closed (default expire).
  • 36. Set a cookie-examples • setcookie (’age’, ‘20’, time () +60*60*24*30) • This command will set the cookie called age on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.
  • 37. Set a cookie-examples • setcookie ( ‘gender’ , ’male’ , 0 , ’/’ ) • This command will set the cookie called gender on the user’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.
  • 38. Read cookie data • All cookie data is available through the superglobal $_COOKIE: • $variable = $_COOKIE[‘cookie_name’] • OR • $variable = $HTTP_COOKIE_VARS[‘cookie_name’] ; e.g. $age = $_COOKIE[‘age’]
  • 39. Storing an array.. • Only strings can be stored in Cookie files. • To store an array in a cookie, convert it to a string by using the serialize() PHP function. • The array can be reconstructed using the unserialize() function once it had been read back in. • Remember cookie size is limited.
  • 40. Delete a cookie • To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past.. • setcookie (‘cookie_name’, ‘’, time () -6000) • Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.
  • 41. Malicious Cookie Usage • There is a bit of a stigma attached to cookies – and they can be maliciously used (e.g. set via 3rd party banner ads). • The important thing is to note is that some people browse with them turned off. e.g. in FF, Tools>Options>Privacy
  • 42. The USER is in control • Cookies are stored client-side, so never trust them completely: They can be easily viewed, modified or created by a 3rd party. • They can be turned on and off at will by the user.
  • 44. User Profile Server web serverweb serverWeb Server Scripts LoadBalancer Ad Server Web Services Apache Server Architecture
  • 45. Three-tiered Web Site: LAMP Client User-agent: Firefox Server Apache HTTP Server example request GET / HTTP/1.1 Host: www.tamk.fi User-Agent: Mozilla/5.0 (Mac..) ... response Database MySQL PHP
  • 46. Server Side Techniques • Server side scripting requires installation on the server side • Typically client siis only xhtml and it unaware that the xhtml was produced by a server side script • Does not require any installations or add-ons on the client
  • 47. Server Side Techniques • PHP • Java EE: Servlet, JSP • .NET • CGI / Perl (Very old) • Ruby • …
  • 48. Client Side Techniques • Requires that the client supports the technique • JavaScript, Applet, Flash…
  • 49. Web Application Frameworks • A web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services. • Numerous frameworks available for many languages
  • 50. Web App vs. Web Site? • What’s the difference between Web App and Web Site? • Rich Internet Application?, AJAX?, Thin Client? • Full application running in your browser or just a web site?
  • 51. Server Variables The $_SERVER array variable is a reserved variable that contains all server information. <html><head></head> <body> <?php echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "User's IP address: " . $_SERVER["REMOTE_ADDR"]; ?> <?php echo "<br/><br/><br/>"; echo "<h2>All information</h2>"; foreach ($_SERVER as $key => $value) { echo $key . " = " . $value . "<br/>"; } ?> </body> </html> The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script. $_SERVER info on php.net
  • 53. • PHP functions are similar to other programming languages. (A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.) • PHP has built-in functions but it gives you an option to create your own functions as well. • There are two parts: • Creating a PHP Function • Calling a PHP Function • In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
  • 54. Array functions Function Description array() Creates an array Array chunk() Splits an array into chunks of arrays Array count values() Returns an array with the number of occurrences for each value Array flip() Exchanges all keys with their associated values in an array Array map() Sends each value of an array to a user-made function, which returns new values Array pop() Deletes the last element of an array Array push() Inserts one or more elements to the end of an array
  • 55. Class and object functions Function Description get_class_vars() Get the default properties of the class get_class() Returns the name of the class of an object get_declared_classes() Returns an array with the name of the defined classes get_object_vars() Gets the properties of the given object get_parent_class() Retrieves the parent class name for object or class method_exists() Checks if the class method exists property_exists() Checks if the object or class has a property
  • 56. Creating a PHP Function • Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it. • Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
  • 57. Sample code<html> <head> <title>Writing a PHP function</title> </head> <body> <?php /*Defining a functions*/ function writeMessage() { echo"Hello"; } ?> </body>
  • 58. Passing parameters • We can pass as many parameters as we want. • They act like variables inside the function. • The following example takes 2 integer parameters and adds them.
  • 59. • <?php • function addFunction($num1,$num2) • { • $sum=$num1+$num2; • echo "Sum of the 2 numbers is:$sum"; • } • addFunction(10,20); • ?> • </body> • </html>
  • 60. Passing Parameters by reference • It is possible to pass arguments by reference. • A reference to the variable is manipulated rather than modifying its copy. • An ampersand has to be added to the variable name. • We have to pass parameters by reference when multiple values have to be returned.
  • 61. • <?php • function addFive($num) • { • $num += 5; • } • function addSix(&$num) • { • $num += 6; • } • $orignum = 10; • addFive( &$orignum ); • echo "Original Value is $orignum<br />"; • addSix( $orignum ); • echo "Original Value is $orignum<br />"; • ?> • </body> • </html>
  • 62. • <?php • function addFunction($num1, $num2) • { • $sum = $num1 + $num2; • return $sum; • } • $return_value = addFunction(10, 20); • echo "Returned value from the function : $return_value"; • ?>
  • 63. Form handling • The PHP superglobals $_GET and $_POST are used to collect form- data. (Superglobals can be accessed by any function.) • When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP filenamed "welcome.php". The form data is sent with the HTTP POST method.
  • 64. • To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this: • <html> • <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> • </body> • </html>
  • 65. When to use GET? • Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. • GET may be used for sending non-sensitive data. • Note: GET should NEVER be used for sending passwords or other sensitive information!
  • 66. When to use POST? • Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send. • Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. • However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
  • 67. Sessions • An alternative way to make data accessible across the various pages of an entire website is to use php sessions. • A session creates a file in a temporary directory on the server where registered session variables and their values are stored. • This data will be available to all the pages on the site during that visit. • The location of the temporary file is determined by setting it in the php.ini file called session.save_path • Before using session variables we have to set this path. • A session ends after the user loses the browser or after leaving the site, the server will terminate the session after a predetermined time, usually 30 mins.
  • 68. What happens when a session is created? • PHP first creates a unique identifier for that particular session which is a random string of 32hexadecimal string. • A cookie called PHPSESSID is automatically sent to the user’s computer to store unique identification string. • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ followed by the 32hex string.
  • 69. Starting a PHP session • A PHP session is started by calling session_start(), it checks if a session has already started, if not, it starts on. This is usually done at the beginning of the page. • Session variables are stored in an array called $_SESSION, these variables are accessible during the lifetime of the session. • In the example, a variable counter is registered which increments each time the page is visited during the session.
  • 71. Destroying a session • A PHP session can be destroyed by session_destroy() function which does not need any argument and a single call can destroy the session. • Unsetting a single variable : <?php Unset($_SESSION[‘counter’]) ?> Call that destroys all the session variables: <?php Session_destroy() ?>
  • 72. • PHP must be configured correctly in the php.ini file with the details of how your system sends an email. • Open php.ini file available in /etc/ directory and find the section headed [mail function]. • For windows, 2 directives must be supplied. • SMTP : Defines your email server address • sendmail_from which defines your own address
  • 73. • [mail function] • ;For Win32 only. • SMTP = smtp.secureserver.net • ; For win32 only • Sendmail_from = abc@xyz.com
  • 74. Emails in PHP The mail() function allows you to send emails directly from a script. Syntax: (to,subject,message,headers,parameters) To : Required, specifies the receivers of the email (receipient’s email address) Subject : Required, Cannot contain new line charachters
  • 75. • Message:Required,Lines should not exceed 70 characters • Headers:Optional, Specifies additional headers like cc, bcc • Parameters: Optional, specifies an additional parameter to the sendmail program
  • 76. • As soon as the mail function is called, PHP will attempt to send the email then it will return true if it is successful or false if it fails. • Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
  • 77. <?php $to = xyz@abc.com $subject = “Subject”; $message = “First php email”; $header = “From : abc@xyz.com”; $retval = mail($to,$subject,$message,$hearder) If(retval==true) Echo”Message sent successfully”; Else Echo”Message could not be sent”; ?>
  • 78. PHP CODING STANDARD Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future. Here are several reasons why to use coding specifications: • Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code. • Simplicity and clarity achieved by consistent coding saves you from common mistakes. • If you revise your code after some time then it becomes easy to understand that code. • Its industry standard to follow a particular standard to being more quality in software.
  • 79. There are few guidelines which can be followed while coding in PHP. • Indenting and Line Length - Use an indent of 4 spaces and don't use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability. • Control Structures - These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional. Examples: if ((condition1) || (condition2)) { action1; } elseif ((condition3) && (condition4)) { action2; } else { default action; }
  • 80. • Function Calls - Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example: $var = foo($bar, $baz, $quux); • Function Definitions - Function declarations follow the "BSD/Allman style": function fooFunction($arg1, $arg2 ) { if (condition) { statement; } return $val; }
  • 81. • Comments - C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged. • PHP Code Tags - Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups. • Variable Names - • Use all lower case letters • Use '_' as the word separator. • Global variables should be prepended with a 'g'. • Global constants should be all caps with '_' separators. • Static variables may be prepended with 's'. • Make Functions Re-entrant - Functions should not keep static variables that prevent a function from being re-entrant. • Alignment of Declaration Blocks - Block of declarations should be aligned.
  • 82. PHP - Predefined Variables PHP provides a large number of predefined variables to any script which it runs.PHP provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These new arrays are called superglobals: All the following variables are automatically available in every scope.
  • 83.
  • 84. 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
  • 85. 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.
  • 86. • enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST. If you want to allow a user to upload a file via a form, you must use this enctype.
  • 87.
  • 88. 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. • The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file's detail upon completion. • Here is the code of uploader.php script which will take care of uploading a file. • MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail protocol that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video, images, application programs, and other kinds
  • 89.
  • 90.
  • 91. PHP Files & I/O • Opening a file • Reading a file • Opening and Closing Files The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. Files modes can be specified as one of the six options in this table.
  • 92.
  • 93. Reading a file • Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes. • The file's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. • So here are the steps required to read a file with PHP. 1. Open a file using fopen() function. 2. Get the file's length using filesize() function. 3. Read the file's content using fread() function. 4. Close the file with fclose() function. The following example assigns the content of a text file to a variable then displays those contents on the web page.
  • 94.
  • 95. PHP for C Developers The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. The language itself is a lot like C, except with untyped variables, a whole lot of Web-specific libraries built in, and everything hooked up directly to your favorite Web server. The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes. Here we will put some similarities and diferences in PHP and C
  • 96. • Similarities: • Syntax: Broadly speaking, PHP syntax is the same as in C: Code is blank insensitive, statements are terminated with semicolons, function calls have the same structure (my_function(expression1, expression2)), and curly braces ({ and }) make statements into blocks. PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#). • Operators: The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C. • Control structures: The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers. • Function names: As you peruse the documentation, you.ll see many function names that seem identical to C functions.
  • 97. Differences: • Dollar signs: All variables are denoted with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type. • Types: PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). Strings are of arbitrary length. There is no separate character type. • Type conversion: Types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed. • Arrays: Arrays have a syntax superficially similar to C's array syntax, but they are implemented completely differently. They are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance. • No structure type: There is no struct in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type. • No pointers: There are no pointers available in PHP, although the typeless variables play a similar role. PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name.
  • 98. • No prototypes: Functions do not need to be declared before their implementation is defined, as long as the function definition can be found somewhere in the current code file or included files. • Memory management: The PHP engine is effectively a garbage-collected environment (reference- counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures - such as new strings and object instances. IN PHP5, it is possible to define destructors for objects, but there is no free or delete. Destructors are called when the last reference to an object goes away, before the memory is reclaimed. • Compilation and linking: There is no separate compilation step for PHP scripts. • Permissiveness: As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.
  • 99. Common uses of PHP • PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them. • PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user. • You add, delete, modify elements within your database thru PHP. • Access cookies variables and set cookies. • Using PHP, you can restrict users to access some pages of your website. • It can encrypt data.
  • 100. Advantages: • Open source: It is developed and maintained by a large group of PHP developers, this will helps in creating a support community, abundant extension library. • Speed: It is relative fast since it uses much system resource. • Easy to use: It uses C like syntax, so for those who are familiar with C, it’s very easy for them to pick up and it is very easy to create website scripts. • Powerful library support: You can easily find functional modules you need such as PDF, Graph etc. • Built-in database connection modules: You can connect to database easily using PHP, since many websites are data/content driven, so we will use database frequently, this will largely reduce the development time of web apps. • Can be run on many platforms, including Windows, Linux and Mac, it’s easy for users to find hosting service providers.
  • 101. Disadvantages: • Security : Since it is open sourced, so all people can see the source code, if there are bugs in the source code, it can be used by people to explore the weakness of PHP • Not suitable for large applications: Hard to maintain since it is not very modular.