Table of Contents
This article mainly shares with you basic operation examples of PHP files. I hope it can help you. First, let's share with you the basic operations of reading and writing PHP files. " >This article mainly shares with you basic operation examples of PHP files. I hope it can help you. First, let's share with you the basic operations of reading and writing PHP files.
Basic operations of reading and writing" >Basic operations of reading and writing
Other commonly used file functions
Home Backend Development PHP Tutorial PHP file basic operation examples sharing

PHP file basic operation examples sharing

Mar 20, 2018 pm 01:27 PM
php share Basic operations


This article mainly shares with you basic operation examples of PHP files. I hope it can help you. First, let's share with you the basic operations of reading and writing PHP files.

Basic operations of reading and writing

  • Write file function: file_put_contents()

    • FILE_USE_INCLUDE_PATH : The built-in path for a copy of filename will be checked

    • LOCK_EX : The file will be locked

    • FILE_APPEND : Will be moved to the end of the file. Otherwise, the contents of the file will be cleared

    • Syntax:

      int file_put_contents(file,data,mode,context)

      Parameters Description
      file Required. Specifies the file to which data is to be written. If the file does not exist, a new file is created.
      data Optional. Specifies the data to be written to the file. Can be a string, one-dimensional array, or data stream.
      mode Optional. How to open/write files. Possible values: FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX
      context Optional. Specifies the environment for a file handle. context is a set of options that can modify the behavior of the stream. If null is used, it is ignored.
    • Return value: This function will return the number of bytes of data written to the file.

    • mode parameter description

    • The function is the same as calling fopen(), fwrite() and fclose() in sequence.

  • Read file function: file_get_contents()

    • Syntax:

      string file_put_contents (path,include_path,context,start,max_length)

      ##ParameterDescriptionpathRequired. Specifies the file to be read. Can be an external urlinclude_pathoptional. If you also want to search for files in include_path, you can set this parameter to "1". contextOptional. Specifies the environment for a file handle. startOptional. Specifies the position in the file to begin reading. This parameter is new in PHP 5.1. max_lengthOptional. Specifies the number of bytes to read. This parameter is new in PHP 5.1.
    • Return value: the read string.

    • Other commonly used file functions

      • Unlink() Delete file

      • ##Rename( ) File move (rename)

      • Filesize() File size

      • File_exists() Whether the file exists

      • Filemtime() The last modification time of the file!

      File handle reading and writing operations

      Most file reading and writing are completed using the functions: File_put_contents, file_get_contents.

      In a few cases, in special cases, the above two functions are not easy to use.
      Typically, the file is too large! It can only be operated part by part!
      The basic units are bytes:

      • #fopen() function opens a file or URL.

        If the opening fails, this function returns FALSE.

        Open file handle, data path between PHP program and file!
        Requires two parameters: file address and open mode!

        Open mode: Specify what operations need to be performed after opening the file! The following modes can be selected:

        • #r: read, read mode.

        • w: write, write operation, clear write.

        • a: append, write operation, append writing.

        • x: New writing can only create new files for operation! It is a write operation, similar to w

        • + extended mode: extended operations can complete read and write operations.

          <?php
              $handle = fopen(&#39;./data.txt&#39;,&#39;r&#39;);
              var_dump($handle); // resoure(3) of type (stream) 得到一个资源类型
          ?>
          Copy after login
      • File handle reading functions fread(),fgetc(),fgets(),feof();

        • One byte data = fgetc(handle); //garbled characters in the case of multi-byte characters

          Whenever a byte is read, move the file pointer forward by one byte! In handle operations, it depends on the file pointer!

        • String = fgets(handle, length)

          If a newline character is read first when reading, it will also terminate. Also called the line reading function! Typical logic, each line records a set of information, this function is the most commonly used!

        • feof() determines whether the end of the file is reached

          Read all the information in the file Example:

          <?php
              $handle = fopen(&#39;./langref.txt&#39;,&#39;r&#39;);
              while (! feof($handle)) {
                  $line = fgets($handle,1024);
                  echo $line . "</br>";
              }
          ?>
          Copy after login

        • String = fread(handle, Length)

          Read content based on length, which is different from fgets and is not limited by newlines
          The only restriction is: the maximum length cannot exceed 8192!

      • File handle write function fwrite($handle, content)

      • Close handle fclose($handle)

      • Pointer operation function


        • fseek(handle, position), positioning setting pointer, the position starts from 0 and increases!

        • ftell(handle), get the pointer position!

      Concurrent file operations (file lock)

      By default, PHP's file operation function is not in a blocking state. Free operating state. Therefore, it is easy to cause errors when operating files concurrently. When one script operation needs to block other script operations, file locks need to be used.

      Lock operation process:


      Add the lock first, check whether the lock is added successfully, and use it again if successful!

      Lock type:

      • Read lock: s-lock (share-lock) shared lock, the expected additional lock before the read operation. As a result, concurrent reads are allowed and additional write operations are blocked.

      • Write lock: x-lock (exclusive-lock) exclusive lock, exclusive lock, try to add the lock type before writing operation. As a result, other scripts cannot read or write.

      • Intention lock: All scripts that operate resources follow a convention to use file locks (convention).

      flock($handle, lock type);

      Type:

      • LOCK_SH Read lock

      • LOCK_EX Write lock

      • ##LOCK_UN Unlock
      • <?php
            //*********脚本1,想要读取文件信息***********
            //尝试加读锁
            $lock_result= flock($handle, LOCK_SH);
            //判断锁定结果
            if(!$lock_result){
                die(&#39;锁定失败,不能操作文件&#39;);
            }
            //文件操作
            $str = fgets($handle, 1024);
            var_dump($str);
        
            sleep(5);
            echo &#39;<br>&#39;;
            $str = fgets($handle, 1024);
            var_dump($str);
            flock($handle, LOCK_UN);//解锁
        ?>
        
        <?php
            //*********脚本2,想要往文件里写入信息***********
            //尝试加写锁
            $lock_result= flock($handle, LOCK_EX);
            //判断锁定结果
            if(!$lock_result){
                die(&#39;锁定失败,不能操作文件&#39;);
            }
            //文件操作
            $result = fwrite($handle, &#39;123456&#39;);
            flock($handle, LOCK_UN);//解锁
        ?>
        Copy after login

        When colleagues execute, the above script 2 needs to wait (in the blocked state) for script 1 to complete before it is executed. ,

        Emphasize that you must judge whether the lock is added successfully

        You can use LOCK_NB to not block when the lock fails:

        $lock_result = flock($handle, LOCK_EX | LOCK_NB);
        Copy after login

      • Unlock:

        Flock($handle, LOCK_UN) to force unlock,
      • Fclose() to automatically unlock!
      • Related recommendations:

      PHP file operation example sharing

      php file upload basic introduction

      php file upload simple example sharing

The above is the detailed content of PHP file basic operation examples sharing. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles