Home > Backend Development > PHP Tutorial > PHP file basic operation examples sharing

PHP file basic operation examples sharing

小云云
Release: 2023-03-21 18:50:01
Original
1116 people have browsed it


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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template