PhantomJs可以通过PHP shell_exec访问远程站点,但不能访问本地站点

时间:2015-05-29 06:03:08

标签: php apache ubuntu phantomjs

当我使用PHP使用shell_exec()在本地服务器页面上运行幻像JS时,我遇到了page.open无法运行的回调问题。如果我通过命令行在本地URL上运行phantomjs,那么回调就会触发。

PHP脚本:

<?php
error_reporting(E_ALL);
session_write_close();
$result = shell_exec('phantomjs server.js ' . $_GET['url'] ); 
echo $result;

JS脚本

/**
 *  PhantomJs server for calling webpages & processing JS
 *  returns page content
 */

var args = require('system').args;
var address = args[1];
var page = new WebPage();

var renderPage = function(){

    page = require('webpage').create();
    var myArgs = Array.prototype.slice.call(arguments),
        url_str = myArgs[0];

     console.log('accessing:'+url_str);

    page.onError = function(msg){console.log('js error');}

    /**
     * From PhantomJS documentation:
     * This callback is invoked when there is a JavaScript console. The callback may accept up to three arguments:
     * the string for the message, the line number, and the source identifier.
     */
    page.onConsoleMessage = function (msg, line, source) {
        console.log('console> ' + msg);
    };

    /**
     * From PhantomJS documentation:
     * This callback is invoked when there is a JavaScript alert. The only argument passed to the callback is the string for the message.
     */
    page.onAlert = function (msg) {
        console.log('alert!!> ' + msg);
    };

    /**
     * Handle Redirection
     */
    page.onNavigationRequested = function(url_sub_str, type, willNavigate, main) {
        if (main && url_sub_str != url_str) {
            url_str = url_sub_str;
            console.log("redirect caught");
            page.close();
            setTimeout(function() {
                renderPage(url_str)
            },1);
        }
    };

    page.onResourceReceived = function (response) {
        console.log('Receive ' + JSON.stringify(response, undefined, 4));
    };

    /**
     * Open the web page and run RRunner
     */
    page.open(url_str, function(status) {
        console.log('here');
        if (status === 'success') {
            console.log(page.content); 
            phantom.exit();         
        } else {
            console.log('failed');          
            phantom.exit();
        }
    });
};


address = 'http://local.wordpress.dev/test.php'; /* does not work via shell_exec */
//address = 'http://local.wordpress.dev/'; /* does not work via shell_exec */
//address = 'http://www.inboundnow.com/'; /* works via shell_exec */
renderPage(address);

当我调用我的php脚本时,js会将其输出到正文中:

accessing:http://local.wordpress.dev/test.php
  • 我在VVV-Apache vagrant机器上运行。
  • 如果我在使用PHP方法时尝试访问.html文件,我会得到一个成功的响应。
  • 如果我尝试访问一个本地虚拟php文件,回复一些内容,它使用PHP方法无法正常工作。

0 个答案:

没有答案