PHP-File Handling

File Handling

fopen()

The fopen() function is used to open files in PHP. Using the correct mode parameter is very important at this point, as it identifies the type of file access that will be required. Below is a list of all possible mode parameters you can use with the fopen() function.

If file open successfully it returns resource id else it will return false on failure.

fopen() functions enable to open the specific file it returns 0 (false).

Syntax

fopen(filename,mode)

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

Example

<?php

$file=fopen(“test.txt”,”r”);

echo $file;                               // If File Found its return unique resource id

?>

Above example open file test.txt in read only mode, if file found it will return Resource id, else it will return 0.

fread()

The fread() reads from 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 read string, or FALSE on failure. fread is binary safe file read means binary data like images and character data can be written with this function.

Syntax

string fread ( resource $handle , int $length )

$handle           A file system pointer resource that is typically created using fopen().

$length                        Up to length number of bytes read.

fwrite()

fwrite() function write 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

int fwrite ( resource $handle , string $string [, int $length ] )

$handle           A file system pointer resource that is typically created using fopen().

$string             String that to be written

$length            writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

fclose()

The fclose() function closes an open file. This function returns TRUE on success or FALSE on failure.

Syntax

bool fclose($handle)

$handle           A file system pointer resource that is typically created using fopen().

file_exists()

The file_exists() function checks whether or not a file or directory exists. This function returns TRUE if the file or directory exists, otherwise it returns FALSE.

Syntax

bool file_exists ( string $filename )

$filename        Path to the file or directory

fgets()

The fgets() function returns a line from an open file. The fgets() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.This function returns FALSE on failure

Syntax

string fgets ( resource $handle [, int $length ] )

$handle           The file pointer must be valid, and must point to a file successfully opened by fopen()

Length             Optional. Specifies the number of bytes to read. Default is 1024 bytes.

fgetc()

The fgetc() function returns a single character from an open file. It get a character from the given file pointer.

Syntax

string fgetc ( resource $handle )

$handle           The file pointer must be valid, and must point to a file successfully opened by fopen().

file()

Reads entire file into an array

Syntax

array file ( string $filename)

filename          Path to the file.

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

fgetss()

when we are reading any HTML tags then it will print tags effect, to not print the tag effect fgetss() function is used to print the HTML tag effects also.


Return a line with HTML tags removed from an open file.

String fgetss($file, [$length, $tag])

fputs()

fputs function is alias of fwrite() function

<?php

$file = fopen(“test.txt”,”w”);

echo fputs($file,”Hello World. Testing!”);

fclose($file);

?>

fpassthru()

read all data from the current position in an open file, Until EOF writes the result to the output buffer function return number of character passed or false on failure

string fpassthru($file);

<?php

/*fpassthru

This function returns the number of characters passed or FALSE on failure.

*/

$file = fopen(“test.txt”,”r”);

// Read first line

echo fgets($file);

echo “<BR><BR>”;

// Send rest of the file to the output buffer

echo fpassthru($file);

fclose($file);

?>

fgetcsv()

Parse line from open file checking fromo csv fields, function return .csv fields in an array on success or false on failure.

It will read only first line of csv file

Array fgetcsv($file,length,seprator)

<?php

$file = fopen(“13contract.csv”,”r”);

print_r(fgetcsv($file));

fclose($file);

?>

<?php

$file = fopen(“13contract.csv”,”r”);

print_r(fgetcsv($file,5,” “));

fclose($file);

?>

Contacts.csv

Kai Jim, Refsnes, Stavanger, Norway

Hege, Refsnes, Stavanger, Norway

readfile()

opens a file sends its contents to the browser and closes the file.

Function return no. of bytes read on success, or false on error

Int readfile($file)

Example

<?php

/*

The readfile() function reads a file and writes it to the output buffer

*/

echo readfile(“test.txt”);

?>

basename()

<?php

/*The basename() function returns the filename from a path.

string basename(path,suffix)

path     Required. Specifies the path to check

suffix   Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show*/

$path = “/testweb/home.php”;

//Show filename with file extension

echo basename($path) .”<br/>”;

//Show filename without file extension

echo basename($path,”.php”);

?>

filetype()

Return type of file (eg file or dir) false on failure

            string filetype(file path)

<?php

/*The filetype() function returns the file type of a specified file or directory.

This function returns the one of seven possible values on success or FALSE on failure.

echo filetype(“test.txt”);

?>

is_dir()

return true if passed value is directory, false if it isn’t

            bool is_dir(filename)

is_file()

return true if passed value is file, false if it isn’t

            bool is_file(filename)

Example

<?php

/*

The is_dir() function checks whether the specified file is a directory.

This function returns TRUE if the directory exists.*/

$file = “filehandling”;

if(is_dir($file))

{

echo (“$file is a directory”);

}

else

{

echo (“$file is not a directory”);

}

?>

<?php

$file = “test.txt”;

if(is_file($file))

{

echo (“$file is a regular file”);

}

else

{

echo (“$file is not a regular file”);

}

?>

is_readable()

The is_readable() function checks whether the specified file is readable. Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Syntax

bool is_readable ( string $filename )

$filename        Path to the file or directory

Example

<?php

$filename = ‘test.txt’;

if (is_readable($filename))

{

echo ‘The file is readable’;

} else

{

echo ‘The file is not readable’;

}

?>

In above file will check whether test.txt file is readable or not, if readable it will return “test.txt is readable”.

is_writable()

The is_writeable() function checks whether the specified file is writeable.

Syntax

bool is_writable ( string $filename )

$filename        Path to the file or directory

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Example

<?php

$filename = ‘test.txt’;

if (is_writable($filename))

{

echo ‘The file is writable’;

} else

{

echo ‘The file is not writable’;

}

?>

In above example will return true if file is writable.

fseek()

The fseek() function seeks in an open file. This function moves the file pointer from its current position to a new position, forward or backward, specified by the number of bytes. This function returns 0 on success, or -1 on failure.

Syntax

int fseek ( resource $handle , int $offset)

handle             A file system pointer resource that is typically created using fopen().

Offset        The offset. To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

ftell()

The ftell() function returns the current position in an open file.

Syntax

              int ftell ( resource $handle )

handle   The file pointer must be valid, and must point to a file successfully opened by fopen()

Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream. If an error occurs, returns FALSE.

Example

<?php

$file = fopen(“test.txt”,”r”);

// print current position

echo ftell($file);

// change current position

fseek($file,”10″);

// print current position again

echo “<br>” . ftell($file);

fclose($file);

?>

test.txt

Welcome to File handling

This is to test file handling

ftell example

rewind()

The rewind() function “rewinds” the position of the file pointer to the beginning of the file.This function returns TRUE on success, or FALSE on failure.

Syntax

bool rewind ( resource $handle )

$handle           The file pointer must be valid, and must point to a file successfully opened by fopen().

copy()

The copy() function copies a file. This function returns TRUE on success and FALSE on failure.

Syntax

bool copy ( string $source , string $dest)

source              Path to the source file.

Dest                 The destination path

ulink()

The unlink() function deletes a file. This function returns TRUE on success, or FALSE on failure.

Syntax

bool unlink ( string $filename)

$filename                    Path to the file.

Example

<?php

$fh = fopen(‘test.txt’, ‘a’);

fwrite($fh, ‘<h1>Hello world</h1>’);

fclose($fh);

echo(unlink(‘test.txt’));            //deletes file

?>

rename()

The rename() function renames a file or directory. This function returns TRUE on success, or FALSE on failure.

Syntax

bool rename ( string $oldname , string $newname)

oldname          The old name

newname         The new name

fileatime()

Return file last access time

int fileatime(filename)

<?php

//This function returns the last access time timestamp on success, FALSE on failure

echo fileatime(“test.txt”);

echo “<br />”;

echo “Last access: “.date(“F d Y H:i:s.”,fileatime(“test.txt”));

?>

filemtime()

Returns last modified time of file

int filemtime(filename)

<?php

//The filemtime() function returns the last time the file content was modified.

echo filemtime(“test.txt”);

echo “<br />”;

echo “Last modified: “.date(“F d Y H:i:s.”,filemtime(“test.txt”));

?

file_get_contents()

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.

Syntax

file_get_contents(path)

path                             Required. Specifies the file to read

Example

<?php

echo file_get_contents(“test.txt”);

?>

file_put_contents

The file_put_contents() writes a string to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Syntax

file_put_contents(file,data,mode,context)

file        Required. Specifies the file to write to. If the file does not exist, this function will create one

data       Required. The data to write to the file

mode   Optional. Specifies how to open/write to the file. Possible values

FILE_APPEND                                 If file filename already exists, append the data to the file instead of overwriting it.

LOCK_EX                                         Acquire an exclusive lock on the file while proceeding to the writing

/

move_upload_file()

The move_uploaded_file() function moves an uploaded file to a new location. This function returns TRUE on success, or FALSE on failure. if the destination file already exists, it will be overwritten.

              bool move_uploaded_file ( string $filename , string $destination )

filename          The filename of the uploaded file.

Destination      The destination of the moved file.

Example

<html>

<body>

<form action=”upload_file.php” method=”post”

enctype=”multipart/form-data”>

<label for=”file”>Filename:</label>

<input type=”file” name=”file” id=”file” />

<br>

<input type=”submit” name=”submit” value=”Submit” />

</form>

</body>

</html>

Upload_file.php

<?php

if ((($_FILES[“file”][“type”] == “image/gif”)|| ($_FILES[“file”][“type”] == “image/jpeg”)

|| ($_FILES[“file”][“type”] == “image/pjpeg”)))

{

echo “Upload: ” . $_FILES[“file”][“name”] . “<br>”;

echo “Type: ” . $_FILES[“file”][“type”] . “<br>”;

echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” Kb<br>”;

echo “Temp file: ” . $_FILES[“file”][“tmp_name”] . “<br>”;

if (file_exists(“upload/” . $_FILES[“file”][“name”]))

{

echo $_FILES[“file”][“name”] . ” already exists. “;

}

else

{

move_uploaded_file($_FILES[“file”][“tmp_name”],

“upload/” . $_FILES[“file”][“name”]);

echo “Stored in: ” . “upload/” . $_FILES[“file”][“name”];

}

}

?>

221 thoughts on “PHP-File Handling

  1. Pingback: Google
  2. Pingback: 먹튀검증
  3. Pingback: cursos online
  4. Pingback: porn massage
  5. Pingback: fbv cursos grátis
  6. Pingback: referat 12631
  7. Pingback: bondage sex kit
  8. Pingback: exercise equipment
  9. Pingback: kegel beads
  10. Pingback: Romantic shayari
  11. Pingback: lego 21035
  12. Pingback: luxury sex toys
  13. Pingback: Google
  14. Pingback: Chicago SEO
  15. Pingback: Detroit SEO
  16. Pingback: online earn money
  17. Pingback: multqa.ae
  18. Pingback: curso online
  19. Pingback: hitachi magic wand
  20. Pingback: curve massager
  21. Pingback: music theory
  22. Pingback: Gay Sex
  23. Pingback: deluxe vibrator
  24. Pingback: chwilówki
  25. Pingback: girth enlargement
  26. Pingback: vibrato lesson
  27. Pingback: jelly dildo
  28. Pingback: Porn City
  29. Pingback: Nerf Gun
  30. Pingback: doors cape town
  31. Pingback: office jobs
  32. Pingback: Expensive
  33. Pingback: penis enlarger
  34. Pingback: anal sex kit
  35. Pingback: strapless dildo
  36. Pingback: fun88
  37. Pingback: 188bet
  38. Pingback: max results pump
  39. Pingback: webcam sex
  40. Pingback: фуражи
  41. Pingback: apps for pc
  42. Pingback: gay anal cleaning
  43. Pingback: Speelgoed bol
  44. Pingback: top couples toy
  45. Pingback: cursos gratuitos
  46. Pingback: Indiatimes
  47. Pingback: cock gay
  48. Pingback: webcambabes
  49. Pingback: shemale dating
  50. Pingback: sexe webcam
  51. Pingback: vaginal dildo
  52. Pingback: strapless strapon
  53. Pingback: dildo with balls
  54. Pingback: butt plug
  55. Pingback: халепа
  56. Pingback: sex toy store
  57. Pingback: the best strap on
  58. Pingback: male stroker
  59. Pingback: get a bigger penis
  60. Pingback: silver bullet toy
  61. Pingback: gay anal cleaning
  62. Pingback: real penis dildo
  63. Pingback: bum plugs
  64. Pingback: Porn
  65. Pingback: best dildos
  66. Pingback: обуть
  67. Pingback: best anal plugs
  68. Pingback: squirting dildo
  69. Pingback: rabbit vibrator
  70. Pingback: huge gay dong
  71. Pingback: anal from behind
  72. Pingback: pleasure panty
  73. Pingback: 15% minoxidil
  74. Pingback: best penis ring
  75. Pingback: satta king
  76. Pingback: double bullet vibe
  77. Pingback: pocket stroker
  78. Pingback: best double dildo
  79. Pingback: best male stroker
  80. Pingback: g spot stimulator
  81. Pingback: anal plug kit
  82. Pingback: porn
  83. Pingback: powerdirector apk
  84. Pingback: male cyberskin
  85. Pingback: true feel dildo
  86. Pingback: EU
  87. Pingback: ssru.ac.th
  88. Pingback: large dong
  89. Pingback: rabbit sex toys
  90. Pingback: best male sex toys
  91. Pingback: bullet sex toy
  92. Pingback: sexy bondage
  93. Pingback: porn land
  94. Pingback: orgasm dildo
  95. Pingback: sexy stocking
  96. Pingback: hundehule
  97. Pingback: more info
  98. Pingback: Julia Ann
  99. Pingback: bdjobstoday bd
  100. Pingback: Fashion Station
  101. Pingback: Pakistani Suits
  102. Pingback: sexboer
  103. Pingback: geile sex filmpjes
  104. Pingback: gratis films
  105. Pingback: pornofilmpjes
  106. Pingback: liteblue login
  107. Pingback: iptv xtream
  108. Pingback: liteblue usps gov
  109. Pingback: virtual visa card

Leave a Reply