Вы находитесь на странице: 1из 3

Chapter 6: Files and Directories

6.1
Opening files, Writing to a file
<?php
$file = fopen("test.txt","w");
fwrite($file,"This data will be written to test.txt");
echo "Open and see test.txt";
fclose($file);
?>

[ After running this program, test.txt file will be


created and data will be written onto it.]

6.2
Locking a file, Reading a file content
The flock() function locks or releases a file.
This function returns TRUE on success or FALSE on failure.
Syntax: flock(file,lock,block)
Parameter

Description

file

Required. Specifies an open file to lock or release

lock

Required. Specifies what kind of lock to use.


Possible values:
LOCK_SH - Shared lock (reader). Allow other processes to access
the file
LOCK_EX - Exclusive lock (writer). Prevent other processes from
accessing the file
LOCK_UN - Release a shared or exclusive lock
LOCK_NB - Avoids blocking other processes while locking

block

Optional. Set to 1 to block other processes while locking

Note: These locks only apply to the current PHP process. Other processes can modify or delete a PHPlocked file if permissions allow.
Note: flock() is mandatory under Windows.
Tip: The lock is released also by fclose(), which is called automatically when script is finished.
<?php
successfully written to test.txt
$file = fopen("test.txt","w");
Not able to read
if (flock($file,LOCK_EX))// exclusive lock
Write something
{
fwrite($file,"Write something");
[When a file is exclusively locked, other
echo "successfully written to test.txt<br />";
processes cannot read or write that file
$filer = fopen("test.txt","r");
until it is unlocked.]
if($s=fread($filer,filesize("test.txt"))) echo $s;
else echo "Not able to read<br />";
flock($file,LOCK_UN); //release lock
if($s=fread($filer,filesize("test.txt"))) echo $s;
else echo "Not able to read<br />";
}
else
{
echo "Error locking file!-unable to write to test.txt";
}
fclose($filer);
fclose($file);
?>

6.3

Handling file upload

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are
uploaded into a temporary directory and then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads
as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated
as upload_max_filesize. These parameters are set into PHP configuration file php.ini.
An uploaded file could be a text file or image file or any document.
Creating an upload form:
The following HTM code below creates an uploader form. This form is having method attribute set
to post and enctype attribute is set to multipart/form-data
Creating an upload script:
There is one global PHP variable called $_FILES. This variable is an associate double dimension array
and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute
in uploading form was file, then PHP would create following five variables:
$_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web server.
$_FILES['file']['name'] - the actual name of the uploaded file.
$_FILES['file']['size'] - the size in bytes of the uploaded file.
$_FILES['file']['type'] - the MIME type of the uploaded file.
$_FILES['file']['error'] - the error code associated with this file upload.
Uploadform.htm
<form method="post" action="upload.php" enctype="multipart/form-data">
Photo: <input type="file" name="file" id="file" /><br>
<input type="submit" name="submit" value="Submit" />
<form>
Upload.php
<?php
if ($_FILES["file"]["error"] > 0 )
echo "Error: " . $_FILES["file"]["error"] . "<br />";
else
move_uploaded_file($_FILES["file"]["tmp_name"] ,"upload/" . $_FILES["file"]["name"] ) ;
?>
Note: Create a folder by name upload in www folder and then run uploadform.htm from local host.
Then, what ever file you upload (size must be less than 2mb-see php.ini file MAX_UPLOAD_SIZE is
2mb only) that will be uploaded to upload folder that you created .
6.4
Working with directories
Creating Directories in PHP
A new directory can be created in PHP using the mkdir() function.
<?php
$result = mkdir ("F:\wamp\www\IP 06\ddd");
echo "Directory ddd created";
?>
Deleting a Directory
Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the
directory to be deleted. The deletion will only be successful if the directory is empty. If the directory
contains files or other sub-directories the deletion cannot be performed until those files and subdirectories are also deleted.
2

<?php
rmdir("ddd");
echo "Directory ddd is deleted";
?>
Finding and Changing the Current Working Directory
It is unlikely that a web application will be able to perform all of its file related tasks in a single directory.
For this reason, it is vital to be able to both find out the current working directory, and change to another
directory from within a PHP script.
The current working directory can be identified using the getCwd() function:
The current working directory can be changed using the chdir() function. chdir() takes as the only
argument the path of the new directory:
<?php
$current_dir = getCwd();
echo "Current directory is $current_dir <br>";
chdir ("./tmp");
$current_dir = getCwd();
echo "Current directory is now $current_dir <br>";
?>
Listing Files in a Directory
The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The
first argument is the path the directory to be scanned. The second optional argument specifies how the
directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically. If the
argument is omitted or set to 0 the list is sorted alphabetically:
<?php
$current_dir = getCwd();
echo "Current directory is now $current_dir<br>";
echo "The files in this directory are:<br>";
$a = scandir(".",1);
//print_r($a);
foreach($a as $v)
echo "$v <br>";
?>

***
3

Вам также может понравиться