phantomJS:绝对路径工作,但相对路径给出问题

时间:2013-06-07 07:26:06

标签: php javascript linux phantomjs

我在Linux网络服务器上。以下文件用于创建屏幕截图:

  • ons.php
  • ong.js
  • ons2.php

所有这些文件以及phantomJS二进制文件都位于同一文件夹中。该文件夹的权限为744

ons.php

$forMonth = date('M Y');
exec('./phantomjs ons.js '.strtotime($forMonth), $op, $er);
print_r($op);
echo $er;

ons.js

var args = require('system').args;
var dt = '';
args.forEach(function(arg, i) {

    if(i == 1)
    {
        dt = arg;       
    }   

});
var page = require('webpage').create();
page.open('./ons2.php?dt='+dt, function () { //<--- This is failing
    page.render('./xx.png');
    phantom.exit();
});

ons2.php

<!DOCTYPE html>
<html>
<head>
    <title>How are you</title>
</head> 
<body>
<?php
if(isset($_GET['dt']))
{

    echo $_GET['dt'];

}
else
{
    echo '<h1>Did not work</h1>';
}
?>

</body>
</html>

在浏览器中打开ons.php后,我收到了以下结果:

Array ( ) 0

但是没有创建截图。

调试

经过多次调试,我发现它与路径有关。

- &GT;如果我将以下内容放在ons.js

.
.
.   
var page = require('webpage').create();
page.open('http://www.abc.com/ppt/ons2.php', function () { // <-- absolute path
    page.render('./xx.png');
    phantom.exit();
});

屏幕截图正在创建中。我想避免使用绝对路径,因为应用程序很快就会转移到不同的域。

我不知道的是,即使所有文件都在同一个文件夹中,相对路径也不起作用。我的page.open('./ons2.php....')语法错了吗?

2 个答案:

答案 0 :(得分:1)

./ons2.php表示本地文件。它不会传递到Web服务器,而且它将彻底失败,因为您还附加了一个查询字符串 - 在本地文件系统中,这将被视为文件名的一部分,因此文件根本不会找到。

需要为此提供绝对网址,以便按预期工作 - 但您可以在PHP中动态确定这一点(使用$_SERVER)和将其作为命令行参数传递给JS脚本。

例如(未经测试):

ons.php

<?php

    // Determine the absolute URL of the directory containing this script
    $baseURL = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
             . '://' . $_SERVER['HTTP_HOST']
             . rtrim(dirname($_SERVER['REQUEST_URI']), '/') . '/';

    $now = new DateTime('now'); // Because all the cool kids use DateTime

    $cmd = './phantomjs ons.js '
         . escapeshellarg($now->format('M Y')) . ' ' // Don't forget to escape args!
         . escapeshellarg($baseURL)
         . ' 2>&1'; // let's capture STDERR as well

    // Do your thang
    exec($cmd, $op, $er);

    print_r($op);
    echo $er;

ons.js

var args, url, page;

args = require('system').args;
if (args.length < 3) {
    console.error('Invalid arguments');
    phantom.exit();
}

url = args[2] + 'ons2.php?dt=' + encodeURIComponent(args[1]);

console.log('Loading page: ' + url);

page = require('webpage').create();
page.open(url, function () {
    page.render('./xx.png');
    phantom.exit();
});

ons2.php保持不变。

答案 1 :(得分:0)

也许page.render中存在问题,但我不这么认为。挂起的最常见情况是未处理的异常。

我会建议你解决这个问题:

  • phantom.onError和/或page.OnError
  • 添加处理程序
  • 将您的代码封装在try / catch块中(例如用于page.render)
  • 加载页面后,回调状态没有测试。最好检查状态(“成功”或“失败”)
  • 调用page.render时,
  • 似乎冻结了。你在当前目录中尝试过一个更简单的文件名吗?也许冻结是因为安全性或文件名无效(无效字符?)

希望这会对你有所帮助

相关问题