Introduction to PHP

Post on 15-Dec-2014

3447 Views

Category:

Education

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

this is study material for CDAA PG DAC students, this slide will lead you how PHP works

Transcript

1

C-D

AC

, Byte

s

New

Delh

i

Introduction to PHP Introduction to PHP

Prabhat Jonathan

2

What is PHP?

PHP stands for PHP: Hypertext Preprocessor

PHP is a server-side scripting language, like ASP

PHP scripts are executed on the server PHP supports many databases (MySQL,

Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

PHP is an open source software PHP is free to download and use PHP is an interpreted language.

3

What is a PHP File?

PHP files can contain text, HTML tags and scripts

PHP files are returned to the browser as plain HTML 

PHP files have a file extension of ".php", ".php3", or ".phtml"

4

Why PHP?

PHP runs on different platforms (Windows, Linux, Unix, etc.)

PHP is compatible with almost all servers used today (Apache, IIS, etc.)

PHP is FREE to download from the official PHP resource: www.php.net

PHP is easy to learn and runs efficiently on the server side

PHP is an open-source projec

5

A PHP Request

6

PHP: Development environment must contain at

least three components: A base operating system (OS) and server

environment (usually Linux) A Web server (usually Apache on Linux or IIS on

Windows) to intercept HTTP requests and either serve them directly or pass them on to the PHP interpreter for execution

A PHP interpreter to parse and execute PHP code, and return the results to the Web server

There’s also often a fourth optional but very useful component:

A database engine (such as MySQL) that holds application data, accepts connections from the PHP layer, and modifies or retrieves data from the database

7

PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.

<?php

// this line of code displays a famous quotation

echo ‘Love Can Make Any One Poet!';

?>

8

Comments in PHP

Single-line comments must be preceded by the // characters

multiline comments must be enclosed within a /* ... */ comment block

9

Mixing PHP with HTML

<html> <body><?phpecho "Hello World"; ?></body></html>

10

PHP Variables

A variable is simply a container that’s used to store both numeric and non-numeric information

Every variable name must be preceded with a dollar ($) symbol and must begin with a letter or underscore character

So, for example, $root, $_num, and $query2

11

Assigning Values to Variables

Assigning a value to a variable in PHP is quite easy: use the equality (=) symbol, which also happens to be PHP’s assignment operator.

<?php

// assign value to variable

$name = ‘Prabhat’;

?>

<h2>

Welcome to <?php echo $name; ?>'s Blog!

</h2>

12

Destroying Variables

<?php

// assign value to variable

$car = 'Porsche';

// print variable value

// output: 'Before unset(), my car is a Porsche'

echo "Before unset(), my car is a $car";

// destroy variable

unset($car);

// print variable value

// this will generate an 'undefined variable' error

// output: 'After unset(), my car is a '

echo "After unset(), my car is a $car";

?>

13

PHP Operators

14

Arithmetic Operators

15

Assignment Operators

= operator is Assignment Operator

16

Comparison Operators

17

Logical Operators

18

The if Statement

if (condition) code to be executed if condition is true;

<?php

// if number is less than zero

// print message

$number = -88;

if ($number < 0) {

echo 'That number is negative';

}

?>

19

The If...Else Statement

if (condition) code to be executed if condition is true;

else code to be executed if condition is

false;

20

<?php

// change message depending on whether

// number is less than zero or not

$number = -88;

if ($number < 0) {

echo 'That number is negative';

} else {

echo 'That number is either positive or zero';

}

?>

21

The if-elseif-else Statement<?php

// handle multiple possibilities

// define a different message for each day

$today = 'Tuesday';

if ($today == 'Monday') {

echo 'Monday\'s child is fair of face.';

} elseif ($today == 'Tuesday') {

echo 'Tuesday\'s child is full of grace.';

} elseif ($today == 'Wednesday') {

echo 'Wednesday\'s child is full of woe.';

} elseif ($today == 'Thursday') {

echo 'Thursday\'s child has far to go.';

} elseif ($today == 'Friday') {

echo 'Friday\'s child is loving and giving.';

} elseif ($today == 'Saturday') {

echo 'Saturday\'s child works hard for a living.';

} else {

echo 'No information available for that day';

}

?>

22

The switch-case Statement<?php

// handle multiple possibilities

// define a different message for each day

$today = 'Tuesday';

switch ($today) {

case 'Monday':

echo 'Monday\'s child is fair of face.';

break;

case 'Tuesday':

echo 'Tuesday\'s child is full of grace.';

break;

case 'Wednesday':

echo 'Wednesday\'s child is full of woe.';

break;

case 'Thursday':

echo 'Thursday\'s child has far to go.';

break;

case 'Friday':

echo 'Friday\'s child is loving and giving.';

break;

case 'Saturday':

echo 'Saturday\'s child works hard for a living.';

break;

default:

echo 'No information available for that day';

break;

}

?>

23

Repeating Actions with Loops

24

The while Statement

Syntax while (condition)

code to be executed; <?php

// repeat continuously until counter becomes 10

// output: 'xxxxxxxxx'

$counter = 1;

while ($counter < 10) {

echo 'x';

$counter++;

}

?>

25

The do-while Loop

Syntaxdo {

code to be executed; } while (condition);

26

<?php

// repeat continuously until counter becomes 10

// output: 'xxxxxxxxx'

$counter = 1;

do {

echo 'x';

$counter++;

} while ($counter < 10);

?>

27

The for Loop

Syntaxfor (init; cond; incr)

{ code to be executed; }

init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement.

cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends.

incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.

28

<?php

// repeat continuously until counter becomes 10

// output:

for ($x=1; $x<10; $x++) {

echo "$x ";

}

?>

29

PHP Functions

30

Create a PHP Function

All functions start with the word "function()"

Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)

