php language presentation

101
PHP •Amol Gharpure-13 •Apurva Bharatiya-17 •Annujj Agarwal-06 •Nirmiti Dhurve-30

Upload: annujj-agrawaal

Post on 12-Apr-2017

253 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: PHP language presentation

PHP• Amol Gharpure-13• Apurva Bharatiya-17• Annujj Agarwal-06• Nirmiti Dhurve-30

Page 2: PHP language presentation

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

Page 3: PHP language presentation

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

Page 4: PHP language presentation

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.

Page 5: PHP language presentation

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.

Page 6: PHP language presentation

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>

Page 7: PHP language presentation

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

Page 8: PHP language presentation

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:<?phpecho "<html><head><title>Howdy</title>…?>

Page 9: PHP language presentation

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.

Page 10: PHP language presentation

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>

Page 11: PHP language presentation

Comments• There are two commenting formats in PHP:1. Single-line comments2. 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”; ?>

Page 12: PHP language presentation

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 67Variable capiTal is

Page 13: PHP language presentation

Three-tiered Web Site: LAMPClientUser-agent: Firefox

ServerApache HTTP Server

example requestGET / HTTP/1.1Host: www.tamk.fiUser-Agent: Mozilla/5.0 (Mac..)...

response

DatabaseMySQL

PHP

Page 14: PHP language presentation

Variables• Variables in PHP are represented by a dollar sign• PHP supports eight types:• boolean, integer, float, double, array, object, resource and NULL

Page 15: PHP language presentation

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

}

?>

Page 16: PHP language presentation

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

Page 17: PHP language presentation

Constants• You cannot alter the value of constant after declaration• define(CONSTANT, "value");• print CONSTANT;

Page 18: PHP language presentation

Example

<?php$a = “Paul ";print ”For " . $a;?>

Page 19: PHP language presentation

<?php$a = “Batman";function Test() { print $a;}print ”Bruce Wayne is ”;Test();?>

Example

Page 20: PHP language presentation

Control Structures• If, else, elseif, switch• while, do-while, for• foreach• break, continue•

Page 21: PHP language presentation

Statements• Every statement ends with ;• $a = 5;• $a = function();• $a = ($b = 5);• $a++; ++$a;• $a += 3;

Page 22: PHP language presentation

Operators• Arithmethic: +,-,*,%• Setting variable: =• Bit: &, |, ^, ~, <<, >>• Comparison: ==, ===, !=, !==, <, > <=, >=

Page 23: PHP language presentation

Logical Operators• $a and $b• $a or $b• $a xor $b• !$a;• $a && $b;• $a || $b;

Page 24: PHP language presentation

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

}

?>

Page 25: PHP language presentation

While and Do-While<?php$a=0;while($a<10){ print $a; $a++;}

$i = 0;do {   print $i;} while ($i > 0);?>

Page 26: PHP language presentation

For

for ($i = 1; $i <= 10; $i++) {   print $i;}

Page 27: PHP language presentation

Foreach$arr = array(1, 2, 3, 4);foreach ($arr as $value) {   echo $value;}

Page 28: PHP language presentation

Switchswitch ($i) {case 0:   echo "i equals 0";   break;case 1:   echo "i equals 1";   break;case 2:   echo "i equals 2";   break;}

Page 29: PHP language presentation

PHP COOKIES

Page 30: PHP language presentation

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.

Page 31: PHP language presentation

Example(1)• User sends a request for page at www.example.com for the first time.

PAGE REQUEST

Page 32: PHP language presentation

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

Page 33: PHP language presentation

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

Page 34: PHP language presentation

