TOP ▲
itcore TOP
> TIPS
> grep.php
タグ:grep php grep.php 画面からgrepを実行するPHPサンプルプログラム。| itcore 2018年
テスト実行
セキュリティのためリードオンリーになっています。
プログラムソース
<?php
//----------------------------
$title = "grep.php 画面からgrepを実行するPHPサンプルプログラム。| itcore 2018年";
// 2018-01-17 初期開発
//----------------------------
uIniErrorOutput(); // エラーを画面に出す。
$mode = uForm("mode");
$self_id = "grep";
$self = basename($_SERVER['PHP_SELF']);
//----------------------------
// grep処理
//----------------------------
if ("" != uForm("sub_grep")) {
$dir1 = uForm("dir1");
$data1 = uForm("data1");
$dir1 = "/tmp/grep"; // サンプルのため固定
//$data1 = "test"; // サンプルのため固定
$cmd = "grep -Rin '$data1' $dir1";
print "cmd=" . htmlspecialchars($cmd) . "<br>\n";
u_shell_exec("mkdir $dir1");
u_shell_exec("echo test1 >$dir1/a.txt");
u_shell_exec("mkdir $dir1/b");
u_shell_exec("echo TEST2 >$dir1/b/c.txt");
$ret = u_shell_exec($cmd);
print nl2br(htmlspecialchars($ret)) . "<br>\n";
exit;
}
function u_shell_exec($cmd) {
//echo "debug53 cmd=$cmd<br>\n";
$cmd = escapeshellcmd($cmd);
//echo "debug54 cmd=$cmd<br>\n";
return shell_exec($cmd);
}
//----------------------------
// 初期画面
//----------------------------
include_once "header.inc"; // ヘッダー
tag("grep PHP");
?>
<h2> <?php echo $title; ?></h2>
<h3>テスト実行</h3>
セキュリティのためリードオンリーになっています。<br>
<form action=<?php echo $self; ?> method=post>
ディレクトリ <input type=text name=dir1 value="/tmp/grep" readonly><br>
検索文字 <input type=text name=data1 value="test" readonly><br>
<input type=submit name=sub_grep value='grep実行'><br>
</form>
<h3>プログラムソース</h3>
<?php
$data = file_get_contents($self);
print nl2br(uHtmlspecialcharsIndent($data));
?>
<hr>
<?php
//----------------------------
// 共通関数
//----------------------------
// エラーを画面に出す。
function uIniErrorOutput() {
error_reporting(E_ALL);
ini_set('display_errors', 1);
}
// フォーム変数の受取。存在しない時は空文字を返す。
function uForm($var) {
if (isset($_POST[$var])) return $_POST[$var];
if (isset($_GET[$var])) return $_GET[$var];
return "";
}
// インデント付きのhtmlspecialchars 行頭の空白を に変換する。
function uHtmlspecialcharsIndent($text) {
$a_line = explode("\n", $text); // 行に分割
$text1 = "";
for($i2 = 0; $i2 < count($a_line); $i2++) {
$line = $a_line[$i2];
for ($i = 0; $i < strlen($line); $i++) {
$s1 = substr($line, $i, 1);
if (" " == $s1) {
$text1 .= " ";
} else if ("\t" == $s1) {
$text1 .= " ";
} else {
$text1 .= htmlspecialchars(substr($line, $i)) . "\n";
break;
}
}
if (count($a_line) -1 != $i2 && 0 == strlen($line)) $text1 .= "\n"; // 最終行以外の空行
}
return $text1;
}
?>