Professional Documents
Culture Documents
Web sites are generally more compelling and useful when content is dynamically controlled.
Dynamic information theory:
dynamic means "marked by usually continuous and productive activity or change." So when we talk
about dynamic data, we mean that the information to be sent to the client as a Web page is a variable
compilation of source data. This contrasts with static Web pages, which are made up of content that is not
dependent on variable input and that are generally parsed directly to the user.
Dynamic content is a happy medium between the two and gives us an opportunity to look at two very
useful PHP functions, include() and require().
All dynamic content has one thing in common: It comes from a data source outside the originating
page.
User $HTTP_POST_VARS These functions handle data that is entered directly by the
$HTTP_GET_VARS user via a Web form.
Database <dbtype>_connect() These are just a few of PHP's many database functions,
(local or <dbtype>_pconnect() which are written specifically for each database. You can
remote) <dbtype>_close() find a complete list of these in the PHP Manual Function
<dbtype>_<function>() Reference.
example:
mysql_fetch_array()
Local file include(),require(),fopen(), These functions handle data in a file on the same server,
fclose() such as a configuration file.
For example:
Listing A shows our main script, and the page you would call in your browser, Display.php. (PHP
code appears in bold.)
Listing A
<!-- display.php
This is a Web page whose style is determined by a configuration file. -->
<html>
<head>
<title>Mood Page</title>
</head>
<?php
include("displayconf.php");
$required_file = $display.".php";
require $required_file;
?>
<br>
<br>
<center>This is the best "mood page" ever!</center>
</font>
</body>
</html>
Use the PHP include() function to include and evaluate variables in the file Displayconf.php.
Create a variable representing the name of the file to be required. In our case, the variable $display,
which is defined in the Displayconf.php file, is evaluated and then appended with .php. (This is our
logic step.)
Use the PHP require() function to display the content from the appropriate included file.
Listing B
<?php
# displayconf.php
# Configuration file for display.php
# -------------------------------------------------
# Set the variable $display to one of the following:
# happy, sad, or generic
$display = "happy";
?>
Example:
<?php
// the message
$msg = "First line of text\nSecond line of text";
// send email
mail("someone@example.com","My subject",$msg);
?>
More Examples:
Send an email with extra headers:
<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n".
Example:
<?php
//readfile intostring
$str= file_get_contents('example.txt') ordie('ERROR:Cannotfind
file');
echo$str;
?>
An alternative method of reading data from a file is PHP’s file()function, which accepts the
name and path to a file and reads the entire file into an array, with each element of the array
representing one line of the file.
To process the file, all you need do is iterate over the array using a foreachloop.
Example:
<?php
//readfile intoarray
$arr= file('example.txt') ordie('ERROR:Cannotfind
file');
foreach($arras$line) {
echo$line;
}
?>
Example:
<?php
//readfile intoarray
$arr= file('http://www.google.com')ordie('ERROR:Cannotfindfile');
foreach($arras$line) {
echo$line;
}
?>
In case of slow network links, it’s sometimes more efficient to read a remote file in “chunks,” to
maximize the efficiency of available network bandwidth.
To do this, use the fgets()function to read a specific number of bytes from a file, as in the next
example:
<?php
//readfile intoarray(chunks)
$str= '';$fp= fopen('http://www.google.com','r')or
die('ERROR: Cannot openfile');
while(!feof($fp)) {
$str.=fgets($fp,512);
} fclose($fp);
echo$str;
?>
First, the fopen()function: it accepts the name of the source file and an argument indicating
whether the file is to be opened in read ('r'), write ('w'), or append ('a') mode,and then creates
a pointer to the file.
Next, a while loop calls the fgets()function continuously in a loop to read a specific number of
bytes from the file and append these bytes to a string variable; this loop continues until the
feof()function returns true, indicating that the end of the file has been reached.
Once the loop has completed, the fclose()function destroys the file pointer.
WRITING FILES
The flip side of reading data from files is writing data to them. And PHP comes with a couple of
different ways to do this as well.
Example:
<?php
//writestringtofile
$data= "A fish \noutof\n water\n";
file_put_contents('output.txt', $data)or die('ERROR:Cannotwritefile');
echo'Datawritten tofile';
?>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite() function.
This function requires two arguments specifying a file pointer and the string of data that is to be
written. Optionally a third integer argument can be included to specify the length of the data to write.
If the third argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading in site it. After
closingthisfileitsexistenceisconfirmedusingfile_exist()functionwhichtakesfilenameas an argument
Example:
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This isa simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
EXAMPLE
Example:
<?php
//checkfile
if(file_exists('somefile.txt')){
$str= file_get_contents('somefile.txt');
} else{
echo 'Namedfiledoesnotexist. ';
}
You can also use the pathinfo()function, which returns an array containing the file’s path,
name, and extension. Here’s an example:
<?php
//getfile pathinfoasarray
if(file_exists('example.txt'))
{
print_r(pathinfo('example.txt'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>
Retrieving File Attributes
You can obtain detailed information on a particular file, including its ownership, permissions,
and modification and access times, with PHP’s stat()function, which returns this
information as an associative array. Here’s an example:
<?php
//getfile information
if(file_exists('example.txt'))
{
print_r(stat('example.txt'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>
You can check if a file is readable, writable or executable with the is readable (), is
writable (), and is executable () functions. The following example illustrates their
usage:
The is_dir()function returns true if the argument passed to it is a directory, while the
is_file()function returns true if the argument passed to it is a file. Here’s an example:
<?php
//testiffileordirectory
if(file_exists('example.txt'))
{
if(is_file('example.txt'))
Creating Directories
To create a new, empty directory, call the mkdir()function with the path and name of the directory
to be created:
Example:
<?php
if(!file_exists('mydir'))
{
if(mkdir('mydir'))
{
echo'Directory successfully created.';
} else
{
echo 'ERROR: Directory couldnotbecreated.';
}
} else
{
echo 'ERROR: Directoryalreadyexists.';
}
?>
Copying Files
You can copy a file from one location to another by calling PHP’s copy()function with the file’s
source and destination paths as arguments. Here’s an example:
<?php
Department of Computer Science Page 14
//copyfile
if(file_exists('example.txt')){
if(copy('example.txt', 'example.new.txt')){
echo'File successfullycopied.';
} else
{
echo 'ERROR: File couldnotbecopied.';
}
} else{
echo 'ERROR: File doesnotexist.';
}
?>
It’s important to note that if the destination file already exists, the copy()function will overwrite it.