PHP File fopen


The fopen() function is used to open a file or URL address.


fopen() opens the file

PHP does not have a separate file creation function, create and open files are used fopen() function. When a file is opened with the fopen() function, if the file does not exist, it tries to create the file and returns a resource.

if the open fails, this function returns FALSE.

grammar:

Resource fopen(string filename, string mode)

The parameter filename is the name of the file you are trying to open /create, and the parameter mode specifies the open mode. The possible values ​​are as follows:

Open Mode Description
r Read-only, and point the file pointer to the beginning of the file
r + read and write, the file pointer to the file start location
w Write only, point the file pointer to the beginning of the file and empty the contents of the file, try to create a file if it does not exist
w + read and write, the file pointer to the beginning of the file location and the contents of the file empty, if the file does not exist try to create the
a Append, point the file pointer to the end of the file to operate, if the file does not exist try to create the
a + read and write append, the file pointer to the end of the file to operate, if the file does not exist try to create the
x Write only, and create the file, if the file already exists, the fopen() call fails and returns FALSE
x + read and write, and create a file, if the file already exists, the fopen() call fails and returns FALSE

For file pointers, see "PHP File Pointer Functions."

To create an example of a file:

if (!file_exists("test.txt ")) {// if the file does not exist(the default is the current directory)
    $fh=fopen("test.txt"," w ");
    fclose($fh); // Close the file
}

Tip: In the above example, if test.txt already exists, it will not create a new file.


fopen() Opens the URL address

The fopen() function can also be used to open URL addresses on the internet:

$fh=fopen("http://www.google.com/"," r ");
if ($fh) {
    while(!feof($fh)) {
        echo fgets($fh);
    }
}

Run the example, the page will display google home page.

Note: fopen() returns only a resource, in order to display the open page address, but also need to use fgets() function to read and output.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook