4

我在通过 ajax 请求进行基本随机数验证时遇到问题。

这些是我的脚本加载器和 css 加载器函数:(在 gallery.php 中)

function gallery_js_loader()
{
    if (!is_admin()) return;
    // async flash uploader
    wp_enqueue_script('swfobject', THEMEURL . "/lib/uploadify/swfobject.js", array(), false, true);
    wp_enqueue_script('uploadify', THEMEURL . "/lib/uploadify/jquery.uploadify.v2.1.4.min.js", array('jquery'), false, true);
    wp_enqueue_script('gallery_admin_scripts', THEMEURL . "/inc/galleries/gallery_admin_scripts.js", array(), false, true);
    wp_localize_script('gallery_admin_scripts', 'param',
                   array(
                        'basename' => GALLERYPOST,
                        'baselocation' => THEMEURL,
                        'nonce' => wp_create_nonce('file-upload-nonce'),
                        'thumb_width' => intval(get_option('thumbnail_size_w')),
                        'thumb_height' => intval(get_option('thumbnail_size_h'))
                   ));
// main styles


}

function gallery_css_loader()
{
    wp_enqueue_style('uploadify_styles', THEMEURL . "/lib/uploadify/uploadify.css");
    wp_enqueue_style('gallery_admin_styles', THEMEURL . "/inc/galleries/gallery_admin_styles.css");
}

 add_action('admin_print_scripts-post.php', 'gallery_js_loader');
 add_action('admin_print_scripts-post-new.php', 'gallery_js_loader');
 add_action('admin_print_styles-post.php', 'gallery_css_loader');
 add_action('admin_print_styles-post-new.php', 'gallery_css_loader');


 function gallery_upload_image()
 {
     $nonce = $_POST["nonce"];

     if (is_admin() && !empty($_FILES) /*&& wp_verify_nonce($nonce, 'file-upload-nonce')*/) {
         require_once(ABSPATH . 'wp-admin/includes/image.php');

         $tempFile = $_FILES['Filedata']['tmp_name'];
         //        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
         $targetDir = wp_upload_dir(date('Y'));
         $targetFile = $targetDir['path'] . '/' . $_FILES['Filedata']['name'];
         $targetFile = str_replace(" ", "", $targetFile);

         move_uploaded_file($tempFile, $targetFile);

         $wp_filetype = wp_check_filetype(basename($targetFile), null);

         $attachment = array(
             'post_mime_type' => $wp_filetype['type'],
             'post_title' => preg_replace('/\.[^.]+$/', '', basename($targetFile)),
             'post_content' => '',
             'post_status' => 'inherit'
         );
         $result['attachmet_id'] = $attach_id = wp_insert_attachment($attachment, $targetFile);
         $result['recieved_nonce'] = $nonce;

         $attach_data = wp_generate_attachment_metadata($attach_id, $targetFile);
         wp_update_attachment_metadata($attach_id, $attach_data);

         $result['success'] = true;
     } else {
         $result['success'] = false;
         $result['recieved_nounce'] = $nonce;
         $result['error'] = array(
             'message' => 'No files or you are not admin ' . $nonce,
             'code' => 'E01'
         );
     }

     echo json_encode($result);
     exit;
 }

 add_action('wp_ajax_do_upload', 'gallery_upload_image');     

在我的 javascrtip 文件中:(在 gallery.js 中)

console.debug("Nonce received ",param.nonce); //c4817b947a 

我的 ajax 调用将从 php 访问 do_upload 操作。这会将接收到的 nonce 字段附加到响应中...(返回到 gallery.php)

function gallery_upload_image()
{
    $nonce = $_POST["nonce"];

    if ( wp_verify_nonce($nonce, 'file-upload-nonce')) {
        /* some logic here, nothing to do with nonce */
        $result['success'] = true;
        $result['debugNonce'] = $nonce;
    } // end validation
    else {
       //invalid nonce
       $result['success'] = false;
       $result['debugNonce'] = $nonce;         
    }
}

收到的结果如下所示: c4817b947a {"success":false,"debugNonce":"c4817b947a"}

第一个 c4817b947a 是因为来自 nonce 生成函数的回声。它不会影响验证发生的方式。

我的结论是 wp_verify_nonce 总是失败。

我在本地主机上使用 wp 3.2.1,全新安装,没有插件。

4

2 回答 2

2

我刚刚遇到了类似的问题,结果我所要做的就是以管理员身份重新登录。我认为它也应该适用于您的情况,因为提供的代码中的其他所有内容似乎都很好。

我想这与 Wordpress 中会话的处理方式有关。

于 2016-10-07T22:57:53.673 回答
0

I do an almost identical interchange without problems. This is in a plugin (class), but that shouldn't matter.

PHP - initialize the javascript :

add_action( 'wp_print_scripts', array( &$this, 'enqueue_script') );

PHP - function enqueue_script:

wp_localize_script( 'B99-Portfolio', 'ajax', array(  'ajaxurl'       => admin_url( 'admin-ajax.php' ),
                                                     'imgurl'        => content_url().'/uploads/portfolio-content/',
                                                     'requestNonce'  => wp_create_nonce('b99-request-nonce')) );

JS - initiate the ajax request:

$.ajax({
        type    : 'POST',
        cache   : false,
        url     : ajax.ajaxurl,
        data    : {
            action          : 'b99_ajax_request_items',
            requestNonce    : ajax.requestNonce             
        },
        dataType: 'json',
        error   : function(jqXHR, textStatus, errorThrown) {alert(jqXHR+" "+textStatus+" "+errorThrown);},
        success : function( response ) {recieveAjax( response );}
        });

PHP - recieve and handle the request ( function b99_ajax_request_items):

$nonce = $_POST['requestNonce'];
        if ( ! wp_verify_nonce( $nonce, 'b99-request-nonce' ) ){
            die ( 'security fail'.$nonce);
        }

Make sure that you have enqueued the script prior to localizing it.

I'm using current versions of both jquery and wordpress and this works seamlessly on a local install of XAMPP. It looks pretty similar to your interchange, but maybe this is something to compare against.

于 2011-09-10T23:07:16.353 回答