Docsity

PHP class notes-unit 4, Lecture notes of Programming Languages

Toggle sidebar
bg1
Contents
File Handling..................................................................................................................................................... 3
Opening files..................................................................................................................................................... 3
feof () & fgets()..................................................................................................................................................... 4
Closing a file..................................................................................................................................................... 4
Reading from a file character by character.............................................................................................................. 4
Reading a whole file at once.................................................................................................................................... 5
Reading a File into an Array..................................................................................................................................... 5
Checking if the files exist......................................................................................................................................... 6
Ge�ng file Size..................................................................................................................................................... 6
Reading Binary Files.................................................................................................................................................7
Parsing files..................................................................................................................................................... 7
Parsing ini files..................................................................................................................................................... 8
Ge�ng file info..................................................................................................................................................... 8
Stats ():..................................................................................................................................................... 8
Se�ng the file pointer loca�on............................................................................................................................... 9
Copying Files..................................................................................................................................................... 9
Deleļæ½ng Files..................................................................................................................................................... 10
Working with Databases............................................................................................................................................ 10
Php with Databases............................................................................................................................................... 10
MySQL..................................................................................................................................................... 10
Accessing Database through PHP.......................................................................................................................... 12
Steps to Connect to database............................................................................................................................ 12
Updaļæ½ng Databases........................................................................................................................................... 14
Insert into Database...........................................................................................................................................15
Deleļæ½ng Records................................................................................................................................................ 15
Creaļæ½ng New Table............................................................................................................................................15
Creaļæ½ng new Database...................................................................................................................................... 16
Sorļæ½ng the Database......................................................................................................................................... 16
Session, Cookies & FTP.............................................................................................................................................. 17
Cookie..................................................................................................................................................... 17
Reading a Cookie............................................................................................................................................... 18
Seļæ½ng Expiraļæ½on Time...................................................................................................................................... 18
Deleļæ½ng a Cookie...............................................................................................................................................18
FTP..................................................................................................................................................... 18
Connecļæ½ng to a FTP server.................................................................................................................................... 19
To get a directory lisļæ½ng.........................................................................................................................................19
Downloading files with FTP....................................................................................................................................19
Uploading Files with FTP........................................................................................................................................20
Page 1 | UNIT 4
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
Discount

On special offer

Partial preview of the text

Download PHP class notes-unit 4 and more Lecture notes Programming Languages in PDF only on Docsity!

Contents

  • File Handling.....................................................................................................................................................
    • Opening files.....................................................................................................................................................
    • feof () & fgets().....................................................................................................................................................
    • Closing a file.....................................................................................................................................................
    • Reading from a file character by character..............................................................................................................
    • Reading a whole file at once....................................................................................................................................
    • Reading a File into an Array.....................................................................................................................................
    • Checking if the files exist.........................................................................................................................................
    • Geļæ½ng file Size.....................................................................................................................................................
    • Reading Binary Files.................................................................................................................................................
    • Parsing files.....................................................................................................................................................
    • Parsing ini files.....................................................................................................................................................
    • Geļæ½ng file info.....................................................................................................................................................
      • Stats ():.....................................................................................................................................................
    • Seļæ½ng the file pointer locaļæ½on...............................................................................................................................
    • Copying Files.....................................................................................................................................................
    • Deleļæ½ng Files.....................................................................................................................................................
  • Working with Databases............................................................................................................................................
    • Php with Databases...............................................................................................................................................
    • MySQL.....................................................................................................................................................
    • Accessing Database through PHP..........................................................................................................................
      • Steps to Connect to database............................................................................................................................
      • Updaļæ½ng Databases...........................................................................................................................................
      • Insert into Database...........................................................................................................................................
      • Deleļæ½ng Records................................................................................................................................................
      • Creaļæ½ng New Table............................................................................................................................................
      • Creaļæ½ng new Database......................................................................................................................................
      • Sorļæ½ng the Database.........................................................................................................................................
  • Session, Cookies & FTP..............................................................................................................................................
    • Cookie.....................................................................................................................................................
      • Reading a Cookie...............................................................................................................................................
      • Seļæ½ng Expiraļæ½on Time......................................................................................................................................
      • Deleļæ½ng a Cookie...............................................................................................................................................
  • FTP.....................................................................................................................................................
    • Connecļæ½ng to a FTP server....................................................................................................................................
    • To get a directory lisļæ½ng.........................................................................................................................................
    • Downloading files with FTP....................................................................................................................................
    • Uploading Files with FTP........................................................................................................................................
    • Delete a file with FTP.............................................................................................................................................
    • Creaļæ½ng Removing Directories with FTP................................................................................................................
    • Sending E-Mail.....................................................................................................................................................
  • Sessions.....................................................................................................................................................
    • Wriļæ½ng a hit counter using Session.......................................................................................................................
    • Difference between Session & Cookie...................................................................................................................

