Guesser
Guesser

Reputation: 1857

New line in serialised array PHP

When taking data from a HTML form and storing a value in a serialised array if there is a new line the serialisation is going wrong with mysql_real_escape_string.

for example this outputs a string of the wrong length also plus the new line has been removed

$value="new\r\nline";

mysql_real_escape_string($value);


$array=array();
$array[0]=$value;

$array=serialize($array);

echo $array;

prints out a:1:{i:0;s:9:"new line";}

Upvotes: 1

Views: 4032

Answers (3)

ontananza
ontananza

Reputation: 392

As advice, you could encode in base 64 the serialized result from HTML form before serialize to avoid errors and make it safe.

$encodedValue=base64_encode($value);

$array=array();
$array[0]=$encodedValue;

$array=serialize($array);

echo $array;

To decode youre stored value just do the reverse process

$array=unserialize($array);
$value=base64_decode($array[0]);
echo $value;

And the HMTL Form value remains intact. By the way encoding in base 64, make it safe to store the value in the BD but 33% greater.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270775

If you're viewing this in a browser, the newline is just being stripped away. View the page source, or wrap it in <pre> tags:

echo "<pre>$array</pre>";

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96326

mysql_real_escape_string returns the escaped value.. you don't use the returned value, so why are you complaining about it?

also, if you check the output in the browser, you won't see the newline. check the generated source.

Upvotes: 1

Related Questions