PDO escape serialised string - php

Is it possible to escape a serialized string using PDO before it is inserted in the database?
I've built something where content from a WYSIWYG editor will be serialized. If someone pastes text from Word to the editor, and saves, I'll get the following error because multiple style tags where added:
unserialize(): Error at offset 105 of 1020
I've tried saying don't paste from Word haha, however I would like to build it so that it is possible even it's not the best way to do it.
I found the PDO function quote, but I'm not sure if that is what I'm looking for.
Besides that function, I couldn't find any other solutions. I'm already using PDO prepared statements.
I would like to know if it is possible. Thanks for the effort.

I believe it is related to encoding.
You should do base64_encode before save and base64_decode after it. As wrote here:
$toDatabse = base64_encode(serialize($data)); // Save to database
$fromDatabase = unserialize(base64_decode($data)); //Getting Save Format
Also, to avoid problems with encoding when you connect to database execute this SQL request:
"SET NAMES 'utf8'"

Related

PDO suspected of escaping characters of my Blob in MySql

Context
I store image in BLOBs columns in a MySql DB with PDO (yeah, this is needed).
I upload a base64_encoded .png from client's browser to a .php webservice through AJAX, and store it on my data base using base64_decode().
Later, I get it back on the client's browser. And upload it again, and so on until space-time continuum breaks.
Retrieving a valid BLOB (imported directly on phpMyAdmin, so 100% sure) from the database is fine, I can print it well on browser.
But storing it on MySql...
Issue
Setting looks like that :
$dbh = new PDO('mysql:host=localhost;dbname=Me', 'My', 'Myself');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("SET CHARACTER SET utf8"); //I tried playing with charset too
$query = $dbh->prepare("UPDATE i_like_underscores SET `my_blob`=:my_blob WHERE `it`=`:belongs");
$my_blob = base64_decode($_POST['my_blob']);
$query->bindParam(':my_blob', $my_blob, PDO::PARAM_LOB);
//The WHERE clause has really no importance here, so I don't even bind it
$query->execute();
It seems that PDO systematically removes some special characters of my blob during this process (but I can't diagnostic when exactly), cause when I later get my picture back (and encode it on base64), all the + and = are gone from my base64 string (while / stills) === corrupted.
I guess it automatically escapes when I bind it, but I can't tell as base64_decoded .png data is encoded in a unreadable weird charset.
I spent many hours on it, and tried :
Changing the encoding
PDO::quote() after base64_decode()
Putting various quotes on my SQL query
Prepared statements and direct PDO::query
Surfing the web for docs on all the PDO function I used
Finding similar cases, on StackOverflow too, no luck
To see how it's done in phpMyAdmin
Setting type PDO::PARAM_STR
Not thinking about quitting PDO just for that special case
Writing all my code backwards
And black magic
Without luck... Could someone give me a clue?
Thanks to davidstrachan, I've solved the removal of = using :
$dbh->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
Then, I came back to that problem later, just to see that the serialization of my form in jQuery was done wrong.
It escaped all the + as spaces (or %20) instead of %2B.

MYSQLi real escape function displaying new lines and carriage returns

i have a text area from which when i try to escape and sanitize through MYSQLi's real_escape function and nl2br and simply output is giving me odd results.
my php code:
<?php
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$postText = nl2br($db->escape_string($_POST['posting']));
?>
the odd output is :
i love this\r\n\r\nand this is gonna be funn.,
and strangely when i just use nl2br without real_escape is giving the output fine which obviously can't move ahead with as i cant trust user"s input.
Please help on this..
You should only apply SQL escaping when the output is going to be used in a SQL query.
If you need to output the value onto a page, you use htmlspecialchars() or htmlentities().
If it's going to be used in a JavaScript literal, use json_encode().
Etc.
In short, each context has their own escaping; don't mix them up.
Also, don't use nl2br() when you write it into the database; rather, apply it after you fetch it from the database.
Yes, it does.
This function's output is not intended to be printed out. But to format SQL string literals only.
Please note that this function is not intended to "sanitize" whatever input either. Please refer here for the details
So, you should never use these 2 functions together.
use escape_string to format SQL strings that you are going to place into query dynamically.
use nl2br only when printing your text onto HTML page
According to your question in the comments, there should be no case when you have to print your string back immediately.
Because after every POST request your PHP should response with Location: header to tell browser reload the page. Upon such reload you can read your data bask from database and print it out.

stripslashes issue in php

when i use stripslashes in php but i did not get the exact solution. I have menstion below which i used in my code those are
Example if i have the value in table like suresh\'s kuma\"r
i trying to display the value in the following three formats but no one is giving exact value
1) value=<?=stripslashes($row[1])?> //output is suresh's
2) value='<?=stripslashes($row[1])?>' //output is suresh
3) value="<?=stripslashes($row[1])?>" //output is suresh's kuma
But the exact output i need is suresh's kuma"r
let me know how to resolve the this issue?
The issue has nothing do to with stripslashes. If I guess correctly, the problem lies in the fact that in your examples quotes break the html field attribute;
I'll show you by manually echoing out your $row content as per your infos:
value=sures kumar --> leads to browser to interpret this as value="sures" kumar
value='suresh'khumar --> well, same story value='sures' khumar
value="Suresh"Khumar -->what can I say...you know the drill
Escaping the quotes won't affect html, since backslashes has no meaning in html.
Both value="Suresh" and value="Suresh\" will work fine for the browser, but your name will always be interpreted by the browser as some unknown attribute, leaving only the first part inside the value.
What you might do, instead, is apply htmlentities($row[1],ENT_QUOTES) so that they get converted in the equivalent entity (&quote;,for ex.) and not break your value attribute. See manual.
Another issue is that you shouldn't be having backslashes in your database in the first place; this might be due to the presence of magic_quotes enabled in your provider, or you passing manually addslashes() or other wrong trickery. If you want to insert into a database values containing quotes, use the escaping mechanism provided by your database driver (mysql_real_escape_string() in mysql, for ex.), or better tools (preparated statements with query bindings).
You should first get rid of all the slashes using that stripslashes and re-saving back the content; but slashes or not, the issue would appear again if you don't format that appropriately for your html, as I showed above.
Are you sure you want stripslashes instead of addslashes? Is the purpose is to quote the " characters?

