Memory App
 




fread() - read arbitrary data from a file

<?php
    // Unlike fgets(), it does not concern itself with newline characters

    $file = "file.txt";

    if ($fd = fopen($file, "w+")) {
        fwrite($fd, "aaarn");
        fwrite($fd, "bbb");
        fclose($fd);
    }

    if ($fd = fopen($file, "r")) {
        
        $contents = fread($fd, filesize($file));
        echo $contents . "<br>"; // Output: aaa bbb

        rewind($fd);
        echo fread($fd, 2) . "<br>"; // Output: aa

        rewind($fd);
        echo fread($fd); // Warning: fread() expects exactly 2 parameters, 1 given
    }
file_exists() - Checks whether a file or directory exists (returns TRUE/FALSE)

<?php
    if (!file_exists('paht/to/foo.txt')) {
        throw new Exception ("The file does not exists");
    }
fseek() - Seeks on a file pointer

<?php
    if ($fd = fopen("file.txt", "w+")) {
        fwrite($fd, "abcrn");
        fwrite($fd, "def");
        fclose($fd);
    }

    if ($fd = fopen("file.txt", "r")) {

        fseek($fd, 2); // advance 2 chars
        echo fgets($fd) . "<br>"; // Outputs: c

        fseek($fd, 2, SEEK_SET); // default (go to begging of the file)
        echo fgets($fd) . "<br>"; // Outputs: c

        fseek($fd, 0, SEEK_CUR); // start from current position
        echo fgets($fd) . "<br>"; // Outputs: def

        fseek($fd, -2, SEEK_END); // start from the end of the file
        echo fgets($fd) . "<br>"; // Outputs: ef
    }
ftell() - Returns the current position of the file read/write pointer (or FALSE)

<?php
    $fd = fopen("example.txt", "r");
    fseek($fd, 2);
    echo ftell($fd); // Output: 2

<?php
    $fd = fopen("example.txt", "r");
    $data = fgets($fd, 2);
    echo ftell($fd); // Output: 1


Questions
0/0 (80)  
Not Logged