This article mainly introduces the introduction to PHP file programming. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
1 Get file information
1.1 The first way (fopen, fstat, file_exists)
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ // 检查文件或目录是否存在,存在则返回 TRUE,否则返回 FALSE $fp = fopen($file_full_path, 'r'); // 打开文件或url,成功时返回文件指针资源,如果打开失败,本函数返回 FALSE。 $fileinfo_arr = fstat($fp); // 通过已打开的文件指针取得文件信息,返回一个数组具有该文件的统计信息 echo '<pre class="brush:php;toolbar:false">'; var_dump($fileinfo_arr); echo '文件的大小是:' . $fileinfo_arr['size'] . '个字节'; echo '文件的创建时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['ctime']); echo '文件的访问时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['atime']); echo '文件的修改时间是:' . date('Y-m-d H:i:s', $fileinfo_arr['mtime']); }else{ echo '文件不存在'; }
1.2 The second way
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ echo '文件的大小是:' . filesize($file_full_path); echo '文件的类型是:' . filetype($file_full_path); echo '文件的创建时间是:' . date('Y-m-d H:i:s', filectime($file_full_path)); echo '文件的访问时间是:' . date('Y-m-d H:i:s', fileatime($file_full_path)); echo '文件的修改时间是:' . date('Y-m-d H:i:s', filemtime($file_full_path)); }else{ echo '文件不存在'; }
2 Read the file content
2.1 The first way, fread
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ // 1、打开文件 $fp = fopen($file_full_path, 'r'); // 2、获取文件的大小 $file_size = filesize($file_full_path); // 3、读取内容 $con_str = fread($fp, $file_size); // 返回所读取的字符串, 或者在失败时返回 FALSE。 fclose($fp); // 替换换行符 $con_str = str_replace("\r\n", '<br>', $con_str); $con_str = str_replace("\n", '<br>', $con_str); // 替换 tab $con_str = str_replace(" ", " ", $con_str); echo $con_str; }else{ echo '文件不存在'; }
2.2 The second way, feof
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ $fp = fopen($file_full_path, 'r'); // 设置缓冲 $buffer = ''; $buffer_size = 1024; $con_str = ''; while(!feof($fp)){ // 测试文件指针是否到了文件结束的位置,到达返回true,否则返回false $buffer = fread($fp, $buffer_size); $con_str .= $buffer; } // 关闭文件 fclose($fp); $con_str = str_replace("\r\n", '<br>', $con_str); $con_str = str_replace("\n", '<br>', $con_str); $con_str = str_replace(" ", ' ', $con_str); echo $con_str; }else{ echo '文件不存在'; }
2.3 The third way, file_get_contents
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ $con_str = file_get_contents($file_full_path); // 将整个文件读入一个字符串 $con_str = str_replace("\r\n", '<br>', $con_str); $con_str = str_replace("\n", '<br>', $con_str); $con_str = str_replace(" ", ' ', $con_str); echo $con_str; }else{ echo '文件不存在'; }
3 Create a file and write the content
3.1 Case 1
<?php $file_full_path = './test.txt'; if(!file_exists($file_full_path)){ if($fp = fopen($file_full_path, 'w')){ // 覆盖写入10句helloworld $con = ''; for($i=0; $i<10; $i++){ $con .= "HelloWorld\r\n"; } // 写入文件 fwrite($fp, $con); // fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。 fclose($fp); }else{ echo '创建文件失败'; } }else{ echo '文件已经存在'; }
3.2 Case 2, file_put_contents
<?php $file_full_path = './test.txt'; if(!file_exists($file_full_path)){ $con = ''; for($i=0; $i<10; $i++){ $con .= "helloworld\r\n"; } // 默认是覆盖写,可以追加FILE_APPEND参数,改为追加写。 file_put_contents($file_full_path, $con); // 和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。 }else{ echo '已经存在该文件'; }
4 Delete file
<?php $file_full_path = './test.txt'; if(file_exists($file_full_path)){ if(unlink($file_full_path)){ echo '<br>删除成功'; }else{ echo '<br>删除失败'; } }else{ echo '文件不存在,无法删除'; }
5 Modify file name
<?php $file_full_path = './test.txt'; $file_new_full_path = './王八.txt'; $file_new_full_path = iconv('utf-8', 'gbk', $file_new_full_path); if(file_exists($file_full_path)){ if(rename($file_full_path, $file_new_full_path)){ // 重命名一个文件或目录 echo '改名成功!'; }else{ echo '改名失败!'; } }else{ echo '文件不存在'; }
6 Operate file directory
6.1 Create a first-level directory
<?php $dir_full_path = './abc'; // 判断有没有该目录 if(!is_dir($dir_full_path)){ if(mkdir($dir_full_path)){ echo '创建目录成功!'; }else{ echo '创建目录失败!'; } }else{ echo '已经存在该目录,无法再次创建'; }
6.2 Create a multi-level directory
<?php $dir_full_path = './abc/edf/xyz'; if(!is_dir($dir_full_path)){ if(mkdir($dir_full_path, 0777, true)){ // true 表示递归创建 echo '创建目录成功'; }else{ echo '创建目录失败'; } }else{ echo '已经存在该目录,无法再次创建!'; }
6.3 Delete a directory (first level)
<?php $dir_full_path = './abc'; if(is_dir($dir_full_path)){ if(rmdir($dir_full_path)){ echo '删除目录成功'; }else{ echo '删除目录失败'; } }else{ echo '不存在该文件夹'; }
7 Application cases of file programming
7.1 How to copy a picture
<?php $file_src_full_path = 'F:/壁纸.jpg'; $file_src_full_path = iconv('utf-8', 'gbk', $file_src_full_path); $file_des_full_path = 'D:/amp/WWW/萧山.jpg'; $file_des_full_path = iconv('utf-8', 'gbk', $file_des_full_path); if(file_exists($file_src_full_path)){ if(copy($file_src_full_path, $file_des_full_path)){ echo '拷贝成功'; }else{ echo '拷贝失败'; } }else{ echo '没有这个文件'; }
7.2 Traverse a folder and determine whether the contents under the folder are directories and files
<?php $dir_full_path = 'D:/amp/WWW/'; if(is_dir($dir_full_path)){ $dir_handle = opendir($dir_full_path); // 如果成功则返回目录句柄的 resource,失败则返回 FALSE while(($file_name = readdir($dir_handle)) !== false){ // 成功则返回文件名 或者在失败时返回 FALSE if(is_dir($dir_full_path . $file_name)){ echo $file_name . '是目录<br>'; }else{ echo $file_name . '是文件<br>'; } } closedir($dir_handle); }else{ echo '不是目录,无法打开'; }
7.3 Write a function to count the size of all files in a directory
<?php $dir_name = 'D:/amp/WWW'; function getDirSize($dir_name){ $dir_size = 0; $dir_handle = opendir($dir_name); while(($file_name = readdir($dir_handle)) !== false){ $file = $dir_name . '/' . $file_name; // 文件全名 if($file_name!=='.' && $file_name!=='..'){ if(is_dir($file)){ $dir_size += getDirSize($file); }else{ $dir_size += filesize($file); } } } closedir($dir_handle); return $dir_size; } echo getDirSize($dir_name);
<br/>
7.4 Delete a directory
<?php $dir_name = 'D:/amp/WWW/.idea'; function rrmdir($src){ $dir_handle = opendir($src); while(false !== ($file = readdir($dir_handle))){ if(($file != '.') && ($file != '..')){ $full = $src . '/' . $file; if(is_dir($full)){ rrmdir($full); }else{ unlink($full); } } } closedir($dir_handle); rmdir($src); } rrmdir($dir_name);
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
php code for traversing all files and sub-files in a folder
PHP files and Directory operations
The above is the detailed content of Introduction to PHP file programming. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

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 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 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.

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

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.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools