Thursday, 7 July 2011

Files in PHP

Copy a file - copy($source, $dest);
Rename      - rename(orignl,new);
Delete      - unlink(file);

Easy way to see the contents of a file  - file_get_contents()

But for more options,  use the following method,

1. Open the file

   $fp = fopen ("file.txt","r"or"w"or"a");  //$fp is the file pointer,r stands for read, w for write,a for append

2. Read the file
   
   $contents = fread($fp, 10)//the 2nd arg accepts the length upto which the file must be read 

   for reading the whole file, replace 10 with filesize("file.txt");

   * The file pointer points at a position in the file
 

   for writing into the file, $contents= fwrite($fp, "blahblahblah",length);//THE LENGTH IS  OPTIONAL

   * if a file does not exist, fwrite creates it.
--------the file pointer--------
   the file pointer moves and stays at a place when we do something to the file.
    we can manually control it using fseek

    eg: fseek($fp, 5). The file pointer moves to the 5th byte relative to the BEGINNING

            fseek($fp, -4 , SEEK_END);//moves the file pointer 4 bytes from the end to the beginning
        
        fseek($fp, 1, SEEK_CUR);//moves 1 byte forward from the current position

        
            ftell($fp)// returns the current position of the pointer 

        rewind($fp) // moves the pinter to the beginning. Same as fseek($fp, 0);

        
   ------------Modes----------------
      r+   :open the file for reading and writing(DOES NOT DELETE ANYTHING)

      w+   :UNLINKE r+, IT BLANKS THE FILE. if the file does not exist, it creates the file.

      a+   :append and read

      x    :if the file exists, returns ERROR. otherwise create it.

stat("text.txt") //returns the info abt file in ARRAY

file("text.txt")  //returns an ARRAY of the contents of the file seperated by NEW LINE

                   check php.net for more options like ignore empty lines
fileatime(), filectime(), filemtime()-----same as the data returned by stat()..accessed time, modified time

FILE-PERMISSIONS
    is_readable() & is_writable()

    chmod($file, 0444) ---makes the file read-only  //php.net for more info

    fileperms — Gets file permissions
FOR BIG FILES, USE WHILE LOOP

    while(!feof($fp)){

     echo fread($fp, 4092);

   }

No comments:

Post a Comment