Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use curl within wordpress plugins?

I'm creating a wordpress plugin and I'm having trouble getting a cURL call to function correctly.

Lets say I have a page www.domain.com/wp-admin/admin.php?page=orders

Within the orders page I have a function that looks to see if a button was clicked and if so it needs to do a cURL call to the same page (www.domain.com/wp-admin/admin.php?page=orders&dosomething=true) to kick off a different function. The reason I'm doing it this way is so I can have this cURL call be async.

I'm not getting any errors, but I'm also not getting any response back. If I change my url to google.com or example.com I will get a response. Is there an authentication issue or something of that nature possibly?

My code looks something like this.. I'm using gets, echos, and not doing async just for the ease of testing.

if(isset($_POST['somebutton']))
{
    curlRequest("http://www.domain.com/wp-admin/admin.php?page=orders&dosomething=true");
}

if($_GET['dosomething'] == "true")
{
     echo("do something");
     exit;
}

function curlRequest($url) {
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    return($response); 
 } 
like image 886
Jason Avatar asked Jan 26 '11 01:01

Jason


2 Answers

You're not supposed to use CURL in WordPress Plugins.

Instead use the wp_ function for issuing HTTP requests, e.g.

function wp_plugin_event_handler () {
    $url = 'http://your-end-point';  
    $foo = 'bar';
    $post_data = array(
         'email' => urlencode($foo));

    $result = wp_remote_post( $url, array( 'body' => $post_data ) );
}

add_action("wp_plugin_event", "wp_plugin_event_handler");

In the past I've run into issues where WordPress plugins event handlers would hang with CURL. Using the WP_ functions instead worked as expected.

like image 114
Bill Avatar answered Oct 09 '22 06:10

Bill


The admin section of the blog is password-protected, of course. You'll need to pass authentication data. Look up http authentication for details. Look specifically here:

http://www.php.net/manual/en/function.curl-setopt.php

You'll want to set the CURLOPT_USERPWD option and possibly CURLOPT_HTTPAUTH.

like image 38
Eric Giguere Avatar answered Oct 09 '22 06:10

Eric Giguere