Things to note when reading files with php fread

高洛峰
Release: 2023-03-03 20:34:01
Original
1332 people have browsed it

php fread function introduction

string fread (int handle, int length)

fread() reads up to length bytes from the file pointer handle. This function is called after reading up to length bytes, or when EOF is reached, or (for network streams) when a packet is available, or (after opening a user space stream) 8192 bytes have been read. Reading of the file will stop.

fread() example:

<?php
  $file = "data.txt";
  $fh = fopen($file, "rt");
  $userdata = fread($fh, filesize($file));
  fclose($fh);
?>
Copy after login

Some points you need to pay attention to when using fread in php

1. Solutions to errors when fread reads and writes large files

If the file exceeds php.ini when using fread to read a file When setting the maximum memory usage value in It is returned in the form of a string, so how does it identify the encoding method used in a.txt to ensure that it is not garbled?

Character encoding is not recognized in file operations for versions below PHP 7.0.

It is only output in byte data. If it is consistent with the character encoding of the php source code file and the output html, it can be displayed correctly.

3. When fread reads a file, there will always be an extra null character

<?
  set_time_limit(0);//设置脚本执行时间无限长
  $flie="flexbuilder_linux_install_a5_112409.bin";//大文件超过php.ini中的内存配置
  $fp=fopen($flie,"r");
  $content="";
  $filename="123.bin";//存为新文件
  $handle=fopen($filename,"a");//写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之
  while(!feof($fp)){//测试文件指针是否到了文件结束的位置
    $content=fread($fp,1024);
    fwrite($handle,$content);
  }
  fclose($fp);
  fclose($handle);
  echo "数据成功写入文件";
?>
Copy after login

When we use the above code to read the file, sometimes there will be an extra null character. This is because you are on a WINDOWS platform, and the file is a text file that is opened and stored. There will be a special byte at the end to mark the end of the file. If you open it with rb, you can naturally read the last special byte. Open it with r and read it with fgets.

I hope this article can help everyone, thank you for your support of this site!

For more articles related to the precautions for reading files with php fread, please pay attention to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!