How do you use curl in wordpress plugins?

I am creating a wordpress plugin and I am having problems with the correct operation of the cURL call.

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

On the orders page, I have a function that looks to see if a button has been pressed, and if necessary, you need to make a cURL call on the same page (www.domain.com/wp-admin/admin.php?page = orders & dosomething = true) to run another function. The reason I'm doing this is because I can use this cURL call async.

I am not getting any errors, but I am not getting a response either. If I change my url to google.com or example.com, I will get a response. Perhaps there is an authentication problem or something like that?

My code looks something like this. I use get, echos and do not run async just for the convenience 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); 
 } 
+5
source share
2 answers

You should not use CURL in WordPress plugins.

Instead, use the wp_ function to issue HTTP requests, for example.

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 ran into problems when WordPress event handlers connected to CURL. Using WP_ functions instead worked as expected.

+10
source

Of course, the blog admin section is password protected. You will need to pass authentication data. Check out http authentication for more information. Look specifically here:

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

CURLOPT_USERPWD , , CURLOPT_HTTPAUTH.

+3

All Articles