Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP]Uniwersalna funkcja do html decode
Forum PHP.pl > Forum > Przedszkole
trifek
Witam.
Mam tablice:

  1. (
  2. [save] => 1
  3. [title] => Monika Krzysiowa
  4. [contactUser] => Array
  5. (
  6. [0] => 29
  7. [1] => 11
  8. [2] => 17
  9. )
  10.  
  11. [email] => kontakt@mail.com
  12. [phone] => 12345678
  13. [description] => opis
  14. 1
  15. 2
  16. 3
  17. 4
  18. [enable] => 1
  19. )



lub



  1. (
  2. [save] => 1
  3. [title] => Monika Krzysiowa
  4. [email] => kontakt@gmail.com
  5. [phone] => 12345678
  6. [description] => opis
  7. 1
  8. 2
  9. 3
  10. 4
  11. [enable] => 1
  12. )



i taką funkcję w php:
  1. public function secureSave(array $string): array
  2. {
  3. foreach ($string as $key => $value) {
  4. $string[$key] = htmlspecialchars_decode($value, ENT_COMPAT);
  5. }
  6. return $string;
  7. }



Powyższa funkcja pracuje poprawnie dla 2 tablicy. W 1 mam problem i daje wynik:
  1. (
  2. [save] => 1
  3. [title] => Monika Krzysiowa
  4. [contactUser] =>
  5. [email] => kontakt@gmaail.com
  6. [phone] => 123456788
  7. [description] => opis
  8. 1
  9. 2
  10. 3
  11. 4
  12. [enable] => 1
  13. )


[contactUser] - problemem jest pusta wartość.

Jak naprawić powyższą funkcję tak żeby była uniwersalna?

Mam różne tablice, nazwy mogą być różne
nospor
W momemecie gdy wartoscia jest kolejna tablica, to musisz powtorzyc operacje. No i tak kolejna tablica moze miec znowu tablice itd itd - rekurencja sie tutaj klania

ps: no i najwazniejsze pytanie: po co ci w ogole to robic? Skad pochodza te dane i gdzie je potem zapisujesz?
trifek
Czyli coś takiego:

  1. $string[$key] = htmlspecialchars_decode($value, ENT_COMPAT); => $string[$key] = is_array($value) ? $this->secureSave($value) : htmlspecialchars_decode($value, ENT_COMPAT);

?smile.gif

Chcę kodować znaki wpisywane przez userów w formularzach przed zapisem do bazy (typu '. '', "" itp). Mam po drodze PDO i bindowanie, ale chcę dodatkowo to jeszcze dodać smile.gif
nospor
Napisz ten kod jeszcze raz bo nie ma prawa sie w ogole odpalic bo ma PARSE ERROR

Cytat
Chcę kodować znaki wpisywane przez userów w formularzach przed zapisem do bazy (typu '. '', "" itp). Mam po drodze PDO i bindowanie, ale chcę dodatkowo to jeszcze dodać

Totalnie bez sensu. Raz ze htmlspecialchars_decode nic nie koduje tylko DEKODUJE a dwa ze to bez sensu. takich rzeczy sie nie robi, tylko sobie zycie utrudniasz a nic nie zabezpieczasz
trifek

  1. public function secureSave(array $string): array
  2. {
  3. foreach ($string as $key => $value) {
  4. $string[$key] = is_array($value) ? $this->secureSave($value) : htmlspecialchars_decode($value, ENT_COMPAT);
  5. }
  6. return $string;
  7. }


Jako taka funkcja działa poprawnie smile.gif

W jaki sposób sugerujesz żeby kodować html przed zapisem do bazy?smile.gif
nospor
Cytat
W jaki sposób sugerujesz żeby kodować html przed zapisem do bazy
Zdaje sie juz napisalem: w zaden. To nie ma zadnego sensu co probujesz tutaj zrobic. Po co ci to? Co ci da to kodowanie? Nic, zupelnie nic. A tylko same problemy potem, chocby z ewentualnym wyszukiwaniem.

ps:

array $string
I na milosc pierszego zalozyciela php - nazywaj zmiennej jakos z glowa. Zmienna jest tablica a ty ja nazywasz string..... To tak jakbys zrobic zmienna:
$true = false;
$false = true;

W tym przypadku powinno byc np
array $data
trifek
Hmmmm.... tylko jak nie dodaję tego "zabezpieczenia" to taki wpis:

'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'



wywala mi błąd:

  1. Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2''' at line 1 in /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/utilities/DbClass.php:78 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/utilities/DbClass.php(78): PDOStatement->execute() #1 /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/utilities/DbClass.php(139): Core\Utilities\Db->Init('SELECT COUNT(ti...', NULL) #2 /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/models/ModelClass.php(24): Core\Utilities\Db->row('SELECT COUNT(ti...') #3 /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/backend/models/GalleryModel.php(230): Core\Models\Model->createSeoUrl(''';fwefewfpew'f...', 'title_pl', 'psGalleryCatego...') #4 /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/backend/controllers/GalleryList.php(14 in /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/utilities/DbClass.php on line 78




Moja klasa od połączeń wygląda tak:

  1. class Db
  2. {
  3. private $_hostname;
  4. private $_database;
  5. private $_username;
  6. private $_password;
  7. private $_port;
  8. private $_pdo;
  9. private $_sQuery;
  10. private $_bConnected = false;
  11. private $_parameters;
  12. private $_config;
  13. private $_psException;
  14.  
  15.  
  16. public function __construct()
  17. {
  18. $this->_config = Registry::register("Core\Utilities\Config");
  19. $this->_psException = new PsException();
  20.  
  21. $this->_hostname = $this->_config->db_host;
  22. $this->_database = $this->_config->db_db;
  23. $this->_username = $this->_config->db_user;
  24. $this->_password = $this->_config->db_pass;
  25. $this->_port = $this->_config->db_port;
  26.  
  27. $this->Connect($this->_hostname, $this->_database, $this->_username, $this->_password, $this->_port);
  28. $this->_parameters = array();
  29. }
  30.  
  31.  
  32. private function Connect($hostname, $database, $username, $password, $port)
  33. {
  34.  
  35. try {
  36. $options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'");
  37. $this->_pdo = new \PDO("mysql:host={$hostname};dbname={$database};port={$port};charset=utf8", $username, $password, $options);
  38.  
  39. $this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  40. $this->_pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
  41. $this->_pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
  42. $this->_pdo->query('SET NAMES utf8');
  43. $this->_bConnected = true;
  44. } catch (PDOException $ex) {
  45. $this->_psException->registerError("Failed to connect to the database: " . $ex->getMessage());
  46. } catch (Exception $e) {
  47. $this->_psException->registerError("Failed to connect to the database: " . $e->getCode() . "." . $e->getMessage());
  48. }
  49. }
  50.  
  51.  
  52. public function CloseConnection()
  53. {
  54. $this->_pdo = null;
  55. }
  56.  
  57.  
  58. private function Init($query, $parameters = "")
  59. {
  60. if (!$this->_bConnected) {
  61. $this->Connect();
  62. }
  63. try {
  64. $this->_sQuery = $this->_pdo->prepare($query);
  65.  
  66. $this->bindMore($parameters);
  67. if (!empty($this->_parameters)) {
  68. foreach ($this->_parameters as $param) {
  69. $parameters = explode("\x7F", $param);
  70. $this->_sQuery->bindParam($parameters[0], $parameters[1]);
  71. }
  72. }
  73. $this->success = $this->_sQuery->execute();
  74. } catch (PDOException $e) {
  75. $this->ExceptionLog($e->getMessage(), $query);
  76. }
  77. $this->_parameters = array();
  78. }
  79.  
  80.  
  81. public function bind($para, $value)
  82. {
  83. $this->_parameters[sizeof($this->_parameters)] = ":" . $para . "\x7F" . ($value);
  84. }
  85.  
  86. public function bindMore($parray)
  87. {
  88. if (empty($this->_parameters) && is_array($parray)) {
  89. $columns = array_keys($parray);
  90. foreach ($columns as $i => &$column) {
  91. $this->bind($column, $parray[$column]);
  92. }
  93. }
  94. }
  95.  
  96. public function query($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
  97. {
  98. $query = trim($query);
  99. $this->Init($query, $params);
  100. $rawStatement = explode(" ", $query);
  101.  
  102. $statement = strtolower($rawStatement[0]);
  103.  
  104. if ($statement === 'select' || $statement === 'show') {
  105. return $this->_sQuery->fetchAll($fetchmode);
  106. } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
  107. return $this->_sQuery->rowCount();
  108. } else {
  109. return null;
  110. }
  111. }
  112.  
  113. public function lastInsertId()
  114. {
  115. return $this->_pdo->lastInsertId();
  116. }
  117.  
  118.  
  119. public function column($query, $params = null)
  120. {
  121. $this->Init($query, $params);
  122. $Columns = $this->_sQuery->fetchAll(\PDO::FETCH_NUM);
  123.  
  124. $column = null;
  125. foreach ($Columns as $cells) {
  126. $column[] = $cells[0];
  127. }
  128. return $column;
  129.  
  130. }
  131.  
  132. public function row($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
  133. {
  134. $this->Init($query, $params);
  135. return $this->_sQuery->fetch($fetchmode);
  136. }
  137.  
  138. public function single($query, $params = null)
  139. {
  140. $this->Init($query, $params);
  141. return $this->_sQuery->fetchColumn();
  142. }
  143.  
  144. private function ExceptionLog($message, $sql = "")
  145. {
  146. $message .= 'Unhandled Exception. $message';
  147. if (!empty($sql)) {
  148. $message .= "\r\nQuery SQL : " . $sql;
  149. }
  150. $this->_psException->registerError($message);
  151. }
  152. }




Czyli błąd jest po stronie Db?
nospor
Jak dla mnie to ta cala twoja klasa jest do przepisania.

$this->_parameters[sizeof($this->_parameters)] = ":" . $para . "\x7F" . ($value);
co to niby ma byc/robic?

Zajrzyj do PDO, zobacz jak tam sie binduje rzeczy i nie kombinuj. Teraz wyglada na to ze ty nic nie bindujesz tylko bezposrednio wkladasz wartosci do zapytania, stad ten blad. Ale naprawde nie chce mi sie analizowac tej klasy ktora jest jednym wielkim WTF wink.gif
trifek
jak debuguję tutaj:
  1. $this->_sQuery = $this->_pdo->prepare($query);
  2. echo "<pre>";print_r($this->_sQuery);echo "</pre>";
  3.  



to mam zwrotkę:
  1. PDOStatement Object
  2. (
  3. [queryString] => SELECT COUNT(title_pl) AS count FROM psGalleryCategories WHERE title_pl = ''';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'';
  4. )



i tutaj jakby widzi za dużo '


Bindowanie mam w:foreachu this->_sQuery->bindParam($parameters[0], $parameters[1]); ;
nospor
Jak sam widzisz twoje zapytanie zawiera tekst ktory wkladasz do bazy a nie zadne bindowanie. Nic wiec dziwnego ze sie wywala.

Jak juz mowilem: klasa ta to sieczka jakas - sorki, jestem poprostu szczery

Pokaz jeszcze jak tej klasy uzywasz. Moze tez i tam robisz blad.
trifek
  1. $queryValue["enable"] = $dataValues['enable'];
  2. $queryValue["number"] = $dataValues['number'];
  3. $queryValue["description"] = $dataValues['description'];
  4. $queryValue["date"] = $dataValues['date'];
  5. $queryValue["visible_on_the_front"] = $dataValues['visible_on_the_front'];
  6. $queryValue["id_category_page"] = $dataValues['id_category_page'];
  7. $queryValue["visible_on_the_front2"] = $dataValues['visible_on_the_front2'];
  8. $this->_db->query("INSERT INTO psGalleryCategories (visible_on_the_front2, id_category_page, visible_on_the_front, date, description, enable, number) VALUES (:visible_on_the_front2, :id_category_page, :visible_on_the_front, :date, :description, :enable, :number);", $queryValue);
nospor
pokaz co zwraca:

  1. foreach ($this->_parameters as $param) {
  2. $parameters = explode("\x7F", $param);
  3. var_dump($parameters);
  4. $this->_sQuery->bindParam($parameters[0], $parameters[1]);
  5. }
trifek
  1. array(2) {
  2. [0]=>
  3. string(9) ":username"
  4. [1]=>
  5. string(17) "admindzLHFu@pl.pl"
  6. }
  7. array(2) {
  8. [0]=>
  9. string(5) ":enum"
  10. [1]=>
  11. string(1) "4"
  12. }
  13. array(2) {
  14. [0]=>
  15. string(9) ":category"
  16. [1]=>
  17. string(1) "1"
  18. }
  19. array(2) {
  20. [0]=>
  21. string(9) ":username"
  22. [1]=>
  23. string(17) "admindzLHFu@pl.pl"
  24. }
  25. array(2) {
  26. [0]=>
  27. string(5) ":enum"
  28. [1]=>
  29. string(1) "4"
  30. }
  31. array(2) {
  32. [0]=>
  33. string(9) ":category"
  34. [1]=>
  35. string(1) "1"
  36. }
  37. array(2) {
  38. [0]=>
  39. string(9) ":username"
  40. [1]=>
  41. string(17) "admindzLHFu@pl.pl"
  42. }
  43. array(2) {
  44. [0]=>
  45. string(5) ":enum"
  46. [1]=>
  47. string(1) "4"
  48. }
  49. array(2) {
  50. [0]=>
  51. string(9) ":category"
  52. [1]=>
  53. string(1) "1"
  54. }


print_r($this->_sQuery); zwraca

  1. $this->success = $this->_sQuery->execute(); and I have result: PDOStatement Object ( [queryString] => SELECT COUNT(title_pl) AS count FROM psGalleryCategories WHERE title_pl = ''';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2''; )




print_r($this->_sQuery);

  1. PDOStatement Object ( [queryString] => SELECT COUNT(title_pl) AS count FROM psGalleryCategories WHERE title_pl = ''';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2''; )




$this->_sQuery = $this->_pdo->prepare($query); echo "<pre>";print_r($this->_sQuery);echo "</pre>";


  1. PDOStatement Object ( [queryString] => SELECT COUNT(title_pl) AS count FROM psGalleryCategories WHERE title_pl = ''';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2''; )
nospor
Kurcze, jako przyklad podales mi zapytanie z INSERT, a kod printujacy wyswietla ci jakiegos SELECT. Prosze, skup sie i podaj mi przyklady i PRINTy z zapytania ktore sie wykrzaczaa a nie zupelnie innego. Dodatkowo print z params pokazuje ze nie ma tam zadnego tekstu wefewfpew'f'wef'wefew wiec znowu dzialasz na innym zapytaniu. Skup sie troche i nie marnuj swojego i mojego czasu
trifek
Przepraszam bardzo.
  1. array(2) {
  2. [0]=>
  3. string(9) ":username"
  4. [1]=>
  5. string(17) "admindzLHFu@pl.pl"
  6. }
  7. array(2) {
  8. [0]=>
  9. string(5) ":enum"
  10. [1]=>
  11. string(1) "4"
  12. }
  13. array(2) {
  14. [0]=>
  15. string(9) ":category"
  16. [1]=>
  17. string(1) "1"
  18. }
  19. array(2) {
  20. [0]=>
  21. string(9) ":username"
  22. [1]=>
  23. string(17) "admindzLHFu@pl.pl"
  24. }
  25. array(2) {
  26. [0]=>
  27. string(5) ":enum"
  28. [1]=>
  29. string(1) "4"
  30. }
  31. array(2) {
  32. [0]=>
  33. string(9) ":category"
  34. [1]=>
  35. string(1) "1"
  36. }
  37. array(2) {
  38. [0]=>
  39. string(9) ":username"
  40. [1]=>
  41. string(17) "admindzLHFu@pl.pl"
  42. }
  43. array(2) {
  44. [0]=>
  45. string(5) ":enum"
  46. [1]=>
  47. string(1) "4"
  48. }
  49. array(2) {
  50. [0]=>
  51. string(9) ":category"
  52. [1]=>
  53. string(1) "1"
  54. }
  55. array(2) {
  56. [0]=>
  57. string(7) ":enable"
  58. [1]=>
  59. string(1) "1"
  60. }
  61. array(2) {
  62. [0]=>
  63. string(7) ":number"
  64. [1]=>
  65. string(0) ""
  66. }
  67. array(2) {
  68. [0]=>
  69. string(12) ":description"
  70. [1]=>
  71. string(54) "'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'"
  72. }
  73. array(2) {
  74. [0]=>
  75. string(21) ":visible_on_the_front"
  76. [1]=>
  77. string(0) ""
  78. }
  79. array(2) {
  80. [0]=>
  81. string(5) ":date"
  82. [1]=>
  83. string(10) "2019-02-27"
  84. }
  85. array(2) {
  86. [0]=>
  87. string(17) ":id_category_page"
  88. [1]=>
  89. string(2) "67"
  90. }
  91. array(2) {
  92. [0]=>
  93. string(22) ":visible_on_the_front2"
  94. [1]=>
  95. string(0) ""
  96. }
  97. array(2) {
  98. [0]=>
  99. string(9) ":title_pl"
  100. [1]=>
  101. string(54) "'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'"
  102. }
  103. array(2) {
  104. [0]=>
  105. string(15) ":description_pl"
  106. [1]=>
  107. string(54) "'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'"
  108. }
  109. array(2) {
  110. [0]=>
  111. string(12) ":keywords_pl"
  112. [1]=>
  113. string(54) "'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^@^7ef125e2'"
  114. }
  115.  
  116.  
  117. Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') VALUES ('', '67', '', '2019-02-27', '\'\';fwefewfpew\'f\'wef\'wefew.\'\'fewvds' at line 1 in /Applications/XAMPP/xamppfiles/htdocs/um_rumia/apps/core/utilities/DbClass.php:79
  118. Stack trace:
  119. #0 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(79): PDOStatement->execute()
  120. #1 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(105): Core\Utilities\Db->Init('INSERT INTO psG...', Array)
  121. #2 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/models/GalleryModel.php(234): Core\Utilities\Db->query('INSERT INTO psG...', Array)
  122. #3 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/controllers/GalleryList.php(149): Backend\Models\GalleryModel->saveDataFromForm(Array, 3)
  123. #4 [internal function]: Backend\Controllers\GalleryListAdminContro in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php on line 79

nospor
No i poprosze jeszcze jak to wywolujesz z tym zapytaniem SELECT. O wszystko po kolei musze sie dopraszac?
trifek
Selecty tak wywołuję:


  1. public function getNumberOfItems(string $searchValue = ""): int {
  2. $searchQuery = null;
  3. if ($searchValue != "") {
  4. $searchQuery .= " and ($searchNames or $searchNames2 or $searchNames3) ";
  5. $queryValue["search"] = "%$searchValue%";
  6. }
  7.  
  8. return $this->_db->single("SELECT COUNT(id_categories_of_photos) AS id_categories_of_photos FROM psGalleryCategories WHERE enable = 1 $searchQuery;", $queryValue);
  9. }
nospor
$searchQuery .= " and ($searchNames or $searchNames2 or $searchNames3) ";
Tutaj wkladasz wartosci bezposrednio do zapytania i ich nie bindujesz. Nie wspominaj juz o tym ze tych zmienne w ogole nie istnieja wiec znowu pokazales jakis wycinek kodu
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.