WordPress nonce - wordpress

Hi I'm trying to get into Wordpress Ajax Requests right now. Now I have finished a script that works perfectly. But since I'm not a security professional, I'd like to ask you if you can help me.
I would also like to know if I have to use a form every time or if I can start a request directly via jQuery Ajax. If so, how do I do that with dynamic requests where I can not set the nonce before? e.g. in a list where each entry has multiple buttons?
Many Thanks!
template-form.php
<form method="post" id="form">
<input type="text" name="form_name" />
<?php wp_nonce_field( 'form_action', 'form_nonce' ); ?>
<input type="submit" id="submit" value="save">
</form>
script.js
jQuery("#submit").click(function (e) {
e.preventDefault();
jQuery.post(ajaxurl + "/ajax.php", jQuery("#form").serialize()).done(function (data) {
alert(data);
});
return false;
});
ajax.php
<?php
define( 'WP_USE_THEMES', false );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
if( isset( $_POST['form_nonce'] ) && wp_verify_nonce( $_POST['form_nonce'], 'form_action') ) {
$form_name = sanitize_text_field($_POST['form_name']);
echo "is working";
}else{
echo "not working";
wp_die();
}
?>

I would also like to know if I have to use a form every time or if I
can start a request directly via jQuery Ajax. If so, how do I do that
with dynamic requests where I can not set the nonce before? e.g. in a
list where each entry has multiple buttons?
No you could also use wp_nonce_url to make ajax calls.
But as far as I know, I will not work if you have a multisite installation and send an ajax call from one blog of the network to another blog.
Apart from that, you code looks ok to me and you are also saying that it is working.
Therefore I am confused where exactly you need help.
Could you clarify your question, please?

Related

get_current_user_id() returning Zero 0

