0

Lately I was challenged to implement functionality that would allow users, editing specific custom post, to download json file based on meta of that post. I finally managed to complete the task (well, in some sense at least), but what now concerns me the most is the security of my solution.

Here goes the code (it's a plugin with three files inside its dir):

functions.php

// Main plugin file. This is where I output button for custom post type edit page 
/*...*/
    <button data-postid="<?php echo $post->ID; ?>" data-fileurl="<?php echo plugins_url('download_json.php',__FILE__); ?>" class="button-secondary" id="mycp-download-json" >Download JSON</button>
/*...*/

script.js

jQuery(document).ready(function(){
    var $btn = jQuery('#mycp-download-json');
    $btn.on('click', function(e){
        e.preventDefault();
        window.location = jQuery(this).data('fileurl') + '?postid=' + jQuery(this).data('postid');
    });
});

download_json.php

<?php
require(dirname(dirname(dirname(__DIR__))) . '/wp-load.php');
$postid = (int)($_GET['postid']);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= file.json");
header("Content-Transfer-Encoding: binary");    
$fields  = get_post_meta($postid,'', true);
echo json_encode($fields,  JSON_HEX_APOS);

And here are my questions:

  • Would simple current_user_can() check be sufficient to prevent unauthorized downloading (by typing the url for example)?
  • In general, is it valid to implement such generate-download functionality this way? Is it necessary to create separate file for handling download request (download_json.php in this case)?
  • Are there other security issues that arise when I am including only wp-load (and not whole wp-blog-header)?

1 Answer 1

1

Plugins that load the WordPress environment this way get rejected from the repository, as they are prone to failure in non-standard configurations.

For something like this I would use the admin-post-$action to receive requests. The WordPress API will be available where you can check if users are authorized to perform specific actions.

1
  • Indeed it solves most of the problems. It's easier to implement, encapsulate in class and so on. Thank you for your answer.
    – Max
    Commented Aug 30, 2015 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.