You are on page 1of 19

UNIT II

DISPLAYING DYNAMIC CONTENT

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.

There are three main types of dynamic information on the Web:

 Dynamic data—Variables within a Web page are generated.

 Dynamic Web pages—An entire Web page is generated.

 Dynamic content—Portions of a Web page are generated.

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

Data sources and PHP functions:

All dynamic content has one thing in common: It comes from a data source outside the originating
page.

Data PHP functions Comments


source

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

Department of Computer Science Page 1


Remote file fopen(),fclose(),fgets(), These functions handle data in a file on a remote server,
fputs() which is accessible via FTP.

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.

Department of Computer Science Page 2


PHP manual regarding the functions require_once() and include_once() for even better control of file
handling and configuration file variable management.

Listing B shows our configuration file, Displayconf.php.

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

"Happy" file content (happy.php)


<body bgcolor=pink text=yellow>
<font size="+5">

"Sad" file content (sad.php)


<body bgcolor=blue text=white>
<font face="arial, helvetica" size="+5">

"Generic" file content (generic.php)


<body bgcolor=white text=black>
<font face="courier" size="+5">
SENDING E-MAIL
 The mail() function allows you to send emails directly from a script.
Syntax:
mail(to,subject,message,headers,parameters);
Parameter Values:
Parameter Description
To Required. Specifies the receiver / receivers of the email

Subject Required. Specifies the subject of the email. Note: This


parameter cannot contain any newline characters
Message Required. Defines the message to be sent. Each line
should be separated with a LF (\n). Lines should not
exceed 70 characters.
Windows note: If a full stop is found on the beginning
Department of Computer Science Page 3
of a line in the message, it might be removed. To solve
this problem, replace the full stop with a double dot:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>

Optional. Specifies additional headers, like From, Cc,


and Bcc. The additional headers should be separated
with a CRLF (\r\n).
Headers Note: When sending an email, it must contain a From
header. This can be set with this parameter or in the
php.ini file.

Optional. Specifies an additional parameter to the


sendmail program (the one defined in the sendmail_path
paramters configuration setting). (i.e. this can be used to set the
envelope sender address when using sendmail with the -
f sendmail option)

Example:

Send a simple email:

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters


$msg = wordwrap($msg,70);

// 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".

Department of Computer Science Page 4


"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>
Send an HTML email:
<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

Department of Computer Science Page 5


mail($to,$subject,$message,$headers);
?>
FILE SYSTEM

WORKINGWITHFILES AND DIRECTORIES


READINGFILES
PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into an arra y, from
the local file system or a remote URL, by lines, bytes, or characters.

Reading Local Files


The easiest way to read the contents of a disk file in PHPis with the file_get_ contents()function.
This function accepts the name and path to a disk file, and reads the entire file into a string variable in one
fell swoop.

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

Reading Remote Files

Department of Computer Science Page 6


Both file_get_contents()and file()also support reading data from URLs, using either the HTTP
or FTP protocol, which reads an HTML file off the Web into an array:

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.

Department of Computer Science Page 7


 The first is the file_put_contents() function, a close cousin of the
file_get_contents()function you read about in the preceding section: this function accepts a
filename and path, together with the data to be written to the file,

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>

Department of Computer Science Page 8


<?php
if(file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
PROCESSING DIRECTORIES
 PHP also allows developers to work with directories on the file system, iterating through directory
contents or moving forward and backward through directory trees.
 Iterating through a directory is a simple matter of calling PHP’s Directory Iterator object,

EXAMPLE

 Directory manipulation functions . . . as in the following listing:


<?php
//createdirectorypointer
$dp= opendir('.') ordie('ERROR:Cannot open directory');
//readdirectory contents
//print filenamesfound
while($file = readdir($dp)) {
if ($file!='.'&&$file !='..'){
echo"$file\n";
}
}
//destroydirectorypointer
closedir($dp);
?>

Department of Computer Science Page 9


 Here, the opendir()function returns a pointer to the directory named in the function call.This
pointer is then used by the readdir()function to iterate over the directory, returning a single entry each
time it is invoked.
 It’s then easy to filter out the .and ..directories, and print the names of the remaining entries. Once
done, the closedir() function closes the file pointer.
PHPFile and Director y Functions

Function What It Does


file_exists() Tests if a file or directory exists
filesize() Returns the size of a file in bytes
realpath() Returns the absolute path of a file
pathinfo() Returns an array of information about a file and its path
stat() Provides information on file attributes and permissions
is_readable() Tests if a file is readable
is_writable() Tests if a file is writable
is_executable() Tests if a file is executable
is_dir() Tests if a directory entry is a directory
is_file() Tests if a directory entry is a file
copy() Copies a file
rename() Renames a file
unlink() Deletes a file
mkdir() Creates a new directory
rmdir() Removes a directory
include()/require() Reads an external file into the current PHP script

Checking if a File or Director y Exists


 If you try reading or appending to a file that doesn’t exist, PHP will typically generate a fatal error.
 To avoid these error messages, always check that the file or directory you’re attempting to access
already exists, with PHP’s file_exists()function.

Example:

<?php
//checkfile
if(file_exists('somefile.txt')){
$str= file_get_contents('somefile.txt');
} else{
echo 'Namedfiledoesnotexist. ';
}

Department of Computer Science Page 10


//checkdirectory
if(file_exists('somedir')){
$files= scandir('somedir');
} else{
echo 'Nameddirectory doesnotexist.';
}
?>
Calculating File Size
 To calculate the size of a file in bytes, call the filesize()function with the filename as
argument:
Example:
<?php
//getfilesize
//output:'Fileis1327bytes.' if(file_exists('example.txt')){
echo'Fileis'.filesize('example.txt').'bytes.';
} else{
echo 'Namedfiledoesnotexist. ';
}
?>

