How do you use curl within wordpress plugins?

烈酒焚心 提交于 2019-12-12 08:03:51

问题


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); 
 } 

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4800688/how-do-you-use-curl-within-wordpress-plugins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!