Files

This page contains php code for reading and writing to and from files


<?php

set relative filepath

$filepath = "./FILE.EXT"; //within same directory, ../ within parent directory

open file and set as file handle

if (!($fp = fopen($filepath, "r"))) die ("Cannot open $filepath."); //r, r+, w, w+, a, a+

get file size

$my_file_stats = stat ($fp);
$my_file_size = $my_file_stats[7];

read all file

$my_lines_array = file("./FILE.EXT");
fpassthru($fp); //reads and writes remaining part of file, no need to use fclose
readfile("./FILE.EXT"); //reads and writes all file

read file one char at a time

while (!feof($fp) {
$one_char = fgetc($fp); //one character at a time
$data = fread ($fp, n); //n = number of characters, irrespective of line breaks
$chars_within_one_line = fgets($fp, n); //n = number of characters, stopping at line breaks
$my_data_values_array = fgetcsv($fp, n, "DELIMITER"); //n > number of characters in line
}

move file position indicator

fseek($fp, n, SEEK_SET); //n = number of characters to offset from beginning of file
fseek($fp, n, SEEK_CUR); //n = number of characters to offset from current position
fseek($fp, n, SEEK_END); //n = number of characters to offset from end of file
$fpi_offset = ftell($fp); //gets current position
rewind($fp); //resets position to 0

write to file

fwrite($fp,"TEXT");

close file handle

fclose ($fp);

?>


Page tags: php
page_revision: 2, last_edited: 1227739619|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License