Ajax完成后才关闭php cURL

时间:2018-02-09 12:55:19

标签: javascript php jquery ajax curl

A有cURL登录到由ajax触发的网络路由器。但我需要保持连接存活,直到xhr请求成功完成。 这有可能吗?

这里要澄清我想要做的事情,这是我登录的Ajax功能:

function logintorouter(){
    $.ajax({
        type: 'GET',
        dataType:"text",
        url: 'login.php'
    }).done(function(data){
        if(data.includes('WiFi')){
            setWiFichannel(); /*Wait for this function to finish before closing cURL connection */
        }else{
             alert('something went wrong, try again later!');
        }
    }).fail(function(data){
        alert('can not connect to router');
    });
} 

我的login.php现在看起来像这样:

<?php
function openRouter(){
    $username = 'admin';
    $password = 'pass';

    $url="http://10.1.10.1/login/Auth";  
    $postinfo = "username=".$username."&password=".$password;

    $cookie_file_path = "cookie.txt";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
    curl_exec($ch);

    curl_setopt($ch, CURLOPT_URL, "http://10.1.10.1/main.html#WiFi");
    $mainPage = curl_exec($ch);

    curl_close($ch);
    /*As you can see I close the connection here so the setWiFichannel() will fail 
    but I don't want to keep the connection alive forever*/     
    return $mainPage; 
}

echo openRouter();
?>

0 个答案:

没有答案