2013-03-18 2 views
0

투표 시스템과 사이트를 생성하는 코드를 만들었습니다. 내 functions.phpfunctions.php의 투표 시스템

<?php 

function add_rating_script() { 
    wp_enqueue_script('rating', get_stylesheet_directory_uri() . '/js/rating.js', array('jquery'), '', true); 
    wp_localize_script('rating', 'ajax_var', array('url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ajax-nonce'))); 
} 

function update_rating() { 

    // Check for nonce security 
    $nonce = $_POST['nonce']; 

    if (!wp_verify_nonce($nonce, 'ajax-nonce')) 
     die('Busted!'); 

    if (isset($_POST['post_rating'])) { 
     // Retrieve user IP address 
     $ip = $_SERVER['REMOTE_ADDR']; 
     $post_id = $_POST['post_id']; 

     // Get voters'IPs for the current post 
     $meta_IP = get_post_meta($post_id, "voted_IP"); 
     $voted_IP = $meta_IP[0]; 

     if (!is_array($voted_IP)) 
      $voted_IP = array(); 

     // Get votes count for the current post 
     $meta_count_up = get_post_meta($post_id, "votes_up", true); 
     $meta_count_down = get_post_meta($post_id, "votes_down", true); 

     // Use has already voted ? 
     if (!hasAlreadyVoted($post_id)) { 
      $voted_IP[$ip] = time(); 
      if ($_POST['post_rating'] == 'up') { 

       // Save IP and increase votes count 
       update_post_meta($post_id, "voted_IP", $voted_IP); 
       update_post_meta($post_id, "votes_up", ++$meta_count_up); 

       echo '<p class=\'message\'>Esse artigo já ajudou <span class=\'count\'>' . $meta_count_up . '</span> pessoas </p>'; 
      }elseif($_POST['post_rating'] == 'down'){ 
       update_post_meta($post_id, "voted_IP", $voted_IP); 
       update_post_meta($post_id, "votes_down", ++$meta_count_down); 

       echo '<p class=\'message\'>Obrigado pelo seu voto.</p>'; 
      } 

     } 
     else 
       echo '<p class=\'message\'>Você já enviou o seu voto.</p>'; 
    } 
    exit; 
    } 

    function hasAlreadyVoted($post_id) { 
    $timebeforerevote = 120; 

    $meta_IP = get_post_meta($post_id, "voted_IP"); 
    $voted_IP = $meta_IP[0]; 
    if (!is_array($voted_IP)) 
     $voted_IP = array(); 
    $ip = $_SERVER['REMOTE_ADDR']; 

    if (in_array($ip, array_keys($voted_IP))) { 
     $time = $voted_IP[$ip]; 
     $now = time(); 

     if (round(($now - $time)/60) > $timebeforerevote) 
      return false; 

     return true; 
    } 

    return false; 
} 

wp_localize_script('rating', 'ajax_var', array(
    'url' => admin_url('admin-ajax.php'), 
    'nonce' => wp_create_nonce('ajax-nonce') 
)); 

add_action('wp_enqueue_scripts', 'add_rating_script'); 
add_action('wp_ajax_post_id', 'update_rating'); 
add_action('wp_ajax_nopriv_post_id', 'update_rating'); 

을 문제에

jQuery(document).ready(function() { 

jQuery("a#up").click(function() { 
    jQuery('.rating').html(''); 
    jQuery('#loading').show(); 

    post_id = jQuery(this).data("post_id"); 

    jQuery.ajax({ 
     type: "post", 
     url: ajax_var.url, 
     data: "action=post_id&nonce=" + ajax_var.nonce + "&post_rating=up&post_id=" + post_id, 
     success: function(data) { 
      jQuery('#loading').hide(); 

      jQuery('.rating').html(data); 

     } 
    }); 

    return false; 
}); 

jQuery("a#down").click(function() { 

    post_id = jQuery(this).data("post_id"); 

    jQuery.ajax({ 
     type: "post", 
     url: ajax_var.url, 
     data: "action=post_id&nonce=" + ajax_var.nonce + "&post_rating=down&post_id=" + post_id, 
     success: function(data) { 
      jQuery('.rating').html(data); 

     } 
    }); 

    return false; 
}); 

}); 

그리고 다음과 같은 PHP 코드 :

exemple

내가 다음 코드 JavaScipt을했다 : 아래 그림과 같이 그의 모습은 동일한 기사에서 사용자가 여러 번 투표하지 못하도록하는 것입니다. IP를 저장하고 비교를 수행합니다. 그러나 시간이 지남에 따라 테이블 Word를 떠날 것입니다. 누르는 것은 위탁되고 매우 천천히. 누구든지이 코드를 최적화하는 것에 대해 알고 있습니까?

답변

0

최적화를위한 트릭 중 하나는 투표 후에 쿠키를 설정하고이를 방어의 첫 번째 줄로 생각하는 것입니다. 이렇게하면 많은 유스 케이스에서 데이터베이스에 대한 콜을 막을 수 있습니다. 쿠키가 설정되지 않은 경우 테이블에서 IP 주소를 확인한 다음에 만 이미 투표했는지 확인하십시오.

사용자가 브라우저를 전환하고 쿠키를 지울 수 있기 때문에 쿠키 전용 접근 방식이 작동하지 않는 것은 분명합니다. 사용자가 현재와 마찬가지로 자신의 IP를 조회합니다 (단, 여전히 방법이있을 수 있음). 인터넷 연결/IP 주소를 공유하는 경우 (예 : 동일한 Starbucks Wifi 연결로 투표) 합법적 인 사용자가 투표하지 못하게 할 수 있습니다.

최소한 쿠키를 먼저 확인하여 잠재적으로 불필요한 많은 데이터베이스 트랜잭션을 사전에 예방할 수 있습니다.

+0

예 실제로 좋은 생각입니다! 많은 보안이 필요한 것은 아닙니다. 버튼을 반복해서 누르지 못하게하고 싶습니다. 캐시를 지울 때까지 중지하면 이미 충분합니다. – Renato