Home Backend Development PHP Tutorial Learn php's fwrite function

Learn php's fwrite function

Jul 25, 2016 am 09:10 AM

This article introduces the usage of PHP's fwrite function for your reference. PHP fwrite() The fwrite() function is used to write a string to a file and returns the number of characters written successfully, otherwise it returns FALSE. grammar: int fwrite( res

This article introduces the usage of PHP’s fwrite function for your reference.

PHP fwrite() The fwrite() function is used to write a string to a file and returns the number of characters written successfully, otherwise it returns FALSE.

Syntax: int fwrite( resource handle, string string [, int length] ) fwrite() writes the contents of string to the file pointer handle. Parameter Description: Parameter Description handle The file pointer to which the string is to be written, usually created by the fopen() function data string to write length is optional and specifies the maximum number of bytes to be written

If the optional parameter length is specified, writing will stop when length bytes have been written or the string has been written.

Example:

Copy code The code is as follows:

$fh = fopen($filename, "w"); echo fwrite($fh, $word); // Output: 6 fclose($fh); ?>

Execute the example program. In the same directory as the program, the content of the file.txt file is: Hello!

Use length parameter In the above example, if the length parameter is used, at most length strings will be written: echo fwrite($fh, $word, 4); // Output: 4

PHP fwrite append writing The additional writing to the file actually has nothing to do with the fwrite function, but with the mode in which the fopen function opens the file. When fopen opens a file and the mode parameter selects a , it means appending to the file:

Copy code The code is as follows:

$fh = fopen($filename, "a"); echo fwrite($fh, $word); fclose($fh); ?>

PHP fwrite newline writing If you want to implement newline writing in the file, you only need to add the newline character n where the newline is required in the written content:

Copy code The code is as follows:

$fh = fopen($filename, "a"); echo fwrite($fh, $word); fclose($fh); ?>

The above example adds n newlines at the end of the content. To make n represent a newline when writing a file, you need to use double quotes when writing (as in the example above). If you use single quotes, the n character will not be interpreted as a newline but as an n string. Click to view: PHP string The difference between single quotes and double quotes.

n is already a real line feed. If you want to simulate a carriage return and line feed on the Windows operating system (that is, when you open a file with WordPad, it is not a black square but a list of lines), you can add r before n and carriage return. symbol:

Copy code The code is as follows:

PHP fwrite write permission When opening an existing file (usually in append-write mode), it is necessary to check whether the file has write permissions to avoid a system error. Use the is_writable function to check whether the file is writable.

The following is an example of stricter checking in append writing mode:

Copy code The code is as follows:

// Make sure the file exists and is writable if (is_writable($filename)) { //open a file if (!$fh = fopen($filename, 'a')) { echo "Cannot open file $filename"; exit; } // write content if (fwrite($fh, $word) === FALSE) { echo "Cannot write to file $filename"; exit; } echo "Successfully written $word to file $filename"; fclose($fh); } else { echo "File $filename is not writable"; } ?>

PHP fwrite function just performs the action of writing a string to a file. Its actual behavior depends more on the fopen function. If you want to write or append a string to a file all at once, the file_put_contents function may be a better choice.

PHP file_put_contents function: write or append string to file The PHP file_put_contents() function is the most suitable choice for writing a string or appending string contents to a file in one go.

file_put_contents() The file_put_contents() function is used to write a string to a file. It returns the number of bytes of data written to the file successfully, and returns FALSE if it fails.

Syntax: int file_put_contents ( string filename, string data [, int flags [, resource context]] )

Parameter Description: Parameter Description filename The name of the file to write data to data The data to be written. The type can be string, array (but not multi-dimensional array), or stream resource flags are optional and specify how to open/write the file. Possible values: FILE_USE_INCLUDE_PATH: Check the built-in path for a copy of filename FILE_APPEND: Write data by appending to the end of the file LOCK_EX: lock the file context is optional. Context is a set of options through which text attributes can be modified

Example:

Copy code The code is as follows:

Run this example, the browser output: 18 The content of the test.txt file (in the same directory as the program) is: This is something.

Tips If the file does not exist, create the file, equivalent to the behavior of the fopen() function. If the file exists, the contents of the file will be cleared by default. You can set the flags parameter value to FILE_APPEND to avoid this (see below). This function is safe for use with binary objects.

Write content in append form When the flags parameter value is set to FILE_APPEND, it means writing new data by appending content after the existing file content: After executing the program, the content of the test.txt file becomes: This is something.This is another something. The behavior of file_put_contents() is actually the same as calling fopen(), fwrite() and fclose() in sequence.

Reference reading

PHP fopen: file creation and opening. PHP fwrite: Write a string to a file. PHP close: Close an open file. PHP file_get_contents: Read the entire file contents into a string. PHP checks whether the file can be read and written using is_readable, is_writable and is_executable functions

The is_readable() function is used to check whether the file is readable, the is_writable() function is used to check whether the file is writable, and the is_executable() function is used to check whether the file is executable. is_readable() The is_readable() function is used to check whether the file is readable. If the specified file or directory exists and is readable, it returns TRUE, otherwise it returns FALSE.

Syntax: bool is_readable(string filename) example:

Copy code The code is as follows:

is_writable() The is_writable() function is used to check whether the file is writable and returns TRUE if the file exists and is writable, otherwise it returns FALSE.

Syntax: bool is_writable(string filename) The filename parameter can be a directory name that allows writability checking.

Example:

Copy code The code is as follows:

is_executable() The is_executable() function is used to check whether the file is executable and returns TRUE if the file exists and is executable, otherwise it returns FALSE. For usage, please refer to is_writable().



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP and Frameworks: Modernizing the Language PHP and Frameworks: Modernizing the Language Apr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles