Memory App
Programming
 




There are two types of streams (files & network). - php.* - standard PHP input/output - file - standard file access - http - access to remote resources via HTTP - ftp - access to remote resources via FTP - compress.zlib - access to compressed data stream using the zlib library fopen() - open a file

<?php
    $filename = "counter.txt";
    $counter = 0;

    if ($fd = @fopen($filename, "r")) {
        $counter = (int) fgets($fd); // gets first line content
        fclose($fd);
    }

    $fw = fopen($filename, "w+"); // open for reading and writing

    fwrite($fw, ++$counter); // writes new counter value

    fclose($fw);

    echo "There has been $counter hits to this page";
       
/*
    r - reading only (pointer at the beginning of the file)
    r+ - reading and writing (pointer at the beginning)
    w - writing only
    w+ - writing and reading
    a - writing only (pointer at the end)
    a+ - reading and writing (pointer at the end)
    x - creates a new file for writing only
    x+ - creates a new file for writing and reading

    w+b - forces binary mode (unaltered date will be written)
    w+t - windows only (Unix n will be converted to Windows rn)

    w, w+, a, a+ - automaticaly create a new file if not exists
    x, x+ - throw a worning if the file exists
*/
fgets() - gets line from file pointer

<?php
    $file = "file.txt";

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

    if ($fd = fopen($file, "r")) {
        
        $aLine =  fgets($fd); // 1024 byte length (default)
        echo $aLine . "<br>"; // Outputs: aaa

        rewind($fd);

        $aByte = fgets($fd, 1); // 1 byte length
        echo "^{$aByte}$" . "<br>"; // Outputs: ^$ (new line character)
        
        rewind($fd);

        $aByte2 = fgets($fd, 2); // 2 bytes
        echo "^{$aByte2}$" . "<br>"; // Outputs: ^a$

        rewind($fd);
        
        $aByte5 = fgets($fd, 5); // 5 bytes
        echo "^{$aByte5}$" . "<br>"; // Outputs: ^aaar $    
    }
feof() - determines when the internal pointer hits the end of a file

<?php
    $file = "file.txt";

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

    if ($fd = fopen($file, "r")) {
        
        $buffer = "";
        while(!feof($fd)) {
            $buffer .= fgets($fd);
        }

        echo $buffer; // Outputs: aaa bbb
    }


Questions



Top Reference > Programming
0/0 (80)  
Not Logged