How to make asynchronous HTTP requests in PHP

后端 未结 18 2074
梦如初夏
梦如初夏 2020-11-22 02:13

Is there a way in PHP to make asynchronous HTTP calls? I don\'t care about the response, I just want to do something like file_get_contents(), but not wait for

18条回答
  •  旧时难觅i
    2020-11-22 03:10

    let me show you my way :)

    needs nodejs installed on the server

    (my server sends 1000 https get request takes only 2 seconds)

    url.php :

     /dev/null &");   
        } 
    } 
    fwite(fopen("urls.txt","w"),implode("\n",$urls);
    execinbackground("nodejs urlscript.js urls.txt");
    // { do your work while get requests being executed.. }
    ?>
    

    urlscript.js >

    var https = require('https');
    var url = require('url');
    var http = require('http');
    var fs = require('fs');
    var dosya = process.argv[2];
    var logdosya = 'log.txt';
    var count=0;
    http.globalAgent.maxSockets = 300;
    https.globalAgent.maxSockets = 300;
    
    setTimeout(timeout,100000); // maximum execution time (in ms)
    
    function trim(string) {
        return string.replace(/^\s*|\s*$/g, '')
    }
    
    fs.readFile(process.argv[2], 'utf8', function (err, data) {
        if (err) {
            throw err;
        }
        parcala(data);
    });
    
    function parcala(data) {
        var data = data.split("\n");
        count=''+data.length+'-'+data[1];
        data.forEach(function (d) {
            req(trim(d));
        });
        /*
        fs.unlink(dosya, function d() {
            console.log('<%s> file deleted', dosya);
        });
        */
    }
    
    
    function req(link) {
        var linkinfo = url.parse(link);
        if (linkinfo.protocol == 'https:') {
            var options = {
            host: linkinfo.host,
            port: 443,
            path: linkinfo.path,
            method: 'GET'
        };
    https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
        } else {
        var options = {
            host: linkinfo.host,
            port: 80,
            path: linkinfo.path,
            method: 'GET'
        };        
    http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
        }
    }
    
    
    process.on('exit', onExit);
    
    function onExit() {
        log();
    }
    
    function timeout()
    {
    console.log("i am too far gone");process.exit();
    }
    
    function log() 
    {
        var fd = fs.openSync(logdosya, 'a+');
        fs.writeSync(fd, dosya + '-'+count+'\n');
        fs.closeSync(fd);
    }
    

提交回复
热议问题