Add a "{"  - The function code starts after the opening curly brace

Insert the function code Add a "}"  - The function is finished by a

closing curly brace

31

<?php function nme() { echo "Kya hal hae DAC !"; }nme();

?>

32

PHP Arrays

An array can store one or more values in a single variable name.

There are three different kind of arrays: Numeric array - An array with a numeric

ID key Associative array - An array where each

ID key is associated with a value Multidimensional array - An array

containing one or more arrays

33

Numeric Arrays

A numeric array stores each element with a numeric ID key.

$names = array("Prabhat",“Nitesh",“shudhanshu");

34

<? Php

$names[0] = “Arvind";

$names[1] = “Nitesh";

$names[2] = “shudhanshu";

echo $names[1] . " and " . $names[2] . " are ". $names[0] .

C-DAC Students ";

?>

35

Associative Arrays <?php

// define array

$fruits = array('apple', 'banana', 'pineapple', 'grape');

?>

36

The keys of the array must be unique

<?php

// define array

$fruits = array(

'a' => 'apple',

'b' => 'banana',

'p' => 'pineapple',

'g' => 'grape‘

Echo “$fruit[“a”] is gud friut”

);

?>

37

Multidimensional Arrays

onion, 0.50 apple, 2.50 orange, 2.00 chicken, 3.50 potato, 1.00 Fish,5.00

38

$foodPrices[‘onion’] = 0.50;$foodPrices[‘apple’] = 2.50;$foodPrices[‘orange’] = 2.00;$foodPrices[‘chicken’] = 3.50;$foodPrices[‘potato’] = 1.00;$foodPrices[‘fish’] = 5.00;

39

$foodPrices [‘vegetable’] [‘onion’] = 0.50;

$foodPrices [‘vegetable’] [‘potato’] = 1.00;

$foodPrices [‘fruit’] [‘apple’] = 2.50;$foodPrices [‘fruit’] [‘orange’] = 2.00;$foodPrices [‘meat’] [‘chicken’] = 3.50;$foodPrices [‘meat’] [‘fish’] = 5.00;

40

$foodPrices key value

vegetable onion Potato

0.501.00

fruit orangeapple

2.00 2.50

meat chickenFish

3.505.00

41

$foodPrices = array(

“vegetable”=>

array(“potato”=>1.00,

”onion”=>.50),

“fruit”=>

array(“apple”=>2.50,

”orange”=>2.00)

);

42

Using multidimensionalarrays in statements

$fishPrice = $foodPrices[‘meat’][‘fish’];echo “The price of fish is Rs .” $fishprice

;

43

Sorting an Array in PHP

sort(), to sort an array in ascending order

44

<?php

$narray[0]="Alfred";

$narray[1]="Robert";

$narray[2]="Deepak";

$narray[3]="Teresa";

$narray[4]="Joshua";

$narray[5]="Chandni";

$narray[6]="Sadiq";

