开发者

PHP MYSQL file contents escape problem

开发者 https://www.devze.com 2022-12-13 21:52 出处:网络
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 esca开发者_Python百科pe special characters, the

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 esca开发者_Python百科pe 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,


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.


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消