Encoding problem when using htmlentities method

I've a problem of character encoding in php, so this's the php code:
n_event=$_GET['ndlann'];
$nom_complet=htmlentities(stripslashes($_POST['nom']));
$email_comment=htmlentities(stripslashes($_POST['email']));
$titre_comment=htmlentities(stripslashes($_POST['titre']));
$texte_comment=htmlentities(stripslashes(nl2br($_POST['commentaire'])));
$pays_comment=$_POST['pays'];
$date_ajout=date('Y/m/d');
Data will be added in a database table , you see that this data comes from a comments form,
so when the user enters some comments with orient languages carachters (arabic,hebrew...etc), the input data will change to something like :
Ø´Ù�را عÙ�Ù� اÙ�Ù�Ù�ضÙ�Ø
I tried to delete the htmlentities method and that works fine , but does start another problem of comments form security (js scripts will be executed)
What can I do with this situation?
and thanks
Do not use htmlentities() ever.
This function has been obsoleted long time ago.
Use htmlspecialchars() instead.
you have also bunch of nonsense in your code
doing htmlentities(nl2br(*)) has no sense.
make stripslashes conditional, only if magic quotes are set on.
there is a possible problem with pays field.
I am also afraid that you're taking htmlentities as some sort of SQL escaing function. Am I right?
In my opinion, and according to the PHP doc, the accepted answer is not correct.
Nowhere it is written that this function has been deprecated.
If you set correctly the third argument of the function, called $encoding, it will solve your problem.
I hope this helps.

PHP MYSQL file contents escape problem

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,
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.

Categories