Set a cookie• setcookie (name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie namevalue = 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.

Page 35: PHP language presentation

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

Page 36: PHP language presentation

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.

Page 37: PHP language presentation

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.

Page 38: PHP language presentation

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

Page 39: PHP language presentation

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.

Page 40: PHP language presentation

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.

Page 41: PHP language presentation

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

Page 42: PHP language presentation

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.

Page 43: PHP language presentation

PHP WEB CONCEPTS

Page 44: PHP language presentation

UserProfileServer

web serverweb serverWeb Server

ScriptsLoad Balancer

AdServer

Web Services

Apache

Server Architecture

Page 45: PHP language presentation

Three-tiered Web Site: LAMPClientUser-agent: Firefox

ServerApache HTTP Server

example requestGET / HTTP/1.1Host: www.tamk.fiUser-Agent: Mozilla/5.0 (Mac..)...

response

DatabaseMySQL

PHP

Page 46: PHP language presentation

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

Page 47: PHP language presentation

Server Side Techniques• PHP• Java EE: Servlet, JSP• .NET• CGI / Perl (Very old)• Ruby• …

Page 48: PHP language presentation

Client Side Techniques• Requires that the client supports the technique• JavaScript, Applet, Flash…

Page 49: PHP language presentation

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

Page 50: PHP language presentation

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?

Page 51: PHP language presentation

Server VariablesThe $_SERVER array variable is a reserved variable that contains all server information.

<html><head></head><body>

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

Page 52: PHP language presentation

PHP functions

Page 53: PHP language presentation

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

Page 54: PHP language presentation

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

Page 56: PHP language presentation

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:

Page 57: PHP language presentation

Sample code<html><head><title>Writing a PHP function</title></head><body><?php/*Defining a functions*/function writeMessage(){echo"Hello";}?></body></html>

Page 58: PHP language presentation

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.

Page 59: PHP language presentation

• <?php• function addFunction($num1,$num2)• {• $sum=$num1+$num2;• echo "Sum of the 2 numbers is:$sum";• }• addFunction(10,20);• ?>• </body>• </html>

Page 60: PHP language presentation

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.

Page 61: PHP language presentation

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

Page 62: PHP language presentation

• <?php• function addFunction($num1, $num2)• {• $sum = $num1 + $num2;• return $sum;• }• $return_value = addFunction(10, 20);• echo "Returned value from the function : $return_value";• ?>

Page 63: PHP language presentation

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.

Page 64: PHP language presentation

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

Page 65: PHP language presentation

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!

Page 66: PHP language presentation

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.

Page 67: PHP language presentation

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.

Page 68: PHP language presentation

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.

Page 69: PHP language presentation

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.

Page 70: PHP language presentation

<?phpSession_start();If(isset($SESSION[‘counter’])){$_SESSION[‘counter’]+=1;}Else$_SESSION[‘counter’]=1;$msg=“You have visited this page”,$_SESSION[‘counter’];?><?php echo($msg);?>

Page 71: PHP language presentation

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 :<?phpUnset($_SESSION[‘counter’])?>Call that destroys all the session variables:<?phpSession_destroy()?>

Page 72: PHP language presentation

• 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

Page 73: PHP language presentation

• [mail function]• ;For Win32 only.• SMTP = smtp.secureserver.net• ; For win32 only• Sendmail_from = [email protected]

Page 74: PHP language presentation

Emails in PHPThe 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

Page 75: PHP language presentation

• 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

Page 76: PHP language presentation

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

Page 77: PHP language presentation

<?php$to = [email protected]$subject = “Subject”;$message = “First php email”;$header = “From : [email protected]”;$retval = mail($to,$subject,$message,$hearder)If(retval==true)Echo”Message sent successfully”;ElseEcho”Message could not be sent”;?>

Page 78: PHP language presentation

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.

Page 79: PHP language presentation

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

Page 80: PHP language presentation

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

Page 81: PHP language presentation

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

Page 82: PHP language presentation

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.

Page 83: PHP language presentation
Page 84: PHP language presentation

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

Page 85: PHP language presentation

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.

Page 86: PHP language presentation

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

Page 87: PHP language presentation
Page 88: PHP language presentation

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

Page 89: PHP language presentation
Page 90: PHP language presentation
Page 91: PHP language presentation

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.

Page 92: PHP language presentation
Page 93: PHP language presentation

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.

Page 94: PHP language presentation
Page 95: PHP language presentation

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

Page 96: PHP language presentation

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

Page 97: PHP language presentation

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.

Page 98: PHP language presentation

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

Page 99: PHP language presentation

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.

Page 100: PHP language presentation

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.

Page 101: PHP language presentation

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.