PHP fopen() Function

The fopen() function will open any valid file or url.

If the function fails it will return false along with an error generated. You can hide the error message by adding an “@” in front of the function name.

Syntax

[code lang=”php”]
fopen(filename, mode, include_path, context);
[/code]

Parameters

filename (String | Required)

This specifies the URL or file to open. Example: “./files/myfile.zip“.

mode (String | Required)

The type of access you are requesting for the file.

These are the valid access modes:

  • r” (Read only. Starts at the beginning of the file)
  • r+” (Read/Write. Starts at the beginning of the file)
  • w” (Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist)
  • w+” (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist)
  • a” (Write only. Opens and writes to the end of the file or creates a new file if it doesn’t exist)
  • a+” (Read/Write. Preserves file content by writing to the end of the file)
  • x” (Write only. Creates a new file. Returns FALSE and an error if file already exists)
  • x+” (Read/Write. Creates a new file. Returns FALSE and an error if file already exists)

include_path (Boolean | Optional)

This can be set to 1 or TRUE if you want to search for the requested file in the include path, also.

context (String | Optional)

Defines the context of the file stream. This is a set of options that change the behavior of the stream.

Originally posted at w3schools.com:

Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character. Windows offers a translation flag (‘t’) which will translate \n to \r\n when working with the file. You can also use ‘b’ to force binary mode. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

Here I showed you how to upload a file from a URL using this function.

Example:

[code lang=”php”]
$filename = “./images/myimage.jpg”;

$file = fopen($filename,”r”);

if($file){
echo “We have the file.”;
} else {
echo “File not found.”;
}
[/code]

Filed under: PHP, Web ProgrammingTagged with: , ,

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *
Website