PHP readfile is basically an inbuilt function in the PHP library used for reading a file and then writing it to an output buffer.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
readfile ( string $file_name [, boolean $path = FALSE [, resource $context ]] ) : int
The parameters being used in the syntax:
- filename:?It is a mandatory field where we provide the name of the file to be read.
- path:?This is an optional parameter and is a boolean value that can be set to either true or false if the file needs to be searched in the provided path.
- context:?This is also an optional field which is used to specify the context of the file handle. Basically a context is a collection of objects having an ability to change the behavior of that stream. It returns the number of bytes which is read from the file if success and returns false if failed to read.
Methods of PHP readfile
Apart from readfile() function, below are some of the other functions that can be used for performing various kinds of operations on the files.
1. file()
This function is also used to read a file and it reads the complete file into an array.
Syntax:
file?(?string?$file_name?[,?int?$flag?= 0?[,?resource?$context?]] ) :?array
where file_name is the path to the file to be read. Flags are the optional fields which can be chosen from the below constants:
- FILE_USE_INCLUDE_PATH:?To search for the respective file in the given path.
- FILE_IGNORE_NEW_LINES:?To omit a new line at the last of each array element.
- FILE_SKIP_EMPTY_LINES:?To skip empty lines.
It returns the file present in the array upon success and false upon failure.
2. fopen()
This function can be used to open both a file and a URL.
fopen?(?string?$file_name?,?string?$mode?[,?bool?$use_include_path?=?FALSE?[,?resource?$context?]] ) :?resource
- where if file_name is a URL then PHP searches a protocol handler (also called as a wrapper) for it. The PHP will issue a notice to help track possible problems in the script and then continue considering it as a normal regular file_name.
- Suppose if the file_name is a local file then PHP tries to open the same stream on that file. The file will be accessible by PHP only if required permissions are granted for its access.
- And suppose the given file_name is a registered protocol and if that one is registered as a network URL then the first PHP ensures that the allow_url_fopen is enabled. It will issue a warning and fail if it is disabled.
Mode:?This parameter mentions the kind of access required to be given to the stream.’? Below are few important modes:
- r – read mode only
- r+ – both read and write only
- w – write mode only
It returns a file pointer resource if success and false on failure.
3. fread()
This function is used for binary-safe file read.
Syntax:
fread?(?resource?$handle?,?int?$length?) :?string
where the handle is used for referencing the file pointer.
The file is read until it reaches one of the below conditions: length in bytes must have been read, EOF is reached, socket timeout occurs. fgets(), fscanf(), ftell(), fwrite(), fopen(), fsockopen() are a few other functions used for file operations in PHP.
Examples of?PHP readfile
Given below are the examples of PHP readfile:
Example #1
Code:
<?php // it is writing content of file to output // buffer used in readfile() function echo readfile("file.txt"); ?>
Output:
This shows a basic example to read a file existing in the local path. Make sure that the filename being specified in the parameter of readfile() function is created and the content to be read is present inside the file. When the readfile() function is used it reads the content of the file and prints in the output.
Example #2
Code:
<?php / file contents written on output // buffer by readfile() function $file = @readfile("file.txt"); if (!$file) { print "File could not be opened"; } ?>
Output:
The previous output was a simple example without any conditions. In this example, let us see how to read and display the output of a file by using certain conditions. We are using if statement to print suppose the file is not present.
Example #3
Code:
<?php $file_name = "file.txt"; $fh = fopen($file_name, 'r'); $data = fread($fh, filesize($file_name)); fclose($fh); echo $data; ?>
Output:
In this example, we are combining the use of multiple file read functions. As in all the above examples, first, we are giving the file name which needs to be read from. Then the mode of operation, ‘r’ is given to them indicating it can only be read. filesize() function takes the filename and returns the size of the file along with its data and assigns it to $data variable. By using fclose() function we are closing that file. Finally, the data is printed as output.
Example #4
Code:
<?php $file_name = "file.txt"; $file = fopen( $file_name , "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $size = filesize( $file_name ); $filetext = fread( $file, $size); fclose( $file ); echo ( "The size of input file in bytes is : $size\n" ); echo ("Printing details of file:\n"); echo ( $filetext ); ?>
Output:
Before running the code, make sure that the file to be read file.txt is created in the local file path. In this example first, we are declaring the file name to be read and opening that with the function fopen(). Suppose the file does not exist, using if condition we are throwing an error message. Finally, we are printing the file size and the content present in the input file.
Conclusion
As seen from all the above examples, readfile() is one of the main functions of PHP used for reading the file name specified in this function. Apart from readfile() we have covered a few other file operations which perform similar actions such as fopen, file, fread, fgets, fgetss, ftell, etc. A combination of all of these are basically used in accessing and performing operations on the input file.
The above is the detailed content of PHP readfile. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

The way to process raw POST data in PHP is to use $rawData=file_get_contents('php://input'), which is suitable for receiving JSON, XML, or other custom format data. 1.php://input is a read-only stream, which is only valid in POST requests; 2. Common problems include server configuration or middleware reading input streams, which makes it impossible to obtain data; 3. Application scenarios include receiving front-end fetch requests, third-party service callbacks, and building RESTfulAPIs; 4. The difference from $_POST is that $_POST automatically parses standard form data, while the original data is suitable for non-standard formats and allows manual parsing; 5. Ordinary HTM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp
