我还安装了 gearman 扩展和 gearman 命令行工具。我尝试使用 gearman 从简单的 php 文件中反转字符串。
Example:
$gmclient= new GearmanClient();
$gmclient->addServer();
$result = $gmclient->doNormal("reverse", "Test the reverse string");
echo "Success: $result\n";
output:
Success: gnirts esrever eht tseT
以同样的方式,我尝试运行 exec('ls -l') ,我能够使用 webroot 目录中的 cakephp 应用程序中的简单 php 文件来执行。文件路径:cakephp/app/webroot/worker.php,cakephp/app/webroot/client.php。
worker.php
<?php
$worker= new GearmanWorker();
$worker->addServer();
$worker->addFunction("exec", "executeScript");
while ($worker->work());
function executeScript($job)
{
$param = $job->workload();
$t = exec($param);
return $t;
}
?>
client.php
<?php
$client= new GearmanClient();
$client->addServer();
$cmd = 'ls -l';
print $client->do("exec", $cmd);
?>
如何使用cakephp中的View、Controller实现同类型的执行? 工作流程:使用ajax方法将数据从View发送到 Controller 并执行“exec() from gearman”,将输出发送回View作为ajax POST方法的响应。
最佳答案
你为什么使用exec
?!这带来了巨大的安全风险。使用DirectoryIterator反而。
您的客户端代码应该是 Controller 的一部分。
<?php
class UploadController extends AppController
{
public function directoryList()
{
$directory = '';
// Get data
if (!empty($this->data['directory']) && is_string($this->data['directory']))
{
$directory = $this->data['directory'];
}
$client= new GearmanClient();
$client->addServer("localhost",4730); // Important!!!
$result = $client->do("fileList", serialize($data));
return $result;
}
}
然后从 View 中使用 requestAction .
$uploads = $this->requestAction(
array('controller' => 'upload', 'action' => 'directoryList'),
array('return')
);
worker 可能看起来像这样:
<?php
$worker= new GearmanWorker();
$worker->addServer("localhost",4730); // Important!!!
$worker->addFunction("fileList", "getFileList");
while ($worker->work());
// From Art of Web
// http://www.the-art-of-web.com/php/directory-list-spl/
function getFileList($dir)
{
// array to hold return value
$retval = array();
$dir = $job->workload();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// open directory for reading
$d = new DirectoryIterator($dir) or die("getFileList: Failed opening directory $dir for reading");
foreach($d as $fileinfo) {
// skip hidden files
if($fileinfo->isDot()) continue;
$retval[] = array(
'name' => "{$dir}{$fileinfo}",
'type' => ($fileinfo->getType() == "dir") ?
"dir" : mime_content_type($fileinfo->getRealPath()),
'size' => $fileinfo->getSize(),
'lastmod' => $fileinfo->getMTime()
);
}
return $retval;
}
这是伪代码。 请勿在生产中使用它!!!请参阅 Gearman documentation进行更高级的工作设置。
要真正利用负载分配,Gearman 服务器当然不应该位于本地主机上。
关于php - 如何使用 cakephp 应用程序中的 gearman 扩展运行 exec()/linux 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179438/