【问题标题】:Reading text file in PHP在 PHP 中读取文本文件
【发布时间】:2011-04-08 19:25:28
【问题描述】:

我的代码-

$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext=="txt")
&& ($_FILES["file"]["size"] < 2000000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {$newname = 'news/'.$filename;
     move_uploaded_file($_FILES['file']['tmp_name'],$newname);
     $fileread = $newname;
    //reading a file
$file = fopen($fileread, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
      //inserting each data into table
      $insert = "insert into $name (serial,data,used) values('','fgets($file)','0')";
      $query = mysqli_query($connect,$insert);
      if($query)
      {
          echo "cool";
      }
  }

所以用户上传包含每行数据的文本文件。我想将数据插入到数据库中,直到查询执行完毕。

插入 db 的是 fgets(Resource id #6) - 这一直持续到我停止。,..它不受控制...

【问题讨论】:

  • 存在安全风险。据我所见,它正在抓取特定文件夹中的所有文本文件并阅读它们。任何文本文件都可以有任何内容。可能会发生 Mysql 注入,Marc B 对此进行了解释。
  • 为什么要将文件的内容存储在数据库中?只需存储(大概)上传文件的文件名... o_O

标签: php mysql database file


【解决方案1】:
  $insert = "insert into $name (serial,data,used) values('','fgets($file)','0')";

您将文字文本fgets($file) 插入到您的数据库中,因为它嵌入在父字符串中。相反,您会想要这样的东西,它也(顺便)消除了 sql 注入漏洞:

 $string = fgets($file);
 $string = mysql_real_escape_string($string);
 $insert = "insert into ... values ( ..., '$string', ...)";

为什么要逃避它?我不知道该文本文件中的内容,但如果任何文本包含单引号,则会导致特定插入失败并出现 SQL 语法错误,现在您在数据库。

【讨论】:

  • 哇...你完全摇滚..它完美无瑕...再次感谢大家。
【解决方案2】:

您需要从单引号中取出 fgets 调用,使其成为字符串。

【讨论】:

    【解决方案3】:

    函数无法在字符串中识别,因此被解释为原始文本。

    我会推荐:

    //inserting each data into table
    $data = fgets($file);
    $insert = "insert into $name (serial,data,used) values('', {$data}, '0')";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 2014-12-19
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多