$narray[7]="Vladimir";

for($i=0; $i<8; $i++)

{

print $narray[$i] . "<br />";

}

?>

45

The output of this PHP code is:

AlfredRobertDeepakTeresaJoshuaChandniSadiqVladimir

46

sort($narray);

for($i=0; $i<8; $i++){print $narray[$i] . "<br />";}

47

AlfredChandniDeepakJoshuaRobertSadiqTeresaVladimir

48

rsort($narray);

for($i=0; $i<8; $i++){print $narray[$i] . "<br />";}

49

Now the output is:

VladimirTeresaSadiqRobertJoshuaDeepakChandniAlfred

50

PHP Cookies

Users may set their browsers to refuse cookies

If your application depends on cookies, it won’t run if cookies are turned off.

PHP has features that work better than cookies.

PHP 5, PHP sessions can store information that is available for the entire session

You can store data in a database. Users can’t delete the data in your database

unexpectedly.

51

Setting Cookies with PHP:

PHP provided setcookie() function to set a cookie.

Name - This sets the variable name of the cookie and is stored in an environment variable called $_COOKIE or $HTTP_COOKIE_VARS variables. This variable is used while accessing cookies.

Value -This sets the value of the named variable and is the content that you actually want to store.

Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Setcookie (variable_name, value, expire);

52

setcookie(“state”,”UP”);echo “Your home state is “.

$_COOKIE[“state”];or

echo “Your home state is “. .$HTTP_COOKIE_VARS [“state”];

Your home state is UP

53

Setting expiration dates

The expiretime value sets the time when the cookie expires.

time: This function returns the current time in a format the computer can understand.

You use the time function plus a number of seconds to set the expiration time of the cookie

setcookie(“state”,”UP”,time()+3600); //expires in one hour

setcookie(“Name”,$Name,time()+(3*86400))//expires 3 days

54

mktime: This function returns a date and time in a format that the computer can understand. You must provide the desired date and time in the following order: hour, minute, second, month, day, and year

setcookie(“state”,”CA”,mktime(3,0,0,4,1,2009)); //Expires at 3:00 AM on April 1, 2009

setcookie(“state”,”CA”,mktime(13,0,0,,,));//expires at 1:00 PM today

55

isset()

isset() function to check if a cookie is set or not.

56

<html><head><title>Accessing Cookies with PHP</title></head><body><?php if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />"; else echo "Sorry... Not recognized" . "<br />";?></body></html>

57

PHP Sessions

A session is the time that a user spends at your Web site

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 pages on the site during that visit.

58

To make session information available, PHP does the following:

1. PHP assigns a session ID number.2. PHP stores the variables that you want saved for the session in

a file on the server3. PHP passes the session ID number to every page.4. PHP gets the variables from the session file for each new

session page The variables are available in the $_SESSION array.

5. A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30

minutes duration

59

Opening and closing sessions

Open the session with the session_start function, as follows:

session_start();The function first checks for an

existing session ID number. If it finds one, it sets up the session variables. If it doesn’t find one, it starts a new session by creating a new session ID number.

60

Storing a Session Variable

To save a variable in a session so that it’s available on later Web pages, store the value in the $_SESSION array, as follows:

$_SESSION[‘varname’] = “Prabhat”;

61

Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function

session_destroy() will reset your session and you will lose all your stored session data. This function does not need any argument

unset() function to unset a session variable. its need argument

62

session_destroy()

<?php session_destroy();?>

63

unset()

<?php unset($_SESSION['counter']);?>

64

Using a form to upload a file

You can display a form that allows a user to upload a file by using an HTML form designed for that purpose. The general format of the form is as follows:

65

The enctype attribute is used in the form tag. You must set this attribute to multipart/form-data when uploading a file to ensure the file arrives correctly.

A hidden field is included that sends a value (in bytes) for MAX_FILE_SIZE. If the user tries to upload a file that is larger than this value, it won’t upload. When sending the value for MAX_FILE_SIZE in your form, you need to consider two size settings in php.ini

The input field that uploads the file is of type file.

66

Note: The value for MAX_FILE_SIZE must be sent before the file is uploaded if you want the file size limit to apply to the uploading file.

If you don’t like the location of the temporary directory, you can change it by changing upload_tmp_dir in the php.ini file.

67

Accessing information aboutan uploaded file

