php 文件管理类,file.browser.class.php,代码:
<?php
date_default_timezone_set('Asia/Shanghai');
class Browser {
const cUsername = "admin";
const cPassword = "password";
public $separator, $sMessage = 0, $sError = 0;
private $aPlainText = array('as','asp','aspx','atom','bat','cfm','cmd','hta','htm','html','js','jsp','java','mht','php','pl','py','rb','rss','sh','txt','xhtml','xml','log','out','ini','shtml','xsl','xslt','backup');
private $aImageType = array('bm','bmp','ras','rast','fif','flo','turbot','g3','gif','ief','iefs','jfif','jfif-tbnl','jpe','jpeg','jpg','jut','nap','naplps','pic','pict','jfif','jpe','jpeg','jpg','png','x-png','tif','tiff','mcf','dwg','dxf','svf','fpx','fpx','rf','rp','wbmp','xif','xbm','ras','dwg','dxf','svf','ico','art','jps','nif','niff','pcx','pct','xpm','pnm','pbm','pgm','pgm','ppm','qif','qti','qtif','rgb','tif','tiff','bmp','xbm','xbm',
'pm','xpm','xwd','xwd');
public function __construct($bAuth){
if ($bAuth) {
if ($_POST['button'] == 'Login') {
if (($_POST['username'] == self::cUsername) && ($_POST['password'] == self::cPassword)) {
$_SESSION['auth'] = "1";
}else{
$_SESSION['auth'] = "0";
}
}
if (!$_SESSION['auth']) {
$sHtml = "<form method=\"post\">
<table background-color:#ffffff; padding: 1em; border:1px solid #000000;\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\" width=\"200\" align=\"center\">
<tr>
<td background-color:#F1F1F1\" colspan=\"2\">Login</td>
</tr>
<tr>
<td>Username</td>
<td><input type=\"text\" name=\"username\" id=\"username\"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type=\"password\" name=\"password\" id=\"password\"/></td>
</tr>
<tr>
<td></td>
<td><input type=\"submit\" name=\"button\" id=\"button\" value=\"Login\"/></td>
</tr>
</table>
</form>";
echo $sHtml;
die();
}
}
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
$this->separator = "\\";
} else {
$this->separator = "/";
}
}
public function downloadFile($file){
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Type: application/octet-stream');
readfile($file);
}
public function fileName($file, $dir){
if (filetype($dir.$file) != "dir") {
$sLink = "<a href=/index.html"browser.php?view=".urlencode($dir.$file)."\">$file</a>";
}
else{
$aCurrentPath = explode($this->separator, $dir);
$iCount = (count($aCurrentPath) -2);
for ($i = 0; $i < $iCount; ++$i) {
$sFullPath .= $aCurrentPath[$i].$this->separator;
}
if ($file == '.') {
$sLink = "<a href=/index.html"browser.php?dir=".$this->separator."\">[ ".$this->separator." ]</a>";
}elseif ($file == '..') {
$sLink = "<a href=/index.html"browser.php?dir=".$sFullPath."\">[ ".$this->separator." ".$this->separator." ]</a>";
}
else{
$sLink = "<a href=/index.html"browser.php?dir=".urlencode($dir.$file)."\">$file</a>";
}
}
return $sLink;
}
public function showDownload($file, $dir = ""){
if (filetype($dir.$file) != "dir") {
return "<a href=/index.html"browser.php?dwl=urlencode($dir$file)\">Download</a>";
}else{
return '';
}
}
public function showEdit($file, $dir){
if (filetype($dir.$file) != "dir") {
$sExt = strtolower(substr(strrchr($file,'.'),1));
if ($sExt == 'zip') {
$sLink = "<a href=/index.html"browser.php?extract=urlencode($dir$file)\">Unpack</a>";
}else{
$sLink = "<a href=/index.html"browser.php?edit=urlencode($dir$file)\" target=\"_new\">Edit</a>";
}
}
return $sLink;
}
public function showFileSize($file, $dir, $precision = 2) {
if (filetype($dir.$file) != "dir") {
return $this->formatSize(filesize($dir.$file));
}else{
return "Dir";
}
}
private function formatSize($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
public function dateFormat($iTimestamp) {
return date("F j, Y, g:i a", $iTimestamp);
}
public function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
if (@unlink($dirname."/".$file)) {
$this->sMessage = "Directory Deleted Successfully: \"".$dirname."\" .";
}
else{
$this->sError = "Can't Deleted Directory \"".$dirname."\" .";
}
else
$this->delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
public function viewFile($file){
$sBaseName = basename($file);
$sExt = strtolower(substr(strrchr($sBaseName,'.'),1));
if ($sExt == "zip") {
$oZip = new ZipArchive;
if ($oZip->open($file) === TRUE) {
echo "<table cellspacing=\"1px\" cellpadding=\"0px\">";
echo "<tr><th>Name</th><th>Uncompressed size</th><th>Compressed size</th><th>Compr. ratio</th><th>Date</th></tr>";
for ($i=0; $i<$oZip->numFiles;$i++) {
$aZipDtls = $oZip->statIndex($i);
$iPercent = round($aZipDtls['comp_size'] * 100 / $aZipDtls['size']);
$iUncompressedSize = $aZipDtls['size'];
$iCompressedSize = $aZipDtls['comp_size'];
$iTotalPercent += $iPercent;
echo "<tr><td>".$aZipDtls['name']."</td><td>".$this->formatSize($iUncompressedSize)."</td><td>".$this->formatSize($iCompressedSize)."</td><td>".$iPercent."%</td><td>".$this->dateFormat($aZipDtls['mtime'])."</td></tr>";
}
echo "</table>";
echo "<p align=\"center\"><b>".$this->showFileSize($file, $dir)." in ".$oZip->numFiles." files in ".basename($oZip->filename).". Compression ratio: ".round($iTotalPercent / $oZip->numFiles)."%</b></p>";
$oZip->close();
} else {
echo 'failed';
}
}elseif (in_array($sExt, $this->aPlainText)) {
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File View');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: inline; filename=' . basename($file));
header('Content-Type: text/plain');
readfile($file);
}elseif(in_array($sExt, $this->aImageType)){
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File View');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: inline; filename=' . basename($file));
header('Content-Type: image/jpg');
readfile($file);
}else{
$this->downloadFile($file);
}
}
public function deleteFiles($aFiles){
if (is_array($aFiles)) {
foreach ($aFiles as $aFilesNames){
if (is_dir($dir.$aFilesNames)) {
$this->delete_directory($dir.$aFilesNames);
}
else{
if (@unlink($dir.$aFilesNames)) {
$this->sMessage = "File Deleted Successfully: \"".$dir.$aFilesNames."\" .";
}else{
$this->sError = "Can't Deleted file \"".$dir.$aFilesNames."\" .";
}
}
}
}
}
public function createFile($dir, $sCreatefile){
if (!file_exists($dir.$sCreatefile)) {
if (is_writable($dir)) {
$handle = fopen($dir.$sCreatefile, "w");
fclose($handle);
$this->sMessage = "File Created Successfully: \"$sCreatefile\" .";
}else{
$this->sError = "Directory Not Writable, Can't Create file.";
}
}
else{
$this->sError = " \"$sCreatefile\" File already exist.";
}
}
private function writeBackup($sFileName){
if (!copy($sFileName, $sFileName.".backup")) {
return false;
}
return true;
}
public function fileWriter($sFile, $string, $backup = false) {
if ($backup) {
$this->writeBackup($sFile);
}
$fp = fopen($sFile,"w");
//Writing to a network stream may end before the whole string is written. Return value of fwrite() is checked
for ($written = 0; $written < strlen($string); $written += $fwrite) {
$fwrite = fwrite($fp, substr($string, $written));
if (!$fwrite) {
return $fwrite;
}
}
fclose($fp);
return $written;
}
public function createDirectory($dir, $sCreatefile){
if (!is_dir($dir.$sCreatefile)) {
mkdir($dir.$sCreatefile, 0755);
$this->sMessage = "Directory Created Successfully: \"$dir\" .";
}else{
$this->sError = "\"$dir\" Directory already exist.";
}
}
public function extract($sExtract){
$path_parts = pathinfo($sExtract);
if (is_writable($path_parts['dirname'])) {
$zip = new ZipArchive;
if ($zip->open($sExtract) === TRUE) {
$zip->extractTo($path_parts['dirname']);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
}
else{
$this->sError = "\"".$path_parts['dirname']."\" Directory is not writable..";
}
}
public function uploadFile($dir, $sFileName){
if (move_uploaded_file($_FILES['myfile']['tmp_name'], $dir.$sFileName)) {
$this->sMessage = "\"$sFileName\" File Successfully Uploaded.";
}
else{
$this->sError = "\"$sFileName\" Uploading Error.";
}
}
public function getCurrentDir($dir){
$aCurrentPath = explode($this->separator, $dir);
$iCount = (count($aCurrentPath) -1);
for ($i = 0; $i < $iCount; ++$i) {
$sFullPath .= $aCurrentPath[$i].$this->separator;
echo "<a href=/index.html"browser.php?dir=".urlencode($sFullPath)."\"><strong>".$aCurrentPath[$i]."<strong></a>".$this->separator;
}
}
public function readContent($sEdit, &$contents = null){
if (file_exists($sEdit)) {
$handle = fopen($sEdit, "r");
if ($handle) {
while (!feof($handle)) {
$contents .= fgets($handle, 4096);
}
fclose($handle);
}
}
}
}
调用示例:
<?php
ob_start();
session_start();
function __autoload($class_name) { require_once $class_name . '.Class.php';}
$oBrowser = new Browser(true);
$dir = trim($_REQUEST['dir']);
$sEdit = trim($_REQUEST['edit']);
$sExtract = trim($_REQUEST['extract']);
$sViewFile = trim($_REQUEST['view']);
if (!$dir) {
$dir = getcwd().$oBrowser->separator;
}else{
$dir = trim($_REQUEST['dir']).$oBrowser->separator;
}
$dir = str_replace($oBrowser->separator.$oBrowser->separator, $oBrowser->separator, $dir);
if ($_POST['button'] == "Delete Selected Files") {
$aFiles = $_POST['chkfiles'];
$oBrowser->deleteFiles($aFiles);
}
if ($_POST['button'] == "Create File") {
$sCreatefile = trim($_POST['createfile']);
$oBrowser->createFile($dir, $sCreatefile);
}
if ($_POST['button'] == "Create Directory") {
$oBrowser->createDirectory($dir, trim($_POST['createfile']));
}
$sDownloadFile = trim($_REQUEST['dwl']);
if ($sDownloadFile) {
$oBrowser->downloadFile($sDownloadFile);
exit;
}
if ($sExtract != "") {
$oBrowser->extract($sExtract);
}
if ($_POST['button'] == 'SAVEFILE') {
$bBackup = trim($_POST['Write_backup']);
$sFileData = trim($_POST['editfile']);
$oBrowser->fileWriter($sEdit, $sFileData, $bBackup);
}
$sFileName = $_FILES['myfile']['name'];
if ($sFileName) {
$oBrowser->uploadFile($dir, $sFileName);
}
if ($sViewFile) {
$oBrowser->viewFile($sViewFile);
exit;
}
$sFiles = scandir(urldecode($dir));
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex">
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
<style type="text/css">
body {font-family:sans-serif; font-size: 10pt; color: #000000;}
input {background-color: #efefef; color: #000000;}
.border {margin: 1px; background-color:#ffffff; padding: 1em; border:1px solid #000000;}
a {text-decoration:none; }
a:hover { color : red; text-decoration : underline; }
table.filelisting {background-color:#000000; width:100%; border:0px none #ffffff;}
th {background-color:#f1f1f1;}
td{background-color:#ffffff;padding-left:5px;font-family:sans-serif; font-size: 9pt; color: #000000;}
.message{border: 1px solid #ffaaaa;background-color: #acffaa;padding:3px 3px 3px 5px;font-size: 9pt;color:#000;text-align:center;}
.error{border: 1px solid #acffaa;background-color: #ffaaaa;padding:3px 3px 3px 5px;font-size: 10pt;color:#000;text-align:center;}
</style>
<script type="text/javascript">
function filter (begriff) {
var suche = begriff.value.toLowerCase();
var table = document.getElementById("filetable");
var ele;
for(var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].cells[1].innerHTML.replace(/<[^>]+>/g,"");
if(ele.toLowerCase().indexOf(suche)>=0 )
table.rows[r].style.display = '';
else table.rows[r].style.display = 'none';
}
}
function selectAll(obj) {
var oFileList = obj.elements['chkfiles[]'];
for(i=0; i < oFileList.length; ++i) {
if(obj.selall.checked == true)
oFileList[i].checked = true;
else
oFileList[i].checked = false;
}
}
</script>
<title>PHP File Browser V. 1.1</title>
</head>
<body>
<?php
if ($oBrowser->sError) {
echo "<p error\">".$oBrowser->sError."</p>";
}
if ($oBrowser->sMessage) {
echo "<p message\">".$oBrowser->sMessage."</p>";
}
?>
<?php
if ($_GET['cmd'] == 'ssh') {
$sSsh_command = trim($_POST['ssh_command']);
if ($sSsh_command) {
$aResult = array();
exec($sSsh_command, $aResult);
}
?>
<div>
<div>
<form name="frmSsh" method="post">
Command: <input type="text" value="<?php echo stripslashes($_POST['ssh'])?>" name="ssh_command" size="70"><input type="submit" value="GO"/>
</form>
</div>
<br/>
<div>
<?php
if (is_array($aResult)) {
foreach ($aResult as $resultVal){
echo $resultVal."<br/>";
}
}
?>
</div>
</div>
<?php
}
elseif($sEdit != "") {
$oBrowser->readContent($sEdit, $contents);
?>
<div>
<div >
<form name="frmedit" method="post">
<p>
<strong>File Name: <?php echo basename($sEdit)?></strong>
</p>
<textarea name="editfile" ><?php echo htmlentities($contents)?></textarea>
<p>
<input type="text" name="button" value="SAVEFILE" />
<input type="checkbox" name="Write_backup" value="1" id="Write_backup" title="Write backup"/>
<label for="Write_backup">
<strong>Write backup</strong>
</label>
<br/>
</p>
<p>
<input type="submit" value="SAVE"/>
</p>
</form>
</div>
</div>
<?php }else{?>
<div>
<div >
<form action="/blog_article/browser.html" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="dir" value="<?php echo $dir;?>" />
<input type="file" onKeypress="event.cancelBubble=true;" name="myfile">
<input title="Upload selected file to the current working directory" type="Submit" name="Submit" value="Upload"/>
</p>
<p>
<input type="button" name="button" value="Launch Shell Program" onclick="window.location = 'browser.php?cmd=ssh'">
</p>
</form>
</div>
<br/>
<form action="/blog_article/browser.html" method="Post" name="filelist" >
Filename filter:
<input name="filt" onKeypress="event.cancelBubble=true;" onkeyup="filter(this)" type="text">
<br />
<br />
<table id="filetable" border="0" cellpadding="0px" cellspacing="1px" width="100%" >
<tr >
<th></th>
<th>Name</th>
<th>Size</th>
<th>Type</th>
<th>Date</th>
<th> </th>
<th> </th>
</tr>
<?php
if (is_array($sFiles)) {
foreach ($sFiles as $file){
//if ($file != "." && $file != "..") {
?>
<tr >
<td>
<?php if ($file != "." && $file != "..") {?><input type="checkbox" id="chkfiles[]" name="chkfiles[]" value="<?php echo $file?>"/><?php } ?>
</td>
<td><?php echo $oBrowser->fileName($file, $dir);?></td>
<td><?php echo $oBrowser->showFileSize($file, $dir);?></td>
<td><?php echo substr(strrchr($dir.$file,'.'),1);?></td>
<td><?php $aFileInfo = stat($dir.$file); echo $oBrowser->dateFormat($aFileInfo['atime'])?></td>
<td><?php echo $oBrowser->showDownload($file, $dir);?></td>
<td><?php echo $oBrowser->showEdit($file, $dir);?></td>
</tr>
<?php } } ?>
<tr >
<td colspan="7">
<input type="checkbox" id="selall" name="selall" onClick="selectAll(this.form)">
<label for="selall">
Select All
</label>
</td>
</tr>
</table>
<br/>
<p>
<input type="text" name="dir" value="<?php echo $dir;?>" />
<input title="Delete selected files and directories." type="Submit" onclick="return confirm('Are you sure want to delete selected files');" name="button" value="Delete Selected Files">
<!--input title="Download selected files and directories as one zip file" id="but_Zip" type="Submit" name="Submit" value="Download selected files as zip"-->
</p>
<p>
Current Location: <?php echo $oBrowser->getCurrentDir($dir); ?>
</p>
<p>
<input type="text" name="createfile">
<input title="Create directory." type="Submit" name="button" value="Create Directory">
<input title="Create File." type="Submit" name="button" value="Create File">
</p>
</form>
</div>
<?php }?>
</body>
</html>
说明:
默认的用户名与密码为:
Password: password
在php中作整数转换时,一般会用(int),另外的强制类型转换方式,还有float, string, array等。
而intval(),如果参数是字符串,则返回字符串中第一个不是数字的字符之前的数字串所代表的整数值。
如果字符串第一个是‘-',则从第二个开始算起。
如果参数是符点数,则返回他取整之后的值。
例如:
<?php
intval("A")=0;
intval(12.3223)=12;
intval("1123Asdfka3243")=1123;
$a=0.99;
$b=(int)$a; //$b=0;
$a=1.99;
$b=(int)$a; //$b=1;
分享一段代码,可用于查询指定域名服务器的域信息,即whois信息查询。
Whois协议(由RFC3912定义)可能是最简单的互联网协议之一。
事实上,whois客户端需要打开TCP连接到端口43,发送查询,发送CR-LF(“\ R\ N”不变),然后接收响应。
代码:
<?php
/**
* whois信息查询
* by www.
*/
function ae_whois($query, $server)
{
define('AE_WHOIS_TIMEOUT', 15); // connection timeout
global $ae_whois_errno, $ae_whois_errstr;
// connecting
$f = fsockopen($server, 43, $ae_whois_errno, $ae_whois_errstr, AE_WHOIS_TIMEOUT);
if (!$f)
return false; // connection failed
// sending query
fwrite($f, $query."\r\n");
// receving response
$response = '';
while (!feof($f))
$response .= fgets($f, 1024);
// closing connection
fclose($f);
return $response;
}
?>
以上代码,实现了一个whois查询函数,包括两个参数$query(whois查询信息)、$server(域名服务器)。
该函数返回服务器的响应信息,失败则返回false。
fsockopen错误代码与错误消息,将写入到全局变量$ae_whois_errno与$ae_whois_errstr中。
大家可以更改常量AE_WHOIS_TIMEOUT来设置查询超时时间。
例子,用于获取域名的域名服务器信息。
代码:
// whois 信息查询
echo ae_whois('', 'whois.verisign-grs.com');
?>
您可能感兴趣的文章:
PHP获取域名的几个全局变量
php 实现dns域名查询的方法详解(图文)
php 从url中获取域名的实例代码
php获取站点的来路域名的方法
探讨:PHP获取域名及域名IP地址的方法
php获取URL中domain域名的代码一例
PHP正则匹配获取URL中域名的代码
PHP获取当前网址及域名的代码
php正则表达式匹配URL中的域名
PHP调用万网接口实现域名查询的功能