PHP MYSQL file contents escape problem

2019-05-21 14:44发布

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,

4条回答
我命由我不由天
2楼-- · 2019-05-21 15:10

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!

查看更多
该账号已被封号
3楼-- · 2019-05-21 15:19

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.

查看更多
迷人小祖宗
4楼-- · 2019-05-21 15:21

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.

查看更多
够拽才男人
5楼-- · 2019-05-21 15:30

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.

查看更多
登录 后发表回答