PHP MYSQL file contents escape problem

喜欢而已 提交于 2019-12-07 19:44:39

问题


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,


回答1:


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!




回答2:


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.




回答3:


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:


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.



来源:https://stackoverflow.com/questions/1861967/php-mysql-file-contents-escape-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!