code_junkie

What is the best way to escape Python strings in PHP?

Nov 11th, 2011
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. subject_prefix = 'This String From User Input'
  2. msg_footer = """This one too."""
  3.  
  4. echo "subject_prefix = '".$subject_prefix."'n";
  5.  
  6. <?php
  7.  
  8. function py_escape($input) {
  9. $descriptorspec = array(
  10. 0 => array("pipe", "r"),
  11. 1 => array("pipe", "w")
  12. );
  13. $process = proc_open(
  14. "python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'",
  15. $descriptorspec, $pipes);
  16. fwrite($pipes[0], $input);
  17. fclose($pipes[0]);
  18. $chunk_size = 8192;
  19. $escaped = fread($pipes[1], $chunk_size);
  20. if (strlen($escaped) == $chunk_size) {
  21. // This is important for security.
  22. die("That string's too big.n");
  23. }
  24. proc_close($process);
  25. return $escaped;
  26. }
  27.  
  28. // Example usage:
  29. $x = "string rfull noft crappy stuff";
  30. print py_escape($x);
  31.  
  32. function python_string_escape( $string )
  33. {
  34. $string = preg_replace( "/\\/", "\\", $string ); # \ (first to avoid string re-escaping)
  35. $string = preg_replace( "/n/", "\n", $string ); # n
  36. $string = preg_replace( "/r/", "\r", $string ); # r
  37. $string = preg_replace( "/t/", "\t", $string ); # t
  38. $string = preg_replace( "/"/", "\"", $string ); # "
  39. $string = preg_replace(
  40. "/([x{00}-x{1F}]|[x{7F}-x{FFFF}])/ue",
  41. "sprintf("\u%04X",uniord("$1"))",
  42. $string );
  43. return $string;
  44. }
  45.  
  46. function uniord($c) {
  47. $h = ord($c{0});
  48. if ($h <= 0x7F) {
  49. return $h;
  50. } else if ($h < 0xC2) {
  51. return false;
  52. } else if ($h <= 0xDF) {
  53. return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
  54. } else if ($h <= 0xEF) {
  55. return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
  56. | (ord($c{2}) & 0x3F);
  57. } else if ($h <= 0xF4) {
  58. return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
  59. | (ord($c{2}) & 0x3F) << 6
  60. | (ord($c{3}) & 0x3F);
  61. } else {
  62. return false;
  63. }
  64. }
  65.  
  66. function escape_string($text, $type) {
  67. // Escape backslashes for all types of strings?
  68. $text = str_replace('\', '\\', $text);
  69.  
  70. switch($type) {
  71. case 'single':
  72. $text = str_replace("'", "\'", $text);
  73. break;
  74. case 'double':
  75. $text = str_replace('"', '\"', $text);
  76. break;
  77. // etc...
  78. }
  79.  
  80. return $text;
  81. }
Add Comment
Please, Sign In to add comment