File Handling in PHP
File Handling in PHP
Opening a File
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to
be opened
the second parameter specifies in which mode the file should be
opened:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
Closing a File
The fclose() function is used to close an open
file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
The feof() function checks if the "end-of-file"
(EOF) has been reached.
The feof() function is useful for looping
through data of unknown length.
Note: You cannot read from files opened in w,
a, and x mode!
if (feof($file)) echo "End of file";
Writing to file
fwrite() writes to an open file.
The function will stop at the end of the file or when it reaches the
specified length, whichever comes first.
This function returns the number of bytes written, or FALSE on failure.
Syntax
fwrite(file,string,length)
Parameter
Description
file
string
length
Example
<?php
$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
?>
Fputs
The fputs() writes to an open file.
This function returns the number of bytes written on success,
or FALSE on failure.
The fputs() function is an alias of the fwrite() function.
Syntax
fputs(file,string,length)
Parameter
Description
file
string
length
<?php
$file = fopen("test.txt","w");
fputs($file,"Hello World. Testing!");
fclose($file);
?>
Uploader.php
<?php
$target_path = "uploads/";
$target_path = $target_path . basename(
$_FILES['uploadedfile']['name']);
if (file_exists("uploads/" . $_FILES['uploadedfile']["name"]))
{
echo $_FILES['uploadedfile']["name"] . " already exists. " ;
}
else
{ move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path);
echo "The file ". basename( $_FILES['uploadedfile']['name']). "
has been uploaded;}
?>
$_FILES Array
An associative array of items uploaded to the current
script via the HTTP POST method.
$_FILES['file_field_name']['name']
The original name of the file on the client machine.
$_FILES['file_field_name']['type']
The mime type of the file, if the browser provided this
information. An example would be "image/gif". This mime
type is however not checked on the PHP side and
therefore don't take its value for granted.
$_FILES['file_field_name']['size']
The size, in bytes, of the uploaded file.
$_FILES['file_field_name']['tmp_name']
The temporary filename of the file in which the uploaded
file was stored on the server.
$_FILES['file_field_name']['error']
The error code associated with this file upload. This
element was added in PHP 4.2.0