0

I really have the reason to reserve this function. I used to saved BINARY content to file, which was run by this function, so the content is something like

WA\0,\0\0\0\0\0\0„Cźw\\\0\0\0\0\0\0\0\0\0\0\0Q\0\0\0

so somehow I must reverse this function. I tried the stripslashes() function, now it looks better:

WA ,      „Cźw\           Q   

still corrupt. I even tried this one:

$search = array( "\0", "\n", "\r", "\\", "\'", "\\", "\Z" );
$replace = array( "\x00", "\n", "\r", "\"", "'", "\", \x1a" );
$a = str_replace($search, $replace, $a);

still no joy. How to restore the original binary data?

4
  • 2
    Why would you perform a string escape function on binary data in the first place? Commented Jun 28, 2015 at 0:32
  • it was done by my fault. Data used to go to database, so it was all good, but we changed our mind and put data to disk. Sadly, we left the escaping accidentally, so data became corrupt.... SO I dont want it! Commented Jun 28, 2015 at 0:34
  • 1
    This might help: stackoverflow.com/a/10845827/4311336 Commented Jun 28, 2015 at 0:42
  • 1
    The manual for mysql_real_escape_string lists exactly seven characters, that the function prepends with a backslash. So write a function that removes a backslash before any of those seven characters, and nothing else. Commented Jun 28, 2015 at 0:45

1 Answer 1

1

The trick is in properly escaping the sequences you want to replace. The following function should work.

function un_mysql_real_escape_string( $data ) {
    return str_replace(
        array( '\0'  , '\n', '\r', '\Z'  , '\"', '\\\'', '\\\\' ),
        array( "\x00", "\n", "\r", "\x1a", '"' , '\''  , '\\'   ),
        $data
    );
}

Unit test for my unescape function.

$data = '';
foreach ( range(0, 255) as $dec ) {
    $data .= chr( $dec );
}

$data_escaped = mysql_real_escape_string( $data );
var_dump( un_mysql_real_escape_string( $data_escaped ) === $data );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.