1

I have an automated PHP script which connects to an email box, reads emails and process them to create tickets. Some of these emails contain various types of file attachments. My script uses following code to save files directly to a postgress database. I'm using codeigniter.

public function saveFiles($filename, $fileurl, $jobid) {
     $filedata = array();
     $filedata['filename']= $filename;
     $filedata['filedescription'] = 'Incoming attachment.';
     $filedata['fileargid'] = $jobid;
     $filedata['fileaddedon'] = date('Y-m-d H:i:s P');
     $filedata['filedata'] = pg_escape_bytea(base64_encode(file_get_contents($fileurl)));

     $results = $this->db->insert('file', $filedata);
     if ($results)
         return $this->db->insert_id();
     else
         return FALSE;
}

However, most of the files are saved without any issue. My problem is some pdf files get corrupted when I deployed this script. Script saves files to local disk before encoding to base64. All these files are healthy as well. I suspect something is happening during pg_escape_bytea(base64_encode(file_get_contents($fileurl))).

I developed this script using php 5.5.9/Ubuntu on my local PC and non of the files get corrupted there. But the script is deployed on a Ubuntu server with php 5.3.10 and files get corrupted there.

I tried to find out what is causing this but no lock so far. Is this because of different php versions?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vajira Lasantha
  • 2,435
  • 3
  • 23
  • 39
  • The code you use to read the file from the DB would be interesting, too. And by any chance, could you provide us with a PDF that gets corrupted? Also, PHP 5.3 is end-of-life since 2014. Maybe an upgrade is the solution... – Kontrollfreak Mar 21 '16 at 22:56

1 Answers1

1

Looks either:

  1. you're encoding to database in the "escape" format and reading from it in hex-format.

  2. You need to cast "when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error." From pg_escape_bytea documentation, it also counts to unscape.

Check section 8.1 here

If isn't a problem I'd save bin2hex output to the field directly.

Muihlinn
  • 561
  • 6
  • 8
  • 1
    I passed a db connection to pg_escape_bytea funtion and it seems to be working fine now. $filedata['filedata'] = pg_escape_bytea($db, base64_encode(file_get_contents($fileurl))); Thanks for your answer. – Vajira Lasantha Apr 21 '16 at 23:40