PHP和图像创建的Crontab问题


Crontab issues with PHP and image creation

上下文:我写了一个脚本,从服务器下载图像,设置白色为透明,并将图像保存在根文件夹中。它还将图像的副本保存在单独的文件夹"images"中,并在其名称中注明日期和时间。

因为我不确切地知道图像何时刷新,所以我将图像的哈希值与创建日期和文件名一起保存在数据库中。

问题:我希望脚本每5分钟自动运行一次,所以我在我的服务器上创建了一个crontab (Ubuntu server 12.04)。Crontab确实每5分钟执行一次脚本,但是它只向数据库添加新记录,而不保存实际的图像。当我尝试通过控制台或web浏览器手动运行脚本时,它会正常工作:保存图像并更新数据库记录。

Crontab(以防有问题):

*/5 * * * * /usr/bin/php5 -f /var/www/radar.php > /var/www/logPHP.log 2>&1
PHP代码:

include 'mysql.php';
$im = imagecreatefromgif("image_url");
$hash = hash_file('md5', "image_url");
$day = date("j");
$month = date("n");
$year = date("Y");
$hour = date("G");
$minute = date("i");
$file = 'image' . $day . '-' . $month . '-' . $year . '_' . $hour . '_' . $minute . '.gif';
echo "Hash: " . $hash . "<br />";
echo "Start: " . date("H:i:s") . "<br />";
$result = mysql_query("SELECT * FROM pictures WHERE hash = '$hash' LIMIT 1");
$num = mysql_num_rows($result);
if ($num == 0) {
    mysql_query("INSERT INTO pictures (year, month, day, hour, minute, hash, file) VALUES ('$year', '$month', '$year', '$hour', '$minute', '$hash', '$file')");
    $dest = imagecreatetruecolor(799, 599);
    imagecopy($dest, $im, 0, 0, 10, 49, 799, 599);
    $color = imagecolorexact($dest, 255, 255, 255);
    imagecolortransparent($dest, $color);
    imagegif($dest, './image.gif');
    imagegif($dest, './images/' . $file);
    imagedestroy($dest);
    imagedestroy($im);
}
echo "End: " . date("H:i:s");
?>
<br /><img src="./image.gif" />
编辑:

现在我在crontab中添加了另一行,它使用wget下载图像并将其保存到特定的文件夹中。图像下载没有问题。我也编辑php文件使用下载的图像,但问题并没有消失。没有创建映像。

AFAIK, CLI PHP使用的ini文件与您的web服务器关联的ini文件不同。如果这也是您的情况,那么调用include()可能会轮询到完全不同的include_path(s),因此无法找到mysql.php

打开此页的错误报告,看看是否会显示错误。

error_reporting(E_ALL);
ini_set("display_errors", 1);

我们尝试从脚本文件夹(如主文件夹)中通过任何其他文件夹使用crontab行。

/usr/bin/php5 -f /var/www/radar.php

如果脚本在这种情况下运行。那么有可能crontab根本没有为您的用户运行。然后配置cron日志或检查syslog以获取任何信息。

您的crontab文件缺少应该运行脚本的用户名。试试这样写:

*/5 * * * * www-data /usr/bin/php5 -f /var/www/radar.php > /var/www/logPHP.log 2>&1

你的/var/log/syslog应该像missing username一样抱怨分组错误。

祝你项目顺利。