sarthak
sarthak

Reputation: 297

Reading text file in PHP

My code-

$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";
      }
  }

So user uploads text file which contains data per line. I want to insert the data into the database till the query is executed.

What is getting inserted into db is fgets(Resource id #6) - and this keeps on going till i stop.,..it is uncontrolled...

Upvotes: 3

Views: 706

Answers (3)

scum
scum

Reputation: 3212

The function cannot be identified in the string and so is interpreted as raw text.

I'd recommend:

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

Upvotes: 0

Marc B
Marc B

Reputation: 360572

  $insert = "insert into $name (serial,data,used) values('','fgets($file)','0')";

You're inserting the literal text fgets($file) into your database, because it's embedded in the parent string. You'd want something like this, instead, which also (incidentally) removes sql injection vulnerabilities:

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

Why escape it? I don't know what's in that text file, but if ANY of the text contains so much as a single quote, it'll cause that particular insert to fail with an SQL syntax error, and now you've got a missing line in the database.

Upvotes: 2

DShook
DShook

Reputation: 15654

You need to take the fgets call out of single quotes which make it a string.

Upvotes: 0

Related Questions