Along with the file, information about the file is sent with the form. This information is stored in the PHP built-in array called $_FILES. $_FILES["fieldname"]["name"] - the name of the

uploaded file $_FILES["fieldname"]["type"] - the type of the

uploaded file $_FILES["fieldname"]["size"] - the size in bytes of the

uploaded file $_FILES["fieldname"]["tmp_name"] - the name of the

temporary copy of the file stored on the server $_FILES["fieldname"]["error"] - the error code

resulting from the file upload

68

For Example

suppose you use the following field to upload a file:<input type=”file” name=”user_file”>

If the user uploads a file named test.txt by using the form$_FILES[user_file][name] = test.txt$_FILES[user_file][type] = text/plain$_FILES[user_file][tmp_name] = D:\WINNT\

php92C.tmp$_FILES[user_file][size] = 435

69

Moving uploaded files to their destination

The general format of the statement that moves the file is as follows:move_uploaded_file(path/

tempfilename,path/permfilename);tempfilename:

element in $_FILES stores the temporary filename and location

move_uploaded_file($_FILES[‘user_file’][‘tmp_name’],‘c:\data\new_file.txt’);

70

Storing Data with PHP

Many applications require the long-term storage of information.

The information needs to be stored on the server

Information can be stored on the server in flat files or in databases.

Flat filesare text files stored in the computer file system.

Databasefor data storage requires you to install and learn

to use database software, such as MySQL or Oracle.

71

Using Flat Files

Using a flat file requires three steps:

1. Open the file.2. Write data into the file or retrieve data from the

file.3. Close the file.

72

Accessing files

$fh = fopen(“filename”,”mode”)The variable, $fh, referred to as a

file handle

73

