PHP Files functions

simple functions

<?php
$docRoot = $_SERVER['DOCUMENT_ROOT'];
//readfile($docRoot."/orders/order.txt"); //do not need fopen
unlink($docRoot."/orders/order.txt");
$fp = fopen($docRoot."/orders/orders.txt",rb);
if($fp){
    echo "open ok";
}else{
    echo 'error';
}
while (!feof($fp)){
    echo fgetc($fp);
}
//fpassthru($fp);  //out put string   needs fopen
//$len = fwrite($fp,'12345',3);
rewind($fp);
fseek();
fclose($fp);
//file_put_contents($docRoot/orders/order.txt,'123',FILE_APPEND);

Examples

<?php
  // create short variable name
  $document_root = $_SERVER['DOCUMENT_ROOT'];
?>
<!DOCTYPE html>
<html>
  <head>
    <title>Bob's Auto Parts - Customer Orders</title>
  </head>
  <body>
    <h1>Bob's Auto Parts</h1>
    <h2>Customer Orders</h2> 
    <?php
      @$fp = fopen("$document_root/orders/Book1.csv", 'rb');
      flock($fp, LOCK_SH); // lock file for reading

      if (!$fp) {
        echo "<p><strong>No orders pending.<br />
              Please try again later.</strong></p>";
        exit;
      }

      while (!feof($fp)) {
         $order= fgets($fp);
         echo htmlspecialchars($order)."<br />";
      }

      flock($fp, LOCK_UN); // release read lock

      echo 'Final position of the file pointer is '.(ftell($fp));
      echo '<br />';
      rewind($fp);
      echo 'After rewind, the position is '.(ftell($fp));
      echo '<br />';

//    while (!feof($fp)) {
//
//          $s= fgetcsv($fp,9,',');
//          echo "<pre>";
//     var_dump($s);
//    }

    if(is_null($s)) {
        echo 'null';
    }
      fclose($fp); 

    ?>
  </body>
</html>

相关推荐