0% found this document useful (0 votes)
10 views11 pages

PHP File and Database Management Guide

Chapter 4 covers file and database handling in PHP, detailing how to work with files including opening, closing, reading, writing, and manipulating directories. It also introduces database interactions with PostgreSQL, explaining SQL commands for data manipulation and structure definition, as well as using the PEAR DB library for database abstraction. Key functions and their syntax for file operations and database connections are provided throughout the chapter.

Uploaded by

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

PHP File and Database Management Guide

Chapter 4 covers file and database handling in PHP, detailing how to work with files including opening, closing, reading, writing, and manipulating directories. It also introduces database interactions with PostgreSQL, explaining SQL commands for data manipulation and structure definition, as well as using the PEAR DB library for database abstraction. Key functions and their syntax for file operations and database connections are provided throughout the chapter.

Uploaded by

snehajanjal54
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-4 Files and Database Handling

1. Introduction
Files are stored in folders on the hard drive and because the data is retained
even after the machine is shut down, they are termed as persistent storage
mechanism. Files can contain information about themselves, who own them
and when they are created. But, directories are special kind of files made for
storing other files.
1.1 Working with Files
PHP provides two sets of file related function, the way in which they handle
files:
i. File handle or the file pointer: It is an integer value used to identify the file
we want to work with.
[Link] way is directly using filename strings.
2. Opening and Closing Files
There are typically three steps involved in working with the files:
[Link] the file you want to work with by associating a file handle with it.
ii. Read from or write to the file by using the file handle.
iii. Close the file using the file handle.
Creating a File: fopen Function
The fopen function needs two important piece of information to operate
correctly
i. The name of the file that we want it to open.
ii. The operation we want to perform with that file (i.e., read from the file,
write information, etc
Since we want to create a file, we must supply a file name and tell PHP that we
want to write the file.
Example. <?php
$filename="[Link]";
$filehandle= fopen($filename, 'w') or die("can't open file");
fclose($filehandle);
?>
PHP will see that "[Link]" does not exist and will create it after running this
code.
1. $filename = "[Link]";
Here we create the name of our file. "[Link]" and store it into a PHP String
variable $filename.
ii. $filehandle = fopen($filename, 'w') or die("can't open file");
This bit of code actually has two parts.
a. The function fopen which takes two arguments: our file name and we inform
PHP that we want to write by passing the character "w".
b. The fopen function returns what is called a file handle, which will allow us to
manipulate the file. We save the file handle into the $filehandle variable.
iii. fclose($filehandle);
We close the file that was opened. fclose takes the file handle that is to be
closed.
Different Ways to Open File/Modes of File
Below the three basic ways to open a file and the corresponding character that
PHP uses.
 Read Mode (r):
Opens a file for reading. The file must exist, and attempts to write to it will result in
an error.
 Write Mode (w):
Opens a file for writing. If the file exists, its contents are truncated (deleted). If the
file does not exist, a new one is created.
 Append Mode (a):
Opens a file for writing, appending new data to the end of the existing content. If
the file does not exist, a new one is created.
A file pointer is PHP's way of remembering its location in a file. When we open
a file for reading, the file pointer begins at the start of the file.
When we open a file for appending, the file pointer is at the end of the file, as
most likely we will be appending data at the end of the file.
File Open: Advanced
There are additional ways to open a file. Above we stated the standard ways to
open a file. However, we can open a file in such a way that reading and writing
is allowable! This combination is done by placing a plus sign "+" after the file
mode character.
Read/Write: 'r+':
Opens a file so that it can be read from and written to. The file pointer is at the
beginning of the file.
Write/Read: 'w+':
This is exactly the same as r+, except that it deletes all information in the file
when the file is opened.
Append: 'a+':
This is exactly the same as r+, except that the file pointer is at the end of the
file.
Consider the following example replace the (X) with one of the options above
(i.e., r, w, a, etc).
Example <?php
$filename "[Link]";
$fh fopen($SourFileName, 'X') or die("Can't open file");
fclose($fh);
?>
Closing a File: fclose Function
Syntax
fclose(filehandle);
The function fclose requires the file handle that we want to close down. In our
example we set our variable "Sfilehandle" equal to the file handle returned by
the fopen function.
After a file has been closed down with fclose it is impossible to read, write or
append to that file unless it is once more opened up with the fopen function.
Getting Status of File
The stat() function gives information about a file, i.e., about their size, when it
was modified, who owns it...etc.
Syntax
array stat (string filename)
In case of error, stat() function returns FALSE. It will also throw a warning.
Reading/Writing onto the File: fread/fwrite Function

fread(): The fread function is the staple for getting data out of a file.
Before we can read information from a file we have to use the function fopen
to open the file for reading. Here's the code to read-open the file we have
created above.
Example,
SmyFile = "[Link]";
$fh= fopen($myFile, 'r');
[Link] Contents
Olddata is lost
Contents Overwritten

The fread() requires a file handle, which we have, and an integer to tell the
function how much data, in bytes, it is supposed to read.
One character is equal to one byte.
If we want to read the first five characters then we would use five as the
integer.
Fwrite():The fwrite() function function allows data to be written to any type of
[Link] takes two parameters
[Link] the file handle.
[Link] string of data that is to be written.
Splitting the Name and Path From a File
basename(): This function takes the complete file path and returns just the
filename, base name is a means of getting the last whole string after the
rightmost slash.
Renaming and Deleting Files
i. Copy(): Makes a copy of the file source to dest. Returns TRUE on
success or FALSE on failure.
Syntax: bool copy (string source, string dest)

ii. rename(): Renames a file or directory.


Syntax: bool rename (string oldname, string newname[, resource
context))
iii. unlink(): Deletes filename.
Unlink(): If we unlink a file, we are effectively causing the system to forget
about it or delete it.
Before we can delete (unlink) a file, we must first be sure that it is not open
in our program. Use the fclose function to close down an open file.
[Link]():The flock() function locks and release a file.
Syntax: flock(file,lock,block);
Reading and Writing Characters in File:
PHP provides a set of functions that makes reading the entire contents of a file
or perhaps analyzing it one character at a time.
[Link]():Gets character from file pointer.
Syntax: string fgetc(resource handle)
Returns a string contacting a single character read from the file pointed to by
handle. Returns FALSE on EOF.
[Link]():Tests for end-of-file on a file pointer.
Syntax: bool feof(resource handle);
[Link]():It gets line from file pointer.
[Link]():Gets line from file pointer and parse for Comma Separated
values(CSV)fields.
[Link]():This function is an alias for fwrite().
The function will stop at the end of the file or when it reaches the specified
length,whichever comes first.
Reading Entire File
There are certain functions which gives access to the complete contents of the
file.
[Link](): Reads entire file into an arrayу:
The file() returns the file in an array. Each element of the array corresponds to
a line in the file, with the newline still attached.
Syntax: array file(string filenamel, int use_include_pathi, resource context]])
[Link](): This function reads all data from the current position in an open
file, unti EOF and writes the result to the output buffer.
Syntax: int fpassthru (resource handle)
Consider the following example.
<?php
Sfile fopen("[Link]", "r");
//Read first line
fgets($file);
// Send read of the file to the output buffer
echo fpassthru($file);
fclose($file):
?>
iii. readfile(): Read a file and write it to the output buffer. Returns the number
of bytes read from the file.
Syntax: readfile (filename, include_path, context)
Where filename: Specifies the file to read.
include_path: Set this parameter to 'l' if we want to search for the file in the
include_path (in [Link]) as well.
context: Specifies the context of the file handle. Context is a set of options that
can modify the behavior of a stream.
Example
<?php
echo readfile("[Link]");
?>
Random Access to File Data
[Link]():seeks on a file pointer.
[Link]():Returns the position of the file pointer referenced by [Link]:int
ftell(resource handle)
[Link]():Sets the file position indicator for handle to the beginning of the
file stream.
Syntax:bool rewind (resource handle)
Getting Information on File
i.file_exists():returns true if the file or directory specified by filename
exists;false otherwise.
Syntax: bool file_exists(string filename)
[Link](): Reurns the size of the file in bytes,or false in case of an error.
[Link]():Returns the time the file was last changed,or false in case of
[Link] time is returned as a UNIX timestamp.
[Link]():Gets file modification time. Returns the time the file was last
modified,or false in case of an error.
[Link]():The pathinfo() function returns an array that contains information
about a file path.
Ownership and Permissions
i.posix_getpwuid(): Return info about a user by user id. The array elements
returned are:
Syntax: array posix_getpwuid(int uid)
ii.posix_getgrgid(): Returns an associative array identified by a group id.
iii. fileowner(): Returns the user ID of the owner of the specified file.
iv. filegroup(): Returns the group ID of the owner of the specified file.
V. filetype: Returns the type (fifo, char, dir, block, link, file, or unknown) of the
specified file.
vi. is_dir(): It returns true if the given filename is a directory.
vii. is_file(): It returns true if the given filename is a regular file.
Working with Directories
PHP enables us to manipulate directories in much the same way as files,
providing a number of equivalent functions. Some directory functions use a
directory handle, whereas others use a string containing the name of the
directory we want to work with.
i. opendir(): Opens up a directory handle to be used.
Example. $dh opendir("directoryname");
[Link](): Closes the directory stream indicated by dir handle. The
dir_handle is the handle with which the directory was opened.
Example. closedir($dh);
[Link](): Read entry from directory handle
$d-readdir($dh);
iv. rewinddir(): Rewind directory handle It resets the directory stream
indicated by dir_handle to the beginning of the directory. The directory handle
sent as a parameter to the rewinddir() function and it returns Null on success
or False on failure.
Syntax
void rewinddir(resource $dir_handle);
The directory handle resource previously opened with opendir(). If the
directory handle is not specified, the last link opened by opendir() is assumed.
v. chdir(): Changes PHP's current directory to directory specified.
vi. rmdir(): The rmdir() function removes an empty directory.
It is mandatory for the directory to be empty, and it must have the relevant
permission which are required to delete the directory.
The directory to be deleted is sent as a parameter to the rmdir() function and it
returns True on success or False on failure.
Syntax
rmdir(dirname, context)
The rmdir() function in PHP accepts two parameters.
a. dirname: It is a mandatory parameter which specifies the directory to be
deleted.
b. context: It is an optional parameter which specifies the behavior of the
stream
vii. mkdir(): Creates directory specified by the pathname.
Consider the following example, it first checks whether the path name exists, if
yes soit removed and created again with all the permissions granted to all
users.
viii. dirname(): Returns the directory part of a given filename.
ix. dir(): An object oriented mechanism for working with directories. We need
to instantiate the object first by calling dir() constructor with the name of the
directory we want to work.
Compare between include() and require()
The require() and include() constructs
PHP provides two constructs to load code and HTML from another module:
require and include.
They both load a file as the PHP script runs, work in conditionals and loops, and
complain if the file being loaded can't be found.
The include and require statements are identical, except upon failure:
1. require will produce a fatal error (E_COMPILE_ERROR) and stop the script.
2. include will only produce a warning (E_WARNING) and the script will
continue.
Syntax
include ('filename');
or
require ('filename');
Database (PHP-PostgreSQL)
PHP provides robust support for interacting with PostgreSQL databases,
allowing developers to build dynamic web applications that leverage
PostgreSQL's features.
The syntax for SQL is divided into two parts.
Data Manipulation Language, or DML: It is used to retrieve and modify data in
an existing database. DML is remarkably compact, consisting of only four
verbs.
select, insert, update, and delete.
Data Definition Language, or DDL: It is the set of SOL commands, used to
create and modify the database structures that hold the data.
Some of the Most Important SQL Commands
SELECT: extracts data from a database
UPDATE: updates data in a database
DELETE: deletes data from a database
INSERT INTO: inserts new data into a database
CREATE DATABASE: creates a new database
ALTER DATABASE: modifies a database
CREATE TABLE: creates a new table
ALTER TABLE: modifies a table
DROP TABLE: deletes a table
CREATE INDEX: creates an index (search key)
DROP INDEX: deletes an index
PEAR DB Basics
PEAR::DB is an advanced, object-oriented database library that provides full
database abstraction that is, we use the same code for all our databases. If we
want our code to be as portable as possible, PEAR:: DB provides the best mix of
speed, power, and portability
The script below demonstrates how to use the PEAR DB library (which comes
with PHP) to connect to a database, issue queries, check for errors, and
transform the results of queries into HTML.
PostgreSQL and PHP
Connecting To Database
pg_connect:The function will create a new connection for each instance of the
function.
Retrieving data with PHP in PostgreSQL
i.pg_fetch_row(): The function returns an array of string [Link] can use
array index notation to get the array fields.
ii.pg_fetch_assoc():function fetches a row as an associative [Link] keys of
the associative array are the column names.
iii.pg_fetch_object():it returns an object with properties that correspond to
the fetched row’s field names.
Closing the connection
Pg_close(): closes a PostgresSQL connection.

You might also like