The filename can be a simple filename (filename.txt), a path to the file (c:/data/filename.txt), or a URL (http://yoursite.com/filename.txt)

74

Opening files in read mode

$fh = fopen(“file1.txt”,”r”);If the file can’t be found, a warning

messageWarning: fopen(file1.txt): failed to open

stream: No such file or directory in d:\test2.php on line 12

Remember, a warning condition does not stop the script. The script continues to run, but the file doesn’t open, so any later statements that read orwrite to the file aren’t executed.

75

a die statement

$fh = fopen(“file1.txt”,”r”)or die(“Can’t open file”);

76

Opening files in write mode

$fh = fopen(“c:/testdir/file1.txt”,”w”);You can check whether a directory

exists before you try to write a file into it by using the following statements:

If(is_dir(“c:/tester”)){$fh = fopen(“c:/testdir/file1.txt”,”w”);}

77

Closing a file

To close a file after you have finished reading or writing it, use the following statement:

fclose($fh);

78

Writing to a file

After you open the file, you can write into it by using the fwrite statement, which has the following general format:

fwrite($fh,datatosave);

79

For example,$today = date(“Y-m-d”);$fh = fopen(“file2.txt”,”a”);fwrite($fh,$today);fclose($fh);

Note:-for data in separate line usefwrite($fh,$today”\n”);

80

Reading from a file

You can read from a file by using the fgets statement, which has the following general format:$line = fgets($fh)

$fh holds the pointer to the open filePHP recognizes the end of the file,

and provides a function feof to tell you when you reach the end of the file.

81

while(!feof($fh)){$line = fgets($fh);echo “$line;}

82

Working with Databases

There are a large number of database management systems currently available, some commercial and some free

IBM DB2 Informix Ingres Microsoft SQL Server (MS SQL) mSQL MySQL Oracle PostgreSQL Sybase

83

Choosing a RDBMS

Choosing a RDBMS depends on your needs.

CostFeaturesResources

Some RDBMSs require more resources, such as disk space and memory, than others. Like oracle

84

Understanding Databases, Records, and Primary Keys

85

Understanding SQL Statements

Data Definition Language (DDL) DDL consists of statements that define the structure and relationships of a database and its tables. Typically, these statements are used to create, delete, and modify databases and tables; specify field names and types; and set indexes.

86

● Data Manipulation Language (DML) DML statements are related to altering and extracting data from a database. These statements are used to add records to, and delete records from, a database; perform queries; retrieve table records matching one or more user-specified criteria; and join tables together using their common fields.

87

● Data Control Language (DCL) DCL statements are used to define access levels and security privileges for a database. You would use these statements to grant or deny user privileges; assign roles; change passwords; view permissions; and create rule sets to protect access to data.

88

89

Creating and Populating a Database

Creating the Databasemysql> CREATE DATABASE music;

Query OK, 1 row affected (0.05 sec)

Next, select this newly database as the default for all future commands with the USE statement:mysql> USE music;

Database changed

90

Adding Tables

mysql> CREATE TABLE artists (-> artist_id INT(4) NOT NULL

PRIMARY KEY AUTO_INCREMENT,-> artist_name VARCHAR (50) NOT

NULL,-> artist_country CHAR (2) NOT

NULL-> );

Query OK, 0 rows affected (0.07 sec)

91

The NOT NULL modifier ensures that the field cannot accept a NULL value after each field definition

The PRIMARY KEY modifier marks the corresponding field as the table’s primary key.

The AUTO_INCREMENT modifier, which is only available for numeric fields, tells MySQL to automatically generate a value for this field every time a new record is inserted into the table, by incrementing the previous value by 1.

92

MySQL Data Types

93

Adding Records

mysql> INSERT INTO artists (artist_id, artist_name, artist_country)

-> VALUES ('1', 'Aerosmith', 'US');

Query OK, 1 row affected (0.00 sec)

94

Executing Queries

SQL allows you to search for records matching specific criteria using the SELECT statement

mysql> SELECT artist_id, artist_name FROM artists;

artist_id artist_name

1 Kishore

2 Rafi

3 Lata

3 rows in set (0.00 sec)

95

Using PHP with a database

Whichever database you’re using, the steps to interact with a database are similar:

1. Connect to the database.2. Send an SQL query that contains

instructions for the database software.3. If you retrieved data from the database,

process the data.4. Close the connection to the database.

96

Connecting to the database

Location: The database does not need to be on the same

computer where PHP is installed. Therefore, you need to tell the PHP connect function the name of the computer where the database is located (the hostname). You can supply either a domain name (such as mycompany.com) or an IP address (such as 172.17.204.2). If the database is on the same computer as PHP, you can use localhost for the hostname.

Account name You must provide a valid account name that can be

used to access the database. The database administrator sets this up. If you’re using a Web hosting company, you will be given a valid account name.

97

Password:You have to have a valid password to access

the database. The database administrator sets this up. If you’re using a Web hosting company, you will be given a valid password for your account.

Database name:An RDBMS can create and maintain many

databases, so you need to tell it which database you want to use.

98

$host = “localhost”;$account = “admin”;$password = “secret”;$dbname = “music”;

99

The basic command

mysql_connect($hos, $account, $password); The password is optional, depending on

whether this particular database user requires one (it’s a good idea). If not, just leave that variable off.

100

mysqli function

mysqli_connect, which adds a fourth parameter allowing you to select a database in the same function you use to connect.

mysqli_connect($hos, $account, $password, $dbname );

101

mysql_select_db

If you need it only if you want to use multiple databases on the same connection.

Next, you’ll want to choose a database to work on:

mysql_select_db($database);if you’re using variables; or

mysql_select_db(‘phpbook’);if you’re using a literal string.

102

mysql_query()

A database query from PHP is basically a MySQL command wrapped up in a tiny PHP function called mysql_query(). This is where you use the basic SQL workhorses of SELECT, INSERT, UPDATE, and DELETE

103

mysql_query(“SELECT * FROM Product WHERE ID<10”);

Or$query = “SELECT * FROM Product

WHERE ID<10”;$result = mysql_query($query);

104

Fetching Data Sets

mysql_fetch_row: Returns row as an enumerated array

mysql_fetch_object: Returns row as an object

mysql_fetch_array: Returns row as an associative array

mysql_result: Returns one cell of data

105

mysql_fetch_row

$query = “SELECT ID, LastName, FirstNameFROM users WHERE Status = 1”;$result = mysql_query($query);while ($name_row = mysql_fetch_row($result)) {print(“$name_row[0] $name_row[1]

$name_row[2]<BR>\n”);}

This code will output the specified rows from the database, each line containing one row orthe information associated with a unique ID (if any).

106

mysql_fetch_object

Function do the same task, except the row is returned as an object rather than an array.

$query = “SELECT ID, LastName, FirstNameFROM users WHERE Status = 1”;$result = mysql_query($query);while ($row = mysql_fetch_object($result)) {echo “$row->ID, $row->LastName, $row-

>FirstName<BR>\n”;}

107

mysql_fetch_array

This function offers the choice of results as an associative or an enumerated array or both

$query = “SELECT ID, LastName, FirstNameFROM users WHERE Status = 1”;$result = mysql_query($query);while ($row = mysql_fetch_array($result))

{echo “$row[‘ID’], $row[‘LastName’],

$row[‘FirstName’]<BR>\n”;}

108

Remember that mysql_fetch_array can also be used exactly the same way as mysql_fetch_row—with numerical identifiers rather than field names.

109

Setting up PHP to send e-mail

E-mail is sent by an outgoing e-mail server. To send e-mail, you need access to an outgoing server. If you can send e-mail from your own computer right now, you’re using an outgoing server.

Your outgoing mail server is typically an SMTP (Simple Mail Transfer Protocol) server. Whether you use a LAN at work, a cable modem at home, or an ISP via a modem, you send your mail with an SMTP server, and the server has an address that you need to know.

110

With the name of your outgoing mail server in front of you, open php.ini

[mail function]; For Win32 only.SMTP = localhost; For Win32 only.;sendmail_from = me@localhost.com

111

Windows users need to change the first two settings. The first setting is where you put the name of your outgoing server, as follows:

SMTP = mail.ispname.com

The second setting is the return address that is sent with all your e-mail. Change the setting to the e-mail address you want to use for your return address, as follows:

sendmail_from = Janet@Valade.com

112

Sending e-mail messages

PHP provides a function called mail that sends e-mail from your script. The format is as follows:

mail(address,subject,message,headers);

113

address: The e-mail address that receives the message

subject: A string that goes on the subject line of the e-mail message

message: The content that goes in the e-mail message

headers: A string that sets values for e-mail headers

114

$to = “janet@valade.com”;$subj = “Test”;$mess = “This is a test of the mail

function”;$headers =

bcc:techsupport@mycompany.com$mailsend = mail($to,$subj,$mess,

$headers);

115

$to variable

You can send the message to more than one person by using the following statement:$to=“janet@valade.com,me@mycom

pany.com”;

116

$headers

Headers are optional. Only the first three parameters are required.

The $mailsend variable contains TRUE or FALSE. However, TRUE is no guarantee that the mail will get to where it’s going. It just means that it started out okay.

117

Generating Personalized PDF

Documents The PDF functions in PHP can create PDF files

using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.

Be easy to designWork on many operating systemsBe difficult to fraudulently duplicate or

modify

118

Why use PDF with PHP?

Invoices for e-commerce sitesReport generation Anything that requires precise

control over printable output

119

pdf_new();

First:create a blank pdf file <anyname>.pdf

To do this set a object, say $pdf, to handle pdf manipulations.

$pdf = pdf_new();

To open the file, code we use the

pdf_open_file function. pdf_open_file($pdf, "C:\abc.pdf");

120

This should create a blank new pdf file size 0kb

The new file has no properties, We will need to use the pdf_set_info

function for this.

pdf_set_info($pdf, "Author", “prabhat");pdf_set_info($pdf, "Title", "Creating a pdf");pdf_set_info($pdf, "Creator", “prabhat");

121

pdf_begin_page

PDF_begin_page ($pdfdoc , $width , $height )

pdf_begin_page($pdf, 595, 842);

122

123

pdf_findfont and pdf_setfont

Now it is time to assign a text font for the information to be displayed.

Arial font type with size of 14. $arial = pdf_findfont($pdf, "Arial", "host",

1);

pdf_setfont($pdf, $arial, 14);

124

pdf_show_xy

The x-values start from the left hand side of the page and move to the right.

The y-values start from the bottom of the page and work towards the top.

125

So if we wish to type some text 50 units from the left of the page and 400 units from the bottom of the page you would type the following.

pdf_show_xy($pdf, "<Type your info here>",50, 400);

126

pdf_end_page

pdf_end_page($pdf);pdf_close($pdf);

127

Working with XML

128

Creating an XML Document

129

Working with Elements

Accessing a particular element now becomes as simple as using parent->child notation to traverse the object tree until that element is reached.

130

<?php// load XML file$xml = simplexml_load_file(‘books.xml')

or die ("Unable to load XML!");echo “title: " . $xml->book->title . "\n";echo "author: " . $xml->book->author. "\

n";?>

top related