Finding the Absolute File Path


 To retrieve the absolute file system path to a file, use the real path()function, as in the next
listing:
Example:
<?php
//getfile path
//output:'File path:/usr/local/apache/htdocs/
// /php-book/ch06/listings/example.txt'
if(file_exists('example.txt'))
{
echo'File path:'.realpath('example.txt');
} else
{
echo 'Namedfiledoesnotexist. ';
Department of Computer Science Page 11
}
?>

 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:

Department of Computer Science Page 12


<?php
//getfile information
//output:'File is: readablewritable'
if(file_exists('example.txt'))
{
echo'Fileis:';
//checkfor readablebit
if (is_readable('example.txt'))
{
echo'readable';
}
//checkfor writablebit
if (is_writable('example.txt'))
{
echo'writable';
}
//checkfor executablebit
if(is_executable('example.txt'))
{
echo'executable';
}
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>

 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'))

Department of Computer Science Page 13


{
echo'It\'safile.';
}
if(is_dir('example.txt')){
echo'It\'sadirectory.';
}
} else
{
echo 'ERROR: File doesnotexist.';
}
?>

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.

Renaming Files or Directories


 To rename or move a file (or directory), call PHP’s rename()function with the old and new path
names as arguments. Here’s an example that renames a file and a directory, moving the file to a
different location in the process:
Example:
<?php
//rename/movefile
if(file_exists('example.txt'))
{
if(rename('example.txt','../example.new.txt'))
{
echo'File successfullyrenamed.';
} else
{
echo 'ERROR: File couldnotberenamed.';
}
} else
{
echo 'ERROR: File doesnotexist.';
}
//renamedirectory

Department of Computer Science Page 15


if(file_exists('mydir'))
{
if(rename('mydir','myotherdir'))
{
echo'Directory successfully renamed.';
} else
{
echo 'ERROR: Directorycouldnotberenamed.';
}
} else
{
echo 'ERROR: Directory doesnotexist.';
}
?>
Reading and Evaluating External Files
 To read and evaluate external files from within your PHPscript, use PHP’s include() or
require()function.
 Avery common application of these functions is to include a standard header, footer, or copyright
notice across all the pages of aWeb site. Here’s an example:

<!DOCTYPEhtmlPUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN"


"DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en">
<head>
<title>MY WEB PAGE</title>
</head>
<body>
<?phprequire('header.php');?>
<p/>
Thisis thepagebody.
<p/>
<?phpinclude('footer.php');?>
</body>
</html>

Department of Computer Science Page 16


PHP FILE UPLOAD
 With PHP, it is easy to upload files to the server.
Configure “php.ini” file:
In your "php.ini" file, search for the file_uploads directive, and set it to on:
file_uploads = On
Create the html form:
<! DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
 <input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Create upload file php script:
"upload.php":
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
     if($check !== false) {
         echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
         echo "File is not an image.";
        $uploadOk = 0;

Department of Computer Science Page 17


    }
}
?>
 $target_dir = "uploads/" - specifies the directory where the file is going to be placed
 $target_file specifies the path of the file to be uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image
Check if already exists:
First, we will check if the file already exists in the "uploads" folder. If it does, an error message is
displayed, and $uploadOk is set to 0:
if (file_exists($target_file))
{
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
Check the Limit of file size:
Now, we want to check the size of the file. If the file is larger than 500KB, an error message
is displayed, and $uploadOk is set to 0:
if ($_FILES["fileToUpload"]["size"] > 500000)
{
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
**************************** UNIT II COMPLETED**********************************
QUESTION BANK
UNIT IV
2 MARKS
1. What is the use of the file_get_ contents()function?
2. What is the use of fopen(),fget(), fclose() functions?
3. List the php file directory functions.
4. What is the use of file_exist() function?
5. What is the use of file_size() function?
6. What is the use of realpath() function?
7. What is the use of stat() function?
8. What is the use of mkdir() function?
9. What is the use of copy() function?

Department of Computer Science Page 18


10. What is the use of remove() function?
11. What is the use of require() and include() function?

5 MARKS AND 10 MARKS

1. How will you read the files from file directory?


2. How will you write the files to file directory?
3. List php directory functions in php and explain it.

Department of Computer Science Page 19

You might also like