FILE HANDLING

FILE HANDLING:
The file is a sequence of bytes which is used to store data it is a logical entity which will be stored in the memory waving particular address.there are various types of file like “txt”, binary files stored with the extension “bin” etc.the file syntax for creating file is given as :
checking whether a file exists

if(file_exists("testfile.txt"))echo "File exists";
Creating a file:
<?php
$fh=fopen("testfile.txy",'w')or die("Failed to createw file");
$text =<<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh,$text)ordie("Could not write to file");
fclose($fh);
echo "File 'testfile.txt'written successfully";
?>

Reading from file:

<?php
$fh=fopen("testfile.txt",'r')or die("File does not exist or you lack permission to open it");
<?php
$fh=fopen("testfile.txt",'r')or die("File does not exist or you lack permission to open it");
$line=fgets($fh);
fclose($fh);
echo $line;
?>

Copying Files:

<?php //copyfile.php
copy('testfile.txt','testfile2.txt') or die("could not copy file");
echo "File successfully copied to 'testfile2.txt' ";
?>

Moving a File:

<?php
if(!rename('testfile2.txt','testfile2.new'))
echo "Could not rename file";
else echo "File successfully renamed to 'testfile2.new'";
?>

Deleting a file:

<?php
if(!unlink('testfile2.new')) 
echo "Could not delete File";
else 
echo"File 'testfile2.new' successfully deleted";
?>

Updating File:

<?php
$fh=fopen("testfile.txt",'r+') or die("Falied to open file");
$text=fgets($fh);
fseek($fh,0,SEEK_END);
fwrite($fh,"$text")or die("Failed to open file");
fclose($fh);
echo "File 'testfile.txt' successfully updated";
?>

Uploading Files:

<?php
echo<<<END
<html><head><title>PHP from Upload</title></head><body>
<form method='post' action='upload.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='10'>
<input type='submit' value='Upload'>
</form>
_END;
if($_FILES)
{
$name=$_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'],$name);
echo "Uploaded image '$name'<br><img src='$name'>";
}
echo "</body></html>";
?>
Translate »