get_current_user_id() is returning 0 for following codes. I do tried some solution available on stack overflow but somehow not working for me. I'm expecting explanation why its returning zero and how to fix?
P.S: I'm calling get_current_user_id() from external php page and included '../wp-blog-header.php' for that.
Code:
<?php
require('../wp-blog-header.php');
get_header();
$user_ID = get_current_user_id();
echo $user_ID;
?>
You have to call wordpress proccess of user authentication. Try adding the following code before get_current_user_id();, if it doesn't solve your problem it'll at least point you the right direction:
$user_id = apply_filters( 'determine_current_user', false );
wp_set_current_user( $user_id );
Hope it helps!
This is likely a result of including wp-blog-header.php directly in your external file. From the Codex on get_current_user_id():
The user's ID, if there is a current user; otherwise 0.
I'm not sure what you're trying to do, but the correct method would be to add this logic to functions.php under the correct action hook, or by writing a custom plugin. By doing one of those two things, you will have access to the authenticated user.
if you are using ajax then may be in some browser versions we can't get id by get_current_user_id() for this we can use xhrFields in over ajax then it will work fine. if the problem with the browser version.
jQuery.ajax({
type: "POST",
xhrFields: {
withCredentials: true
},
cache: false,

need the right way to setcookie in wordpress

i've been looking the whole day how to setcookies in wordpress. in my way i found out (using the developer toolbar) that the cookie is set but still not working.
i have 2 files the first contains the login form redirecting to another page to set the cookie and return to another page to check if it's working. domain which is tested on is like this : blog.mydomain.com. here's the setcookie file :
<?php
setcookie("user_name","test",time()+3600);
?>
and chcking the cookie like this :
if(isset($_COOKIE["user_name"])){
echo "cookie exists";
}
else{
echo "cookie doesn't exist";
}
i've read many topics about this issue but there was no clear answer.
Thanks in advance
This typically happens when you try to set a cookie after sending output to the browser. To set a cookie in WP, you should use the 'init' hook to set the cookie on init.
function set_username_cookie() {
if (!isset($_COOKIE['user_name'])) {
setcookie("user_name","test",time()+3600);
}
}
add_action( 'init', 'set_username_cookie');
well, my best way to use cookie in wordpress is this,
function set_my_cookie() {
global $post;
$post_id = $post->ID;
$cookie_name = "my_cookie";
$cookie_value = "my_cookie_val";
if (!isset($_COOKIE['my_cookie'])) {
{
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}}add_action( 'wp', 'set_my_cookie');
i used this the function to setcookie in wp hook of wordpress. the main reason of this is that we may need sometime current page or post, that we cannot access on init hook, but we can access in wp hook.
now, in a shortcode or other plugin/theme functions we may just need to check if the cookie exists or not. thats it
Another option is to use PHP's ob_start(); and ob_end_flush();.
You can find documentation on the two functions here
The way I resolved my issues was to call the two functions before and after the opening and closing html tags like this:
<?php ob_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php /* Wordpress loop and other tempate code here */ ?>
</body>
</html>
<?php ob_end_flush(); ?>
The issue I was running into was calling a global function that used PHP's setcookie(); and because WordPress processes the page progressively, the cookie couldn't be created due to the page's headers already being sent.
PHP's output buffering function forces the headers to be sent before WordPress processes the page.
Hope this helps.

Wordpress phpinfo cookies issue

Hey ya'll I have this site here http://www.taranmarlowjewelry.com/ and in the top right corner there is a shopping cart, but it does not show up when you first visit the site, but when you refresh the page it shows up.
I have been looking into this and I think it has to do with this cookie PHPSESSID because when I delete that cookie the shopping cart goes away again.
I have also been told this is a PHP configurations issues.
I tried making some adjustments to my php5.ini file like so...
session.use_only_cookies = 1
session.use_trans_sid = 0
session.url_rewriter.tags = ""
but that didnt work....I got it from here http://wordpress.org/support/topic/frontpage-slideshow-and-phpsessid-in-general-fix?replies=1
Does anyone know which I need to adjust in my php configuration?
I tried to set a cookie in wp-content/themes/twentyeleven/header.php right after the tag like this...
<?php
setcookie("PHPSESSID","6a52e6037be6342014834c475b6c0637","/","http://www.taranmarlowjewelry.com/")
?>
and then I get this error...
Warning: setcookie() expects parameter 3 to be long, string given in /home/content/19/9468119/html/wp-content/themes/twentyeleven/header.php on line 54
and the shopping cart does not show up when you first visit my site but when you refresh it will still show up.
I even manually put in the cookie in my theme's functions.php file at the bottom like so...
function set_new_cookie() {
setcookie("PHPSESSID", '6a52e6037be6342014834c475b6c0637', time()+3600); /* expire in 1 hour */
}
add_action( 'init', 'set_new_cookie');
it sets it, it doesn't show any errors, but it does not solve my problem.
I also tried this in my theme's functions.php file...
function set_new_cookie() {
set_cookie('PHPSESSID', '6a52e6037be6342014834c475b6c0637');
$_COOKIE['PHPSESSID'] = '6a52e6037be6342014834c475b6c0637';
}
add_action( 'init', 'set_new_cookie');
and got this error
Fatal error: Call to undefined function set_cookie() in /home/content/19/9468119/html/wp-content/themes/twentyeleven/functions.php on line 5
here is the shopping cart form...
<form class="product_search" style="font-size:0px !important;" method="GET" action="<?php echo $pp_url?>/" >
<input name="product_search" id="wpsc_search_autocomplete" class="wpsc_product_search wpsc_live_search_embed .wpsc_live_search" autocomplete="off" style="padding:0px !important; height:25px !important; vertical-align:top;" />
<script type='text/javascript' > /* <![CDATA[ */
jQuery('#wpsc_search_autocomplete').keypress( function(e){
if ( e.keyCode == 13 ) {
var url = '<?php echo $pp_url ?>'+'?product_search='+jQuery(this).val();
url = encodeURI(url);
jQuery(window.location).attr('href', url);
}
});
/* ]]> */
</script>
<input type="submit" id="button" name="button" class="searchBtn" value="GO"/>
</form>
I fixed my issue with the shopping cart by going into wp-ecommerce/wpsc-includes/shopping_cart_functions.php and adjusting this line
if ( isset( $cart ) ) {
echo wpsc_shopping_basket_internals( $cart, false, true );
}
to this
//if ( isset( $cart ) ) {
echo wpsc_shopping_basket_internals( $cart, false, true );
//}
The problem is not in the cookie being set. Your session_start() will set that. However you need to understand how cookies (including the session cookie) work. The cookies are sent from the server to the browser in the response header. So the user will not have the cookie set in their browser until they start getting your response source. On their next request to the site, their browser will send the cookie with the request.
So the problem is that is you are trying to rely on something in the $_COOKIE superglobal on the first page load, it will not be there (unless the user already had it set from a previous visit). If you need to work with the $_COOKIE in the initial page load you need to do something like this
setcookie('cookiename', 'cookie value');
$_COOKIE['cookiename'] = 'cookie value';

what's the recommendation for adding javascript fragments to wordpress admin

This is more of a semantics advice request:
I have a little screen in my WP admin>settings and it just needs literally a couple of lines of javascript added. My first thought is to do it like this:
add_settings_section('social_options_facebook_connect', '', 'social_facebook_section_text', 'social');
function social_options_facebook_connect(){
echo '
<script>
//throw a function in here which is about 2 lines long
</script>';
//button
echo '<input name="Submit" type="submit" onclick="javascript:myFunctionCallHere()" value="Connect Site To Facebook" class="button-primary" style="margin:20px;" />';
}
but this seems a little dirty.
What is the recommended way of doing this?
thanks very much.
Take a look at http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts . This example shows how to limit it to only your .php pages.
I usually include a check to only load the extra stuff on the page it's required on. That way you're not adding it to every page in the admin. Assuming it's not necessary on every page!
It's probably not going to be of much benefit in this case but if you start adding more and more it definitely helps the speed of your admin pages.
$_current_page = isset($_GET["page"]) ? $_GET["page"] : "";
if ($_current_page == 'social') {
function social_admin_enqueue_scripts() {
wp_enqueue_script( 'social_script_1', 'url-for-script', '', '1.0.0', true );
wp_enqueue_script( 'social_script_2', 'url-for-script', '', '1.0.0', true );
}
add_action( 'admin_enqueue_scripts', 'social_admin_enqueue_scripts' );
}

Protect wordpress theme with license key validation

I'm planning to develop some professional Wordpress Themes and would like to protect it using license keys, is it possible?
If so, would any one be willing to link to some posts or articles to help me get started?
You could set up a database on your own server, holding the license key and the licensed url for the theme. Then, set up an admin page for your theme. Within, first register a license settings array. Then implement a hidden settings field on that same page that gets updated whenever the license key is being updated by site admin. the update function sends a request to your server passing the license key and the $_SERVER's host and setting the hidden license_settings field to either true or false.
A really simplified code would look like this:
functions.php
<?php
// functions.php
require("myadminpage.php");
# Functions follow here...
?>
myadminpage.php
<?php
// myadminpage.php
// register settings
function my_settings_init() {
register_setting('settings_license', 'settings_license');
}
// register admin page
function my_add_admin_page() {
add_menu_page(__( '' ), __( 'Manage License' ), 'administrator', 'myadminpage', 'my_admin_page');
}
add_action('admin_init', 'my_settings_init');
add_action('admin_menu', 'my_add_admin_page' );
if(isset($_GET["settings-updated"]) && $_GET["settings-updated"] == true) {
$options = get_option('settings_license');
$key = $options["key"];
$host = parse_url($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'], PHP_URL_HOST);
$url = sprintf("http://you.com/check-license.php?key=%s&url=%s", $key, $host);
$options["valid"] = trim(file_get_contents($url)) == 1) ? "true" : "false";
update_option('settings_license', $options);
}
// callback function that renders your admin page
function my_admin_page() {
settings_fields('settings_license');
$options = get_option('settings_license');
?>
<form method="post" action="options.php">
<input id="settings_license[key]" type="text" name="settings_license[key]" value="<?php echo $options["key"]; ?>">
<input id="settings_license[valid]" type="hidden" name="settings_license[valid]" value="<?php echo $options["valid"]; ?>">
<input type="submit" value="Save">
</form>
<?php
}
?>
Now you can, when ever you need/want, get the license options and handle the invalid usage in any way you want. Eg (a rude way):
header.php
<?php
// very first line
$license = get_option('settings_license');
// see: http://ckon.wordpress.com/2006/08/09/server-request_uri-doesnt-always-work-correctly-heres-how-to-fix/
$ruri = $GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'];
if(!preg_match("#wp-admin#", $ruri) && $license["valid"] != "true") {
wp_die( __('This website uses unlicensed software.<br>Administrators can update their license key here.') );
}
# rest of header.php comes here..
Finally obfuscate your php code (eg http://www.ioncube.com/sa_encoder.php) and you're done. However, make sure you're not violating any other licenses, such as WP's. If there's one single line of WordPress core functions used within your final code, you can not release it under any other license than WP, which is GPL.
I don't think so. After all, the users must have the php code to use the theme and if they have it - they may alter it in a such way that it won't need a key any more.

Resources