0
如何在WordPress中使用ajax和update_post_meta()更新post_meta時防止注入?我擔心用戶在我的網站上輸入的內容會讓我很容易受到注入以及其他令我無法想象的討厭的東西的影響。如何在WordPress中使用ajax和update_post_meta()更新post_meta時防止注入?
我是WordPress開發和網站開發新手。
我正在構建一個系統,用戶可以登錄並更新有關其業務的各種信息,然後將其保存到MySQL數據庫(將來我將使用客戶端應用程序的WordPress REST API獲取這些數據)。所以我建立了配置文件頁面併爲用戶輸入表單,然後使用ajax和WordPress的update_post_meta()函數發送數據。這是我的阿賈克斯回調:
/**
* AJAX Callback
* Always Echos and Exits
*/
function lla_update_profil_meta_callback() {
// Ensure we have the data we need to continue
if(! isset($_POST) || empty($_POST) || ! is_user_logged_in()) {
// If we don't - return custom error message and exit
header('HTTP/1.1 400 Empty POST Values');
echo 'Could Not Verify POST Values.';
exit;
}
// Get our current post ID
$post_id = lla_get_post_id();
if($post_id != null){
//get all the values from $_POST
$um_val = sanitize_text_field($_POST['kategori_id']) ;
$selected_term_data = get_term((int)$um_val);
$new_post_title = sanitize_text_field($_POST['post_title']);
//these are the values and im guessing it should be here i protect against injection?
$new_beskrivelse = $_POST['beskrivelse'];
$new_telefon = $_POST['telefon'];
$new_email = $_POST['email'];
$new_website = $_POST['website'];
$new_vejnavn = $_POST['vejnavn'];
$new_husnummer = $_POST['husnummer'];
$new_salside = $_POST['salside'];
$new_postnummer = $_POST['postnummer'];
$new_by = $_POST['by'];
update_post_meta($post_id, 'kategori_id', $um_val);
update_post_meta($post_id, 'beskrivelse', $new_beskrivelse);
update_post_meta($post_id, 'telefon', $new_telefon);
update_post_meta($post_id, 'email', $new_email);
update_post_meta($post_id, 'website', $new_website);
update_post_meta($post_id, 'vejnavn', $new_vejnavn);
update_post_meta($post_id, 'husnummer', $new_husnummer);
update_post_meta($post_id, 'salside', $new_salside);
update_post_meta($post_id, 'postnummer', $new_postnummer);
update_post_meta($post_id, 'by', $new_by);
//make sure the category chosen is updated in the backend aswell
wp_set_object_terms($post_id, (int)$um_val, $selected_term_data->taxonomy, false);
//updating post-title
$my_post = array(
'ID' => $post_id,
'post_title' => $new_post_title,
'post_name' => $new_post_title,
);
wp_update_post($my_post);
}else{
echo "no post";
}
exit;
}
add_action('wp_ajax_nopriv_um_cb', 'lla_update_profil_meta_callback');
add_action('wp_ajax_um_cb', 'lla_update_profil_meta_callback');
我該如何使這更安全?
您可以使用函數'htmlspecialchars'參考 - http://php.net/manual/en/ function.htmlspecialchars.php。例子'$ new_beskrivelse = htmlspecialchars(!empty($ _ POST ['beskrivelse'])?$ _POST ['beskrivelse']:'')' – htmlbrewery