php - file

最後更新: 2017-08-08

目錄

 


file_put_contents

 

PHP Version: 5

Usage:

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

* identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
* If filename does not exist, the file is created
* Default: overwritten

FLAG:

    FILE_APPEND
    # Acquire an exclusive lock on the file while proceeding to the writing.
    LOCK_EX

Return Values:

number of bytes that were written to the file

OR

FALSE on failure.

i.e.

<?php
    $file = 'test_rw_file.txt';
    $msg = "some msg\n";
    file_put_contents($file, $msg, FILE_APPEND | LOCK_EX);
?>

 


fopen, fread (PHP 4, PHP 5)

 

fopen()

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

mode:

'r'      Open for reading only; place the file pointer at the beginning of the file.

'r+'    Open for reading and writing; place the file pointer at the beginning of the file.

'w'     Open for writing only;

place the file pointer at the beginning of the file and truncate the file to zero length.

If the file does not exist, attempt to create it.

i.e.

<?php
    $handle = fopen("/home/rasmus/file.txt", "r");
    $handle = fopen("/home/rasmus/file.gif", "wb");
    $handle = fopen("http://www.example.com/", "r");
    $handle = fopen("ftp://user:[email protected]/somefile.txt", "w");
?>

int fwrite ( resource $handle , string $string [, int $length ] )

fwrite() writes the contents of string to the file stream pointed to by handle.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached,

whichever comes first.

If writing twice to the file pointer, then the data will be appended to the end of the file content:

i.e.

<?php
    $fp = fopen('data.txt', 'w');
    fwrite($fp, '1');
    fwrite($fp, '23');
    fclose($fp);

    // the content of 'data.txt' is now 123 and not 23!
?>

fread()

The function reads from an open file.

fread ( resource $stream , int $length )

i.e.

$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));

fclose - Closes an open file pointer

Returns TRUE on success or FALSE on failure.

 


Rename / Move file

 

<?php
  $from = "/tmp/tmp_file.txt"
  $to = "/home/data/my_file.txt"
  rename($from, $to);
?>

 


 

 

 

 

Creative Commons license icon Creative Commons license icon