Question

I am attempting to upload a .pdf file into a mysql database using php.

It is all good except for the contents of the file. No matter how I seem try to escape special characters, the query always fails, mostly with "Unknown Command \n".

I have used addslashes, mysql_real_escape_string, removeslashes etc.

Does anyone have any ideas on how to escape file contents?

Many Thanks,

Was it helpful?

Solution

I've used the following sequence before, which seems to work nicely, and will store any data into the db, including images, pdfs, arrays of data, etc... :)

Storing the data (can be a string, array, object, etc.);

First, turn the data into a base64 encoded string

$strData = strtr(
             base64_encode(
               addslashes(
                 gzcompress( serialize($dataToStore) , 9)
                 )
               ) , '+/=', '-_,');

Then store that string data in the db...


Retrieving the data;

Extract the string data from the db

decode the data back to what you want (you may need to perform an extra step after this depending on the input data, array, image, etc.)

$returnData = unserialize(
                gzuncompress(
                  stripslashes(
                    base64_decode(
                      strtr($strDataFromDb, '-_,', '+/=')
                    )
                  )
                )
              );

This certainly helped me to store what I needed to store in a mySQL db!

OTHER TIPS

I don't see why you would want to store a file in a database, but I suggest you take a look at prepared statements.

Guess: You may be encountering errors due to the incompatibility between character sets. PDF is probably a binary file so you need to make sure that db column is set up to handle it that.

Beside the escaping problem you might run into "packet too large" errors if the (MySQL) system variable max_allowed_packet is set to a "small" value.
Using the mysqli extension, prepared statements and mysqli_stmt::send_long_data you can avoid both problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top