开发者

Wordpress nonce check always false

I'm having problems with a basic nonce validation via an ajax request.

Those are my script loader and css loader functions: (in 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');     

In my javascrtip file: (in gallery.js)

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

My ajax call will access a do_upload action from php. This one will append the received nonce field to the response... (back in 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;         
    }
}

The received result looks like this: c4817b947a {"success":false,"debugNonce":"c4817b947a"}

The first c4817b947a is because of the echo from the nonce generation function. It does not influence the way the validation happens.

My conclusion is that wp_verify_nonce always fails.

I am using wp 3.2.1 on localhost, fresh install, no plugins.


I've just ran into a similar issue and it turned out that all I had to do is to re-log as admin. I think it should also work in your case, because everything else in the provided code seems to be fine.

I guess it has something to do with how sessions are handled in Wordpress.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