Php method code for reading files

Source: Internet
Author: User
Tags fread readfile alphanumeric characters
Compiled a few php read files in a few ways to facilitate later access, hope to help everyone.

1.frea,

string fread (int $handle, int $length)

Fread () reads up to length bytes from a file pointed to by handle. The function stops reading the file when it has read up to the maximum length of bytes, or when it reaches EOF, or (for a network stream) when a package is available, or when 8,192 bytes have been read (after opening a stream of user space), depending on which situation is encountered first.

Fread () returns the read string if an error returns FALSE.

<?php    $filename = "/usr/local/something.txt";    $handle = fopen ($filename, "R");//To read the binary file, the second parameter needs to be set to ' RB '        //through FileSize to obtain the file size, the entire file is read into a string at once    $contents = Fread ($handle, FileSize ($filename));    Fclose ($handle);? >

You cannot use this method if the file you are reading is not a local normal file, but a remote file or a stream file, because FileSize cannot get the size of these files. At this point, you need to determine whether the end of the file has been read by the return value of feof () or fread ().
  
For example:

<?php    $handle = fopen (' http://www.baidu.com ', ' R ');    $content = ";    while (!feof ($handle)) {        $content. = Fread ($handle, 8080);    }    echo $content;    Fclose ($handle);? >

Or:

<?php    $handle = fopen (' http://www.baidu.com ', ' R ');    $content = ";    while (false! = ($a = fread ($handle, 8080))) {//returns false to indicate that a $content has been read to the end of the file        . = $a;    }    echo $content;    Fclose ($handle);? >

2.fgets

String fgets (int $handle [, int $length])

Fgets () reads a row from the file pointed to by handle and returns a string up to length-1 bytes in length. Stop after encountering a newline character (included in the return value), EOF, or having read the length-1 byte (see first the case). If length is not specified, the default is 1 K, or 1024 bytes.

<?php    $handle = fopen ('./file.txt ', ' R ');    while (!feof ($handle)) {        echo fgets ($handle, 1024x768);    }    Fclose ($handle);? >

The note:length parameter becomes optional from PHP 4.2.0, and if omitted, the length of the line is assumed to be 1024. starting with PHP 4.3, ignoring length will continue to read data from the stream until the end of the line. If most of the rows in the file are larger than 8KB, specifying the length of the largest row in the script is more efficient with resources. Starting with PHP 4.3 This function can be used safely in binary files. The earlier versions were not.

3.fgetss

String Fgetss (Resource $handle [, int $length [, String $allowable _tags]])

As with the Fgets function, but FGETSS tries to remove any HTML and PHP tags from the text that is being read, you can specify which tags are not removed with the optional third parameter.

<?php    $handle = fopen ('./file.txt ', ' R ');    while (!feof ($handle)) {        echo fgetss ($handle, 1024x768, ' <br> ');    }    Fclose ($handle);? >

4.file

Array file (string $filename [, int $use _include_path [, Resource $context]])

Reads the contents of a file into an array, each of which corresponds to a line in the file, including newline characters. You can use the RTrim () function to filter line breaks when you don't need a line terminator.

<?php    $a = File ('./file.txt ');    foreach ($a as $line = + $content) {        echo ' line '. $line + 1). ': ' $content;    }? >

5.readfile

int ReadFile (string $filename [, bool $use _include_path [, Resource $context]])

Reads a file and writes to the output buffer. Returns the number of bytes read from the file. If an error returns false and the error message is displayed unless it is called in the form of @readfile ().

<?php    $size = ReadFile ('./file.txt ');    Echo $size;? >

6.file_get_contents

String file_get_contents (String $filename [, bool $use _include_path [, Resource $context [, int $offset [, int $maxlen] ]]] )

Reads a file into a string. The third parameter, $context, can be used to set parameters such as setting timeouts when accessing remote files, and so on.

In addition, File_get_contents has a much better performance than several of these functions, so it should be preferable to use file_get_contents. But ReadFile looks better than file_get_contents (? ), because it does not need to call fopen.

<?php     $ctx = stream_context_create (Array ('         http ' = = = Array (             ' timeout ' + 1    //Set timeout            )         )     );     Echo file_get_contents ("http://www.baidu.com/", 0, $ctx);?>

7.fpassthru

int Fpassthru (Resource $handle)

Reads the given file pointer from the current location to EOF and writes the result to the output buffer.

<?php     Header ("Content-type:text/html;charset=utf-8");     $handle = fopen ('./test2.php ', ' R ');    Fseek ($handle, 1024);//Position the pointer at 1024 bytes    fpassthru ($handle);? >

8.parse_ini_file

Array Parse_ini_file (string $filename [, bool $process _sections])

Parse_ini_file () Loads a INI file specified by filename and returns the settings in it as a union array. If you set the last process_sections parameter to TRUE, you will get a multidimensional array that includes the name and settings of each section in the configuration file. The default value for Process_sections is FALSE.

Attention:
1. If the value in the INI file contains any non-alphanumeric characters, you need to enclose it in double quotation marks (").
2. Some reserved words cannot be used as key names in the INI file, including: Null,yes,no,true and false. A value of Null,no and false is equivalent to "", and a value of Yes and true is equivalent to "1". Character {}|&~! [() "also cannot be used anywhere in the key name, and these characters have a special meaning in the option value.
Test.ini File Contents:

; This is a sample configuration file
; Comments start with '; ', as in php.ini

[First_section]one = 1five = 5animal = Bird[second_section]path = "/usr/local/bin" URL = "Http://www.example.com/~username

test.php content:

<?php     $config = Parse_ini_file ('./test.ini ', ture);     Print_r ($config);? >

Output content:

Array (    [first_section] = = Array        (            [One] = 1            [Five] = 5            [Animal] = BIRD        )    [ Second_section] = Array        (            [path] =/usr/local/bin            [URL] + http://www.example.com/~username        ))

Several caveats:

1. Encourage the use of the B flag when working with binary files, even if the system does not need it, to make the script more portable.

2. The allow_url_fopen option activates the URL form of the fopen encapsulation protocol so that URL objects such as files can be accessed. The default encapsulation protocol provides access to remote files with FTP and HTTP protocols, and some extension libraries such as zlib may register more encapsulation protocols. For security reasons, this option can only be set in php.ini.

3. If you want to open a URL with special characters (for example, a space), you need to use UrlEncode () for URL encoding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.