PHP执行Shell命令(2)

一个完整的使用PHP框架(Yii2)进行Shell操作的例子:

1.在models中新建SearchForm.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SearchForm extends Model
{

public $keyword;

public function rules()
{

return [
[['keyword'], 'required'],
];
}

public function attributeLabels()
{

return [
'keyword' => '关键词',
];
}

}

2.在SiteController.php中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function actionSearch()
{

$result = array();
$model = new SearchForm();

if ($model->load(Yii::$app->request->post())) {
$keyword = $model->keyword;
$cmd_search = "grep -n ".$keyword." /var/html/index*";
exec($cmd_search, $result, $status);
}
return $this->render('search', [
'result' => $result,
'model' => $model,
]);
}

3.在views/site中新建search.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div class="site-search">
<div>
<?php $form = ActiveForm::begin(['id' => 'search-form']); ?>

<?= $form->field($model, 'keyword')->textInput(['placeholder'=>'输入关键词']) ?>

<div class="form-group">
<?= Html::submitButton('搜索', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

<p>共搜索到 <?= count($result) ?> 条结果</p>
<div>
<p>搜索结果展示如下:</p>
<?php
foreach ($result as $key=>$value) {
echo "<p>".$value."</p>";
}
?>

</div>
</div>
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!