我需要一种为图像管理脚本生成缩略图(使用 PHP5)的方法,并且遇到了一个问题,即我的主机安装了多个版本的 PHP(4 和 5),并将 PHP4 设置为默认值。这意味着从 CLI 对 php 的任何调用都将运行 PHP4。我想出了以下作为我希望成为跨平台解决方案的方法。我在这里发布它主要是因为我在使用 Google 时很难找到任何帮助,所以这可能会在将来对某人有所帮助,我也有以下问题。
- 你有什么明显的问题吗?
- 您是否知道或知道更好的顺序来优化 php5 二进制文件的任何其他路径?
- 如果主机禁用了 exec 或 shell_exec,EGalleryProcessQueue.php 脚本能否作为独立的 cron 作业运行?我还没有访问 cron 的权限来测试它。我不太担心这个问题,因为无论如何我最终都会去测试它。
- 有没有人对我可以获得一些反馈的方式有任何建议,以了解处理图像的距离?请参阅 EGalleryProcessQueue.php 的 TODO 部分 我想在管理部分显示进度条。
主脚本
/**
* Writes the array to a text file in /path/to/gallery/needsThumbs.txt for batch processing.
* Runs the thumbnail generator script in the background.
*
* @param array $_needsThumbs the array of images needing thumbnails
*/
private function generateThumbnails($_needsThumbs)
{
file_put_contents($this->_realpath.DIRECTORY_SEPARATOR.'needsThumbs.txt',serialize($_needsThumbs));
$Command = realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR.'EGalleryProcessQueue.php '.$this->_realpath.' '.$this->thumbnailWidth.' '.$this->thumbnailHeight;
if(PHP_SHLIB_SUFFIX == 'so')// *nix (aka NOT windows)
{
/*
* We need to make sure we are using the right PHP version
* (problems with shared hosts that have PHP4 and PHP5 installed,
* but PHP4 set as default).
*/
$phpPaths = array('php', '/usr/local/bin/php', '/usr/local/php5/bin/php', '/usr/bin/php', '/usr/bin/php5');
foreach($phpPaths as $path)
{
exec("echo '<?php echo version_compare(PHP_VERSION, \"5.0.0\", \">=\"); ?>' | $path", $result);
if($result)
{
shell_exec("nohup $path $Command 2> /dev/null > /dev/null &");
break;
}
}
}
else // Windows
{
$WshShell = new COM("WScript.Shell");
$WshShell->Run("php.exe $Command", 0, false);
}
}
EGalleryProcessQueue.php
#!/usr/bin/php
<?php
if ($argc === 4 && strstr($argv[0], basename(__FILE__))) {
// File is being called by the CLI and has not been included by another script
if(!file_exists($argv[1].DIRECTORY_SEPARATOR.'needsThumbs.txt'))
{
// Either no thumbnails need to be created or a wrong directory has been supplied
exit;
}
include(realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR.'EGalleryThumbGenerator.php');
$generator = new EGalleryThumbGenerator;
$generator->directory = $argv[1];
$generator->thumbnailWidth = is_int($argv[2]) ? $argv[2] : 128;
$generator->thumbnailHeight = is_int($argv[3]) ? $argv[3] : 128;
// $generator->processImages() returns the number of images left to process (it does them in blocks of 10)
while (($i = $generator->processImages()) > 0)
{
/*
* TODO Can we get some sort of feedback to the user here?
* Possibly so that we can display a progress bar in the management section.
* Probably have to write $i to a file to be read by the main script.
*/
}
exit;
}
?>