PHP

  minte9
REMEMBERS




Last update:   29-10-2021

Files and Network

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
 
$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";
fgets() - gets line from file pointer
 
$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
 
$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    
Read file
        A B C D E F
🔔
1/2