$handle = fopen(ā€œ/home/file.txtā€ , ā€œrā€); $handle variable can be now used to work with the file.

  • To open a file for binary writing, $h = fopen(ā€œ/home/file.txtā€ , ā€wbā€);
  • Backslashes () can also be used in file path. In such case, they should be escaped by a (\) double backslash.
  • In the file location, the files in other websites can also be used, if given the complete address of the file. E.g: Program 4. <? php $h = fopen(ā€œfile.txtā€, ā€œrā€); if ($h) echo ā€œfile opened OKā€;’ ?>

ā–² In the above program,

  • the file ā€œfile.txtā€ is opened in read mode.
  • after opening file, if successful fopen will return TRUE.
  • the message is displayed if fopen is successful. E.g.: $h = fopen (http://www.php.net , ā€œrā€); This will open the URL on the internet, preparing to read from web pages.

feof () & fgets()

  • feof() function gets the file handle as argument and will return TRUE if end of file is reached.
  • Syntax: feof()
  • feof() is usually added to a conditional statement.
  • fgets() will read a string of text from the file.
  • Syntax: fgets( [,length])
  • fgets() gets the file handle as argument, with an optional argument ā€˜length’ of the string to read.
  • fgets() reads (length-1) bytes from the file.
  • The default length is 1024 bytes. E.g.: Program 4. <?php

$h = fopen("file.txt" , "r"); while (!feof($h)) { $text = fgets($h); echo $text, "
"; } ?>

  • In the above program,
    • $h is the handle for the file ā€œfile.txtā€ which is opened in read only mode.
    • The file pointer moves through the file and copies the text to $text variable till end of file is reached.
    • The data is then displayed on screen.

Closing a file

  • Every file that is opened should be closed.
  • Closing a file frees up the resources connected with the file.
  • Properly closes the file.
  • Syntax: fclose(<$file handle>);
  • This function returns true if the file is successfully closed.
  • E.g.: Program 4. <?php $h = fopen("file.txt" , "r"); while (!feof($h)) { $t = fgets($h); echo $t; } fclose ($h); ?> The above program,
  • Fopen a file using fopen() function.
  • Reads string using fgets()
  • Finally closes the file handle using fclose().

offset - offset into the file at which to start reading. maxlen - maximum length of the data to read.

  • Except the filename option, the remaining arguments are optional.
  • In the file name argument, either the name of the file with its path or the address of a website is include.
  • E.g.: Program 4. <?php $te = file_get_contents("file.txt"); $f_t = str_replace("\n", "
    " , $te); echo $f_t; ?>
  • In the above program.
    • $te variable holds the entire contents of the file ā€œfile.txtā€.
    • In the next line, the \n character in the file is replaced with
      tag.
    • The file content is then displayed.
  • To move a whole website, the address of the page is passed as parameter.

Reading a File into an Array

  • Storing the entire file into an array is achieved using the function file( ).
  • Syntax: file(filename [, use_include_path [, context]])
  • filename – name of the file to open.
  • The function returns an array or FALSE if failed.
  • Each line of the document becomes an element of the array.
  • This is useful to fetch data’s in a binary database.
  • E.g.: File.txt:

Aa bb cc dd

Php program: Program 4.

$ln) echo "Line $no: $ln
"; ?>
  • In the above program,
  • The text in ā€œfile.txtā€ is stored in array $dt.
  • The stored array is then displayed one by one.
  • The file has 3 lines therefore the array will have 3 elements.
  • Each array element will have a \n character in the end.
  • To get rid of the new line, rtrim () function is used.

Checking if the files exist

  • To check if the file already exist in the computer, file_exist ( ) function is used.
  • The file to be searched is passed as argument.
  • The function will return TRUE if the file exists and a FALSE otherwise.
  • Syntax: file_exists (filename)
  • The file name is passed as argument and the function will return TRUE if the file exist, otherwise FALSE is returned.
  • E.g.: Program 4. <?php $fnm = "temp.txt"; if (file_exists($fnm)) { $data = file($fnm); foreach ($dt as $no => $line) { echo "Line $no:", $line, "
    "; } }
  • In the above program,
    • The file ā€œfile.txtā€ is opened in ā€œrbā€ mode.
    • To the fread function, the handle and the size of the file is passed.
    • fread function returns the whole content of the file into the variable $text.
    • The ā€œ\nā€ is then replaced with
      tag.
    • The same text is then displayed on screen.
    • Finally the handle is closed.
    • The output will be the contents of the file ā€œfile.txtā€.

Parsing files

  • The binary files can be parsed using function fscanf ().
  • Syntax: fscanf ($handle, format)
  • The function takes a file handle and format as arguments
  • Format string is same as is used for other printf function.
  • E.g.: Program 4. <?php $h = fopen("actors.txt" , "r"); while ($n = fscanf($h, "%s\t %s\n")) { list ($f_name, $l_name) = $n; echo $f_name, " ", $l_name, "
    "; } fclose($h); ?> - In the above program,
    • actors.txt is a formatted file which is already available.
    • The data’s in actors.txt is in a format (String, tab space, String, new line).
    • A similar format is given to the format of fscanf function
    • The fetched data is splitted, into 2 variables and displayed separately.
    • The contents of ā€œActors.txtā€ is

Jim Carry Bob Miller Bryan Grant.

  • The records are arranged in a predefined format, such a file is termed as Binary File.
  • fread() function will return the entire data’s as one string.
  • Whereas scanf() function will expect the data’s in the prescribed format and the return value is stored in a single variable.

Parsing ini files

  • Parse_ini_files() is a function that is used to read ini files.
  • Syntax: Parse_ini_file(filename [, process section])
  • This function loads in the ini file and returns the setting in an associative array.
  • A TRUE in process section argument will allow multidimensional array with the sections & settings; default value is FALSE.
  • E.g.: Program 4. Sample.ini ; This is a sample ini file

[First section] first_color = red second_color = while third_color = blue

[Second section] File= ā€œ/usr/local/code.dataā€ URL = http://www.php.net

  • Program to read and parse this ini file is: <?php $arr = parse_ini_file("sample.ini"); foreach ($arr as $key => $val) { echo "$key ----------- $val
    ";
  • The elements of the array can be accessed using the numeric index or the string index.
  • For numeric index the size of the file will be in $arr [7].

Setting the file pointer location

  • The file pointer points to the current location in the file.
  • When a file is opened, the pointer is set to the first location.
  • fseek() function is used to a move the file pointer location to desired location.
  • Syntax: fseek (handle, offset, [start_point]);

handle - handle of thee referenced file. offset - no. of bytes to set the pointer to. start point - starting point for the pointer.

  • Starting point is optional. It can be any one of the following constants.
    • SEEK_SET : Beginning of file.
    • SEEK_CUR : Current pointer location.
    • SEEK_END : End of the file
  • Offset can be a +ve or –ve number.

Copying Files

  • To copy the content of one file to another file, copy( ) function is used.
  • Syntax: copy(source, destination);
  • This function returns TRUE if the copy was successful.
  • E.g.: Program 4. <?php $s = 'file.txt'; $d = 'copy.txt'; if (!file_exists($d)) { if (copy($s, $d)) echo "Copy Successful"; } else

echo "could not copy $s
File already exists"; ?>

Deleting Files

  • To delete a file entirely, unlink( ) function is used.
  • Syntax:

unlink(filename [,context]) filename – filename to be deleted.

  • This function returns TRUE if the delete was successful.
  • E.g.: Program 4. <?php if (unlink("copy.txt")) echo "Deleted the file"; else echo "could not delete file"; ?> - In the above program,
    • The file ā€œcopy.txtā€ is deleted from disk using unlink( ) function.
    • The deleted operation is included in a condition.
    • Depending on the condition is TRUE a message is displayed correspondingly.

Working with Databases

  • A Database is a collection of one or more tables.
  • Databases organize data for easy access and use by programs.
  • A common database construct is a table.
  • A table is a collection of data in rows and columns.
  • Each row in a table is called a record.
  • Each column in a record is called a field.

Php with Databases

  • Php handles databases on the server.
  • Php supports various kinds of database servers.

CREATE DATABASE ; This command will create an empty database. E.g.: CREATE DATABASE produce;

4. To view the list of available databases:

SHOW DATABASES;

5. To set a database as default database:

USE ; This will set the database mentioned as default databases. E.g.: USE produce;

6. Create new table:

CREATE TABLE

(field nm data type…); The above command will create a table table name with the fields added to it. E.g.: CREATE TABLE fruit (name VARCHAR (20), number VARCHAR (20));

  • The various data types used frequently are:

1. VARCHAR (length) - creates a variable length string.

2. INT - creates an integer.

3. DECIMAL (total digits, total places) - creates a decimal value.

4. DATETIME - creates a data and time object like 2008 – 11 – 15 20:00:00.

7. To show the list of tables in the current database:

SHOW TABLES;

This will display all the table names in the current databases.

8. To display the structure of a table,

DESCRIBE

; E.g.: DESCRIBE fruit; The above E.g. will display the structure of the table fruit.

9. To add DATA INTO DATABASES:

INSERT INTO

VALUES (value(s)); E.g.: INSERT INTO fruit VALUES (ā€˜apple’, ā€˜1020’);

  • The above e.g. will add a record to the table.
  • Similarly any number of records can be added to a table.

10. To display the contents of a table:

SELECT * FROM

; E.g.: SELECT * FROM fruits: This above E.g. will display the entire contents of the table fruits.

11. To exit mysql monitor:

QUIT

Accessing Database through PHP

  • Php has many inbuilt function to interact with MySQL.
  • The function are:

mysql_affected_rows Get the number of rows affected by the previous

MySQL operaļæ½on.

mysql_change_user Change the logged-in user.

mysql_data_seek Sek data in the database

mysql_drop_db Drop a MySQL database

mysql_fetch_array Fetch a result row as an associaļæ½ve array, a numeric

array or both.

mysql_fetch_assoc Fetch a result row as an associaļæ½ve array

mysql_field_len Return the length of a given field.

mysql_get_server_info Get MySQL server info.

mysql_info Get informaļæ½on about the most recent query.

mysql_list_tables Lists the tables in a MySQL database.

mysql_list_fields Lists MySQL table fields.

mysql_result Get result data.

Steps to Connect to database

The examples in this book will work with PHP4 & 5.(Note: These are from the syllabus ) Whereas if you have installed PHP 7, which is the current version, the alternate commands are in the blog page, hļæ½p:// viid.me/qr731T which is part of hļæ½p://krishnas-php-tutorial.blogspot.in/

1. Connecting to database Server:

  • Php connects to databases using connection object.
  • To create connection object,
  • E.g.: $q = ā€œselect * from fruitsā€; $res = mysql_query ($q) or die (ā€œquery failed:ā€. mysql_error( ));
  • The sql query is stored in a variable separately for simplicity.
  • The variable is passed to mysql_query() function as parameter and the result is stored in variable $res.
  • At the end the variable will have data if query was successful or message with error string if failed.
  • The returned data has to be displayed with additional functions.

4. Displaying Table Data:

  • To extract individual rows from the return data, mysql_fetch_array( ) function is used.
  • This function returns an array corresponding to the current record in the data table.
  • Syntax: mysql_fetch_array (return [, result_type]) - result - resource returned by mysql_query function. - result_type - type of preferred array.
  • It can be either one of these: MYSQL_ASSOC, MYSQL_NUM MYSQL_BOTH is the default value. E.g.: while ($row = mysql_fetch_array($result)) { echo ā€œ
ā€; echo ā€œā€; echo ā€œā€; } The first statement assigns the current row from fruit table to $row.

Name field can be accessed like this: $row [ā€˜name’] or $row [ā€˜number’]

5. Closing connection object:

  • The connection to the database is closed using function mysql_close( ).
    • Syntax: mysql_close([link identifier]) where - link_idenifier: the connection object.
    • (^) E.g.: mysql_close($conn);

Example program to fetch data from database and display it. Program 4-

ā€œ, $row[ā€˜name’], ā€œ ā€œ, $row[ā€˜number’], ā€
ā€; echo ā€œā€; echo ā€œā€; echo ā€œā€; while ($r = mysql_fetch_array($res)) { echo ā€œā€; echo ā€œā€; echo ā€œā€; } echo ā€œ
Name Number
ā€œ, $row[ā€˜name’], ā€œ ā€ $row[ā€˜number’], ā€
ā€; mysql_close($conn);