专业编程基础技术教程

网站首页 > 基础教程 正文

PHP处理文件(php操作文件的常用函数)

ccvgpt 2024-07-19 12:46:13 基础教程 7 ℃

程序员代码开发,一定要小心小心再小心,不给黑客留破绽。黑客一定要学开发,不知道开发,怎么发现开发中的漏洞呢?脚本小子和黑客大牛,差的就是开发经验~


PHP处理文件(php操作文件的常用函数)

从 0 到 1 构建威胁情报系统(知乎)

作者 ailx10

去查看

一、PHP读写文件

1、简单的读文件(file_get_contents方法

a

<?php

$hack_home = file_get_contents("hack-home.html");
if(date('H' > 12)){
    $hack_home = str_replace("{color}","blue",$hack_home);
}else{
    $hack_home = str_replace("{color}","yellow",$hack_home);
}
print $hack_home;

2、简单的写文件(file_put_contents方法

<?php

$hack_home = file_get_contents("hack-home.html");
if(date('H' > 12)){
    $hack_home = str_replace("{color}","blue",$hack_home);
}else{
    $hack_home = str_replace("{color}","yellow",$hack_home);
}

file_put_contents("ailx10-home.html",$hack_home);

二、精细的读写文件内容

1、文件内容比较少(file方法

<?php

foreach (file("ailx10-hackbiji.txt") as $line){
    $line = trim($line);
    $info = explode("|",$line);
    print "<li><font color='red' >$info[0]</font>($info[1])</li>";
}
fclose($f);

2、文件内容超级多

  • fopen 打开文件
  • fgets 读取文件一行
  • feop 判断是否读到文件末尾
  • fclose 关闭文件
<?php

$f = fopen("ailx10-hackbiji.txt","rb");
while( (! feof($f)) && ($line = fgets($f)) ){
    $line = trim($line);
    $info = explode("|",$line);
    print "<li><font color='blue' >$info[0]</font>($info[1])</li>";
}
fclose($f);

三、处理CSV文件

CSV文件是程序员非常喜欢的文件格式,它比Excel更加轻量级,它使用逗号进行数据分割

  • 和普通读写的差别是 fgetcsv 方法
  • 直接读出数组,非常适合结构化的数据
  • 同理,fputcsv方法直接把数组,写成csv文件
<?php

$f = fopen("ailx10.csv","rb");
$i = 0;
while( (! feof($f)) && ($line = fgetcsv($f)) ){
    $i +=1;
    if($i==1)
    {
        continue;
    }else {

        $info = $line;
        print "<li><font color='blue' >@$info[0]</font>($info[1]),那时候是$info[3]年,我上$info[2]</li>";
    }
}
fclose($f);
  • 也可以直接下载csv文件
  • fputcsv($fh,$row); 其中打开的文件是 php://output
<?php
try {
    $db = new PDO("mysql:host=127.0.0.1;dbname=hack", "root", "");
    print "数据库连接成功~<br>";

    header("Content-Type: text/csv");
    header("Content-Disposition:attachment; filename=ailx10.csv");
    $fh = fopen("php://output","wb");
    $que = $db->query('select * from study where subject like "web安全%"');
    while($row = $que->fetch()){
        fputcsv($fh,$row);
    }
    fclose($fh);
}catch (PDOException $e) {
    print "数据库连接失败,因为:" . $e->getMessage();
}

?>

四、PHP文件权限

  • file_exists 检查文件和目录是否存在
  • is_readable 检查程序是否有权限读文件
  • is_writeable 检查程序是否有权限写文件
  • 读文件之前,先判断是否有读权限
  • 写文件之前,先判断是否有写权限

五、错误检查

  • 很多方法都有返回值,判断是成功还是失败
  • 失败的时候返回往往是 false
  • 但成功时,返回有可能是0
  • 这个时候就要注意使用===恒等运算符来检测返回值

六、路径穿越

  • 警惕 ../返回上一层 ,别让用户穿越路径
  • 这是靶场必备的题型,划重点啦~

本篇完,谢谢大家~

Tags:

最近发表
标签列表