minte9
LearnRemember



Read file

Outputs a file (useful when you need to include static files).
 
header("Content-type: <span class='keyword_code'>application/pdf</span>");
readfile("zce-php.pdf");
Read a file into an array of lines.
 
/* * example.txt --
    aaa
    bbb
    ccc
*/

$arr = file("example.txt");

print_r($arr); // [0] => aaa [1] => bbb [2] => ccc 

Get Contents

Load an entire file into memory (returns the file as string). Use urlencode() for URI with special characters like space (?a=Hello World)
 
$file = file_get_contents("example.txt");
 
$file = file_get_contents("http://studyon.minte9.com");
echo urlencode($file);
Read 3 characters starting from 2st character.
 
/* * example.txt --
    aaa
    bbb
    ccc
*/

$file = file_get_contents("example.txt", NULL, NULL, 2, 3);
echo $file; // a b (anb)

    // Second param can be: NULL, TRUE or FILE_USE_INCLUDE_PATH (php > 5)
    // Third param refers to Stream context

Put contents

Allows you to write the contents of a PHP string to a file in one pass.
 
touch("example.txt");

$data = "My Data";

file_put_contents("example.txt", $data);
    // example.txt content is now: My Data

// using flags
$data = "My Data2";
file_put_contents("example.txt", $data, FILE_APPEND);
    // content now: My DataMy Data2

// LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents("example.txt", "xxx", <span class='keyword_code'>FILE_APPEND | LOCK_EX</span>);
With an array, will automatically apply the equivalent of implode('', $array).
 
touch("example.txt");

$data = array("xxx", "yyy", "zzz");

file_put_contents("example.txt", $data); // content_file: xxxyyyzzz



  Last update: 303 days ago