php学习基础-文件系统(二) 文件读写操作、文件资源处理
一、文件的打开与关闭
/* *读取文件中的内容 * file_get_contents(); //php5以上 * file() * readfile(); * * 不足:全部读取, 不能读取部分,也不能指定的区域 * * fopen() * fread() * fgetc() * fgets() * * * * * 写入文件 * file_put_contents(“URL”, “内容字符串”); //php5以上 * 如果文件不存在,则创建,并写入内容 * 如果文件存在,则删除文件中的内容,重新写放 * * 不足: 不能以追加的方式写,也不能加锁 * * fopen() * fwrite() 别名 fputs * * * 本地文件: * ./test.txt * c:/appserv/www/index.html * /usr/local/apahce/index.html * * 远程: * http://www.baidu.com * http://www.163.com * * ftp:[email protected]:www.baidu.com/index.php * *///读取出所有行 $lines=file("lampcms.sql");$sqlstr="";foreach($lines as $line){ $line=trim($line); if($line!=""){ if(!($line{0}=="#" || $line{0}.$line{1}=="--")){ $sqlstr.=$line; } }}$sqlstr=rtrim($sqlstr,";");$sqls=explode(";",$sqlstr);echo '<pre class="brush:php;toolbar:false">';print_r($sqls);echo '';
二、小偷程序,抓取网站上的页面,从页面链接中获取资源图片
$str=file_get_contents("http://www.163.com");preg_match_all('/\<img alt="php学习基础-文件系统(2) 文件读写操作、文件资源处理" >/i',$str, $images);$imgs=""; foreach($images[0] as $img){ $imgs.=$img.'<br>';}echo file_put_contents("test.txt", $imgs);
三、更改网站配置项,修改文件内容,先读取,在使用正则匹配写入
if(isset($_POST["sub"])){ setConfig($_POST);}function setConfig($post){ //读取文件中的内容 $str=file_get_contents("config.inc.php"); $zz=array(); $rep=array(); foreach($post as $key=>$value ){ $zz[]="/define\(\"{$key}\",\s*.*?\);/i"; $rep[]="define(\"{$key}\", \"{$value}\");"; } echo '<pre class="brush:php;toolbar:false">'; print_r($zz); print_r($rep); echo ''; //改写文件中的内容 $str=preg_replace($zz, $rep, $str); file_put_contents("config.inc.php", $str); //再写回文件}?>
四、读取文件中得sql,执行sql
$lines=file("lampcms.sql");$sqlstr="";foreach($lines as $line){ $line=trim($line); if($line!=""){ if(!($line{0}=="#" || $line{0}.$line{1}=="--")){ $sqlstr.=$line; } }}$sqlstr=rtrim($sqlstr,";");$sqls=explode(";",$sqlstr);echo '<pre class="brush:php;toolbar:false">';print_r($sqls);echo '';
五、向文件中写入内容
/*写入文件 * file_put_contents(“URL”, “内容字符串”); //php5以上 * 如果文件不存在,则创建,并写入内容 * 如果文件存在,则删除文件中的内容,重新写放 * * 不足: 不能以追加的方式写,也不能加锁 * * fopen() * fwrite() 别名 fputs */ $file=fopen("./test.txt", "a"); //如果打开文件成功返回资源,如果失败返回false for($i=0; $i<br><br><p>六、循环读取文件每次按照固定长度读取</p><p></p><pre code_snippet_id="324578" snippet_file_name="blog_20140503_6_8088416" name="code" class="php"> $file=fopen("http://www.163.com", "r"); //如果打开文件成功返回资源,如果失败返回false $str=""; while(!feof($file)){ $str.=fread($file, 1024); } echo $str; fclose($file); //关闭文件资源
七、文件常用函数实例
$file=fopen("./test.txt", "r"); //如果打开文件成功返回资源,如果失败返回false echo ftell($file)."<br>"; echo fread($file, 10)."<br>"; echo ftell($file)."<br>"; echo fread($file, 10)."<br>"; echo ftell($file)."<br>"; fseek($file,100, SEEK_CUR); echo ftell($file)."<br>"; echo fread($file, 10)."<br>"; echo ftell($file)."<br>"; fseek($file,-20, SEEK_END); echo fread($file, 20)."<br>"; echo ftell($file)."<br>"; rewind($file); //回到文件头部 echo ftell($file)."<br>"; echo fread($file, 20)."<br>"; fclose($file); //关闭文件资源

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use
