2

I'm currently developping a PHP website and I need to store files in my database. I'm using a LONGBLOB to store files such as PDF,PPTX,... The file upload was working fine until i get this error : Fatal error: Allowed memory size of 134217728 bytes exhausted

Here is my function :

public function uploadFile() {
    // We upload only pdf for now
    if (isset($_FILES['fichier']['name']) && $_FILES['fichier']['type']=="application/pdf"){
      $tmp_name = $_FILES['fichier']['tmp_name'];
      // Avoid problem with space
      $nom = str_replace(' ','_',$_FILES['fichier']['name']);
      $taille = $_FILES['fichier']['size'];
      $type = $_FILES['fichier']['type'];
      $fp = fopen($tmp_name, 'rb');
      $content = fread($fp, filesize($tmp_name));
      $statement = $this->db->prepare("INSERT INTO document(nomfichier,fichier,typefichier,taillefichier) VALUES (?,?,?,?)");
      $statement->bindParam(1, $nom);
      $statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);
      $statement->bindParam(3, $type);
      $statement->bindParam(4, $taille);
      $statement->execute();
      $statement->closeCursor();
      // Redirect
      header('Location: documentation');
      die('redirect');

Edit : Problem comes from the database who choose a blob instead of longblob when regenerated

Tikroz
  • 183
  • 2
  • 14
  • You might want to increase the memory limit and also check for the max. allowed file size for your uploads - http://stackoverflow.com/q/2184513/80836 – Andreas May 16 '17 at 10:00
  • I don't have access to the php.ini for the prod env, what should i do ? – Tikroz May 16 '17 at 10:45

3 Answers3

0

Check upload_max_filesize variable in your php.ini file.

It might be set to 128M , try increasing it to the desired value.

Varun
  • 1
  • What if i don't have access to the file in the prod env ? – Tikroz May 16 '17 at 10:43
  • If your server allows PHP config changes through .htaccess, then you can create .htaccess file in the same folder as your php file and in that file write: php_value upload_max_filesize 256M php_value post_max_size 256M – Varun May 16 '17 at 12:31
0

Check post_max_size & upload_max_filesize. post_max_size must be greater than upload_max_filesize. Set upload_max_filesize as per your requirement.

Dipanwita Kundu
  • 1,637
  • 1
  • 9
  • 14
0

I think the problem exists in the line below:

$content = fread($fp, filesize($tmp_name));

Here you are trying to read the content of the file, at this point you will get out of memory when the filesize is large.

So, increasing memory limit is not a better solution in this case. It's better to stream the file content rather than keeping hole content in memory.

Remove the above mentioned line, also replace the following line:

$statement->bindParam(2, $content, PDO::PARAM_LOB, $taille);

with

$stmt->bindColumn(2, $fp, PDO::PARAM_LOB);

PDO::PARAM_LOB tells PDO to map the data as a stream

Dileep Kumar
  • 1,077
  • 9
  • 14