search
HomeBackend DevelopmentPHP TutorialTroubleshooting on file operations in PHP development_PHP tutorial

Troubleshooting on file operations in PHP development_PHP tutorial

Jul 13, 2016 pm 05:19 PM
phpauthorPrefacerightdevelopoperatesupportdatabasedocumentDifficultiesofQ&A

作者:杨宗威
前言:

  PHP中对各类数据库的操作有着支持,对文件的操作也同样有着很丰富的操作方法,很多朋友现在的操作还是基于文件操作可是有的时候在操作文件的时候还存在不少的困惑和疑点,以下是我在日常编写过程中碰到的以及坛上朋友所碰到的关于文件操作的一些问题收藏吧。

  问:如何新建一个文件?

  答:

  1、使用fopen("要建立的文件名","参数"),参数可选w,w+,a,a+

  2、使用exec("echo > 要建立的文件名");这样是使用系统方式建立这个文件,你还可以使用touch这个linux命令来建立

  问:为什么我无法建立文件?

  答:

  1、如果你使用了fopen建立文件,是否正确的使用了参数

  2、系统权限问题,请询问你的WEBMASTER你的FTP目录是否有写的权限

  3、FTP权限问题,你要确认你的PHP文件所要写文件所在目录要有写的权限,也就是你的FTP软件登陆后other组要有写这个权限,

  如果没有请修改权限后尝试

  问:如何将文件读入数组?

  答:使用file函数

  问:如何将文件全部读出?

  答:

   

    1、使用fread($fp);

  2、如果你的PHP版本>=4.3.0的话可以使用file_get_contents();

  问:如何判断文件是否存在?

  答:使用file_exists();

  再问:为什么不使用fopen()来判断呢?

  答:原因是有时候是因为权限问题导致fopen返回的数据引导我们错误的判断

  问:为什么当我读取一个WEB页面的时候出错?

  答:

  1、可能是你的传递参数错,当读取WEB页面的时候你只可以使用r方式读取页面

  2、确保你要读取的WEB页面可以访问

  
    问:我如何才能获得文件的相关属性?

  答:PHP提供了一组获得文件属性的方法,例如 filemtime(),fileowner(),filegroup(),filectime(),fileatime()...详细的使用请参阅手册。

  问:PHP打开文件后是否可以象C一样进行文件“游标”的定位呢?

  答:可以的,使用fseek();

  问:我想在访问文件的时候不允许其他人也访问此文件,怎么办?

  答:

  1、你可以采用其他方面程序限制用户接入文件操作的页面

  2、使用flock();详细的参数以及使用方法请参阅手册

  问:如何删除文件内第一行,或指定一行数据?

  答:

  PHP并没有提供这样的操作方法,不过我们可以通过组合使用,以下代码演示我们将删除文件"test.dat"中的第三行数据(test.dat 文件中数据不止三行)

  

  <?php

   $filename="test.dat";//定义操作文件

   $delline=3; //要删除的行数

   if(!file_exsits($filename)){

    die("指定文件未发现!操作中断!");

   }

   $farray=file($filename);//读取文件数据到数组中

   for($tmpa=0;$Tmpa
    if(strcmp($Tmpa+1,$delline)==0){

     //判断删除的行

     continue;

    }

    //重新整理后的数据

    $newfp.=$farray[$Tmpa]." ";

   }

   $fp=@fopen($filename,"a") or die("写方式打开文件 $filename 失败");//我们以写的方式打开文件

   @fputs($fp,$newfp) or die("文件写入失败");

   @fclose($fp);

  ?>

  以上代码演示的是删除一行文件,不过你如果仔细的看的话,其实也给你提供了其他的文件操作的相关提醒~

  问:当我试图打开一个不存在的文件的时候,我如何不让错误显示出来以避免我的路径泄露!!

  答:在你要打开文件的方法前增加@符号用来屏蔽错误,@是PHP提供的错误信息屏蔽的专用符号或您可以在这个要操作的步骤前增加(通常是在页首)error_reporting(0);用来屏蔽页面内所有错误信息的显示一个不推荐的方法就是去修改php.ini(ISP除外)。

  问:我使用的是虚拟主机,我如何防止其他用户窃取我的数据?

  答:建议ISP修改php.ini中的open_basedir进行限制,不推荐的ISP设置是将fopen,file等文件操作加入disable_function中。

  问:为什么我用PHP建立文件后我FTP登陆要删除这些文件无法删除??

Answer: Mainly because the files created by PHP belong to the WEB user group, that is, the files created do not belong to your FTP user! ! ! The solution to this problem is to use chmod, unlink, etc. of the PHP program. It is recommended that users remember to chmod file permissions when using PHP to create files. It is recommended to be 777

Question: How to use text files as data warehouse? Some guestbooks, forums, etc. all use this!

Answer: In fact, this is just a typical example of using file and combining it with explode to read and split data.

Question: How to change the file name?

Answer: rename();

Question: How to delete files?

Answer: unlink(); exec("del(rm -vf) filename");

Note: rm -vf is for use under Linux

Question: How to clear files?

Answer: Use fopen(filename,"w"); or exec("echo > filename");

Question: How to edit the file content?

Answer: I remember I once answered a question about deleting file content. In fact, editing content only requires variable substitution based on deleting the content. I hope you can look up and change my continue above to replace the variable data.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/532668.htmlTechArticleAuthor: Yang Zongwei Foreword: PHP has support for the operation of various databases, and it also has many functions for the operation of files. Rich operating methods, many friends still operate based on files...
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.