sanitize_post()
Очищає кожне поле зазначеного об’єкта/масиву посту.
Функція очищає дуже легко, наприклад, при типі очищення dbекрануючі слеші не ставляться.
Якщо тип очищення вказаний як raw, то очищення буде мінімальним: тільки деякі з числових полів будуть перетворені на число: ID, post_parent, menu_order, ancestors. Решта повернеться як передано.
post_content очищається від тегів при фільтрах editна displayоснові доступних тегів для прав поточного користувача.
При очищенні типом dbфункція не екранує символи.
sanitize_post_field()
(дуже швидко) | 50000 разів – 3.16 сек
(швидко)
Хуків немає.
Повертає
Объект|WP_Post|Массив. Очищений об’єкт/масив даних передано в $post .
Використання
sanitize_post($post, $context);
- $post
(об’єкт/WP_Post/масив) (обов’язковий) - Дані записи (поста), які потрібно очистити.
- $context
(рядок) Тип очищення даних. Можливо : _
raw– Для використання у рядку.edit– Для подальшого редагування.db– для використання у запиті.display– Виведення на екран.attribute– Для використання в атрибуті.
Типово: ‘display’
Приклади
#1 Приклад очищення
Допустимо ми отримуємо дані записи в запиті $_POST і перш ніж виводити кожне з них на екран, нам потрібно їх очистити. Це можна зробити окремо, але набагато швидше буде прогнати дані через цю функцію, так:
$post_data = $_POST['post_data']; $post_data = sanitize_post($post_data); // Або для використання у SQL запиті: $post_data = sanitize_post($post_data, 'db'); //результат не захищений від SQL ін'єкцій
#2 Очищення перед додаванням до БД
Приклад з функції wp_insert_post() , у прикладі я прибрав дуже багато коду, щоб показати лише суть очищення:
$postarr = $_POST['post_data']; // видаляємо дані про попереднє очищення unset($postarr['filter']]); // Очищаємо $postarr = sanitize_post($postarr, 'db'); // збираємо $data з параметрів $postarr ......... // Забираємо слеші, їх вставить $wpdb->insert $ data = wp_unslash ($ data); // вставляємо $wpdb->insert( $wpdb->posts, $data );
#3 Як чистяться дані:
// Нехай $_POST['post_data'] були такі дані:
$post_data = array(
'ID' => '6129',
'post_author' => '1',
'post_date' => '2015-09-03 01:36:12',
'post_content' => 'Контент " лапка. <fo> <foo>foo</foo> <script>щось</script> ',
'post_title' => 'wp_get_post_revision',
'post_status' => 'publish',
'comment_status' => 'open',
'post_name' => 'wp_get_post_revision',
'post_content_filtered' => '',
'post_parent' => '0',
'menu_order' => '0',
'post_type' => 'func',
'comment_count' => '0'
);
// виводимо
foreach( $post_data as $k => $v ){
echo "$k = (", gettype($v) ,") ". htmlspecialchars($v) ."n";
}
/* Отримуємо:
ID = (string) 6129
post_author = (string) 1
post_date = (string) 2015-09-03 01:36:12
post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script>
post_title=(string) wp_get_post_revision
post_status = (string) publish
comment_status = (string) open
post_name = (string) wp_get_post_revision
post_content_filtered = (string)
post_parent = (string) 0
menu_order = (string) 0
post_type = (string) func
comment_count = (string) 0
*/Тепер давайте подивимося, як виглядають дані після очищення, звертаємо увагу на типи:
$post_data = sanitize_post($post_data, 'raw'); // raw ---------------- /* ID = (integer) 6129 post_author = (string) 1 post_date = (string) 2015-09-03 01:36:12 post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script> post_title=(string) wp_get_post_revision post_status = (string) publish comment_status = (string) open post_name = (string) wp_get_post_revision post_content_filtered = (string) post_parent = (integer) 0 menu_order = (integer) 0 post_type = (string) func comment_count = (string) 0 filter = (string) raw */ $post_data = sanitize_post($post_data, 'edit'); // edit ---------------- /* ID = (string) 6129 post_author = (string) 1 post_date = (string) 2015-09-03 01:36:12 post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script> post_title=(string) wp_get_post_revision post_status = (string) publish comment_status = (string) open post_name = (string) wp_get_post_revision post_content_filtered = (string) post_parent = (string) 0 menu_order = (string) 0 post_type = (string) func comment_count = (string) 0 filter = (string) edit */ $post_data = sanitize_post($post_data, 'db'); // db ---------------- /* ID = (integer) 6129 post_author = (string) 1 post_date = (string) 2015-09-03 01:36:12 post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script> post_title=(string) wp_get_post_revision post_status = (string) publish comment_status = (string) open post_name = (string) wp_get_post_revision post_content_filtered = (string) post_parent = (integer) 0 menu_order = (integer) 0 post_type = (string) func comment_count = (string) 0 filter = (string) db */ $post_data = sanitize_post( $post_data, 'display'); // display ---------------- /* ID = (integer) 6129 post_author = (string) 1 post_date = (string) 2015-09-03 01:36:12 post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script> post_title=(string) wp_get_post_revision post_status = (string) publish comment_status = (string) open post_name = (string) wp_get_post_revision post_content_filtered = (string) post_parent = (integer) 0 menu_order = (integer) 0 post_type = (string) func comment_count = (string) 0 filter = (string) display */ $post_data = sanitize_post( $post_data, 'attribute'); // attribute ---------------- /* ID = (string) 6129 post_author = (string) 1 post_date = (string) 2015-09-03 01:36:12 post_content = (string) Контент " лапка. <br> <foo>foo</foo> <script>щось</script> post_title=(string) wp_get_post_revision post_status = (string) publish comment_status = (string) open post_name = (string) wp_get_post_revision post_content_filtered = (string) post_parent = (string) 0 menu_order = (string) 0 post_type = (string) func comment_count = (string) 0 filter = (string) js */
нотатки
- Дивіться: sanitize_post_field()
список змін
| З версії 2.3.0 | Введено. |