A. D.
A. D.

Reputation: 758

PHP file download combined with a MySQL database entry (file is displayed in browser)

I have this PHP code that I use to download a file. It has always worked but now I have changed my server provider and it no longer works.

Before I let the user download the file, I want to add a database entry for that download with information (name of the downloaded file, user's IP address, user's host, current time).

So the two things work if I don't use the other, but combined they don't work. If I combinde them, it adds the entrybut just displays the file's contents on the website instead of downloading the file

This is the code:

<?php

$file = "./files/MyFile.zip";

if(!file_exists($file)){
  echo "File \"" . $file . "\" not found";
} else {
  $download_ip = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
  $host = gethostbyaddr($download_ip);

  // Connect
  $db = new mysqli('host', 'user', 'password', 'database');
  if ($db->connect_error) { die('Database error (' . $db->connect_errno . ') ' . $db->connect_error); }
  echo 'Successfully connected to database ' . $db->host_info . "<br />";

  // Query
  if($db->query("INSERT INTO downloads (name,ip,host,time) VALUES('".mysql_real_escape_string($id)."' , '$download_ip' , '$host' , NOW())") == true) {
    echo 'query was successful';
  } else {
    echo 'query failed';
  }

  // Close
  $db->close();

  // DL
  header('Content-type: application/octet-stream');
  header('Content-Length: ' . filesize($file));
  header('Content-Disposition: attachment; filename="' . basename($file) . '"');
  ob_clean();
  flush();
  readfile($file);
  exit();
}

?>

I am just a casual PHP user, so could anyone please help me? I'd appreciate it very much.

PHP version is 5.6 (but I can also change it to 5.5 or 5.3)

Upvotes: 1

Views: 543

Answers (1)

hellcode
hellcode

Reputation: 2698

Remove all "echo" commands, because you cannot send headers after that.

Upvotes: 1

Related Questions