Implementation of File Operations Creation of File, Open, Read, Write

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

SUJAL MORADIYA

21ID01IT021

Implementation of file operations Creation


of file, open, read, write

1. Write a PHP script to open a file in PHP using fopen() and


fclose() function.

<?php
$check = fopen("res.txt", "r");
fclose($check);
echo "HELLO!";
?>

2. Write a PHP script to write content of the string into file.

<?php

$file_pointer = 'res.txt';
$open = file_get_contents($file_pointer);
$open .= "hello!";
file_put_contents($file_pointer, $open);
echo "content added";
?>

3. Write a PHP script to delete file using unink()

function. <?php

$file_pointer = "res.txt";

if (!unlink($file_pointer)) {
echo ("$file_pointer cannot be deleted due to an error");
}
else {
echo ("$file_pointer has been deleted");
}
?>

4. Write a PHP script to show the use of PHP Open File Modes.
<?php
$myfile = fopen("res.txt", "r") or die("Unable to
open file!");
echo fread($myfile,filesize("res.txt"));
fclose($myfile);
?>

5. Write a PHP script to read data of the file using fread() function.

<?php
$myfile = fopen("res.txt","r") or die("Unable to pen
file!");
echo fread($myfile, filesize("res.txt"));
fclose($myfile);
?>

6. Write a PHP script to show the use of fgets() function.

<?php
$fp = fopen("res.txt","r");
echo fgets($fp);
fclose($fp);
?>
7. Write a PHP script to show the use of fputs() function.

<?php
$theFile = fopen("example.txt","a");
fputs($theFile,"line of text\n");
echo "content added";
?>

8. Write a PHP script to show the use of fgetc() function.

<?php
$fp = fopen("example.txt","r");
while(!feof($fp))
{
echo fgetc($fp);
}
fclose($fp);
?>

<?php
$i=0;
$fp = fopen("example.txt","r");
while(!feof($fp))
{
echo fgetc($fp);
$i++;
}
echo $i;
?>
9. Write a PHP script to show the use of fwrite() function.

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

10. Write a PHP script to upload a file in directory.

<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");

if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}

if($file_size > 2097152){


$errors[]='File size must be excately 2 MB';
}

if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>

<form action="" method="POST" enctype="multipart/form-data">


<input type="file" name="image" />
<input type="submit"/>
</form>

</body>
</html>

You might also like