Dienstag, 11 November 2025

Top 5 diese Woche

Ähnliche Tutorials

Modular File System

Dieses Dreamcodes Script ist ein selbstinstallierendes Mini Framework, um dir in Sekundenschnelle eine komplette, funktionsfähige Entwicklungsumgebung bereitzustellen. Nach dem ersten Start richtet sich alles automatisch ein: Ordner, Module, Templates, Design-Dateien und eine intuitive Weboberfläche.

Damit kannst du Dateien direkt im Browser erstellen, bearbeiten, speichern und versionieren, ohne zusätzliche Software oder Datenbanken. Alles läuft in einer einzigen PHP-Datei, die sich selbst organisiert und ein professionelles, modernes Layout mitbringt.

<?php
session_start();
date_default_timezone_set('Europe/Berlin');
$SITE_TITLE = "Modular File Creator";
$LINK_DREAMCODES = "http://www.dreamcodes.net";
$ADMIN_USER = "admin";
$ADMIN_PASS = "secret";-
$INSTALL_MARKER = __DIR__ . '/.dreamcodes_installed';
$BASE = __DIR__;
$ALLOWED_EXT = ['html','css','js','php','txt','json','md'];
$DIRS = [
    'assets',
    'assets/css',
    'assets/js',
    'templates',
    'modules',
    'history',
    'data',
];
function safe_filename($name) {
    // Remove path traversals and invalid chars, allow dots
    $name = basename($name);
    $name = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $name);
    return $name;
}
function ext_of($name) {
    return strtolower(pathinfo($name, PATHINFO_EXTENSION));
}
function send_flash($msg, $type='ok') {
    $_SESSION['flash'] = ['msg'=>$msg,'type'=>$type];
}
function get_and_clear_flash() {
    if(isset($_SESSION['flash'])) {
        $f = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $f;
    }
    return null;
}
function ensure_dirs($dirs) {
    foreach($dirs as $d) {
        if(!is_dir($d)) mkdir($d, 0755, true);
    }
}
function is_allowed_ext($name, $allowed) {
    $ext = ext_of($name);
    return in_array($ext, $allowed);
}
function list_files_dir($dir) {
    $items = array_diff(scandir($dir), ['.','..']);
    $files = [];
    foreach($items as $it) {
        if(is_file($dir . '/' . $it)) $files[] = $it;
    }
    return $files;
}
if(!file_exists($INSTALL_MARKER)) {
    ensure_dirs($DIRS);
    file_put_contents('assets/css/style.css', <<<CSS
:root{--bg:#f5f7fb;--card:#fff;--accent:#0a74da;--muted:#6b7280}
*{box-sizing:border-box}body{font-family:Inter,Segoe UI,Helvetica,Arial,sans-serif;background:var(--bg);margin:0;color:#111}
header{background:linear-gradient(90deg,var(--accent),#005bb5);color:white;padding:18px 28px}
.container{max-width:1100px;margin:28px auto;padding:0 18px}
.grid{display:grid;grid-template-columns:1fr 360px;gap:20px}
.card{background:var(--card);padding:18px;border-radius:12px;box-shadow:0 6px 20px rgba(2,6,23,0.06)}
.field{margin-bottom:12px}
input[type=text],textarea,select{width:100%;padding:10px;border:1px solid #e6e9ef;border-radius:8px}
button{background:var(--accent);color:white;padding:10px 14px;border-radius:8px;border:0;cursor:pointer}
.small{font-size:13px;color:var(--muted)}
.files-list a{display:block;padding:8px;border-radius:8px;text-decoration:none;color:var(--accent)}
.version-link{display:flex;justify-content:space-between;align-items:center;padding:8px;border-radius:8px;background:#f8fafc;margin:6px 0}
.preview-iframe{width:100%;height:300px;border:1px solid #e6e9ef;border-radius:8px}
.footer{padding:18px;text-align:center;color:#6b7280;font-size:13px}
.upload-drop{border:2px dashed #e6e9ef;border-radius:8px;padding:18px;text-align:center;color:var(--muted)}
CSS
    );
    file_put_contents('assets/js/app.js', <<<JS
function enableDropZone() {
    var dz = document.getElementById('dropzone');
    if(!dz) return;
    dz.addEventListener('dragover', function(e){ e.preventDefault(); dz.classList.add('dragover'); });
    dz.addEventListener('dragleave', function(e){ dz.classList.remove('dragover'); });
    dz.addEventListener('drop', function(e){
        e.preventDefault(); dz.classList.remove('dragover');
        var f = e.dataTransfer.files[0];
        if(!f) return;
        var input = document.getElementById('upload_file');
        // populate FileList not trivial; fallback: notify user to use form
        alert('Drag & Drop erkannt. Wähle die Datei im Upload-Formular oder nutze den normalen Upload-Button.');
    });
}
function insertTemplate(tpl) {
    var content = document.getElementById('content');
    if(!content) return;
    content.value = tpl;
}
function previewContent() {
    var type = document.getElementById('filetype').value;
    var cont = document.getElementById('content').value;
    var iframe = document.getElementById('preview');
    if(!iframe) return;
    if(type === 'html') {
        iframe.srcdoc = cont;
    } else if(type === 'css') {
        iframe.srcdoc = '<!doctype html><html><head><style>'+cont+'</style></head><body><div style=\"padding:20px\">CSS Vorschau</div></body></html>';
    } else if(type === 'js') {
        iframe.srcdoc = '<!doctype html><html><head></head><body><script>'+cont+'</script></body></html>';
    } else {
        alert('Live Vorschau nur für HTML/CSS/JS.');
    }
}
document.addEventListener('DOMContentLoaded', function(){ enableDropZone(); });
JS
    );
    file_put_contents('templates/default.html', <<<HTML
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>Beispiel</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
  <h1>Hallo von Dreamcodes</h1>
  <p>Dies ist ein Beispiel-Template.</p>
</body>
</html>
HTML
    );
    file_put_contents('templates/style.css', <<<CSS
body{font-family:Arial,Helvetica,sans-serif;background:#fff;color:#111}
h1{color:#0a74da}
CSS
    );
    file_put_contents('templates/app.js', "console.log('Dreamcodes template loaded');");
    file_put_contents('modules/editor.php', <<<'PHP'
<?php
// modules/editor.php - simple editor module (included by master)
if(!defined('DREAMCODES_MASTER')) die('no direct');
?>
<div class="card">
  <h3>Datei erstellen / bearbeiten</h3>
  <form method="post" id="createForm" onsubmit="return true;">
    <div class="field">
      <label class="small">Dateiname</label>
      <input type="text" name="filename" placeholder="z.B. index.html" required>
    </div>
    <div class="field">
      <label class="small">Typ</label>
      <select id="filetype" name="filetype" onchange="">
        <option value="html">HTML</option>
        <option value="css">CSS</option>
        <option value="js">JS</option>
        <option value="php">PHP</option>
        <option value="txt">TXT</option>
      </select>
    </div>
    <div class="field">
      <label class="small">Inhalt</label>
      <textarea id="content" name="content" rows="12" required></textarea>
    </div>
    <div style="display:flex;gap:8px">
      <button type="button" onclick="previewContent()">Live-Vorschau</button>
      <button type="submit" name="create_file">Speichern</button>
    </div>
  </form>
  <iframe id="preview" class="preview-iframe"></iframe>
</div>
PHP
    );
    file_put_contents('modules/upload.php', <<<'PHP'
<?php
// modules/upload.php - upload UI
if(!defined('DREAMCODES_MASTER')) die('no direct');
?>
<div class="card">
  <h3>Datei hochladen</h3>
  <div id="dropzone" class="upload-drop">Ziehen & Ablegen oder Datei wählen</div>
  <form method="post" enctype="multipart/form-data">
    <div class="field">
      <input type="file" id="upload_file" name="upload_file" required>
    </div>
    <div>
      <button type="submit">Hochladen</button>
    </div>
  </form>
</div>
PHP
    );
    file_put_contents('modules/history.php', <<<'PHP'
<?php
// modules/history.php - history list partial
if(!defined('DREAMCODES_MASTER')) die('no direct');
?>
<div class="card">
  <h3>Datei-Historie</h3>
  <?php
  $files = array_diff(scandir(__DIR__.'/../'), ['.','..', basename(__FILE__)]);
  ?>
  <div class="small">Nutze die Seitenleiste für Details.</div>
</div>
PHP
    );

    file_put_contents('modules/api.php', <<<'PHP'
<?php
// modules/api.php - tiny API endpoints (call via GET params)
if(!defined('DREAMCODES_MASTER')) die('no direct');
if(isset($_GET['cmd']) && $_GET['cmd'] === 'listFiles') {
    header('Content-Type: application/json');
    $files = array_values(array_diff(scandir(__DIR__.'/../'), ['.','..', basename(__FILE__)]));
    echo json_encode($files);
    exit;
}
PHP
    );
    file_put_contents($INSTALL_MARKER, "installed: " . date('c') . PHP_EOL);
}
define('DREAMCODES_MASTER', true);
if(!isset($_SESSION['user'])) {
    if(isset($_POST['login'])) {
        $u = trim($_POST['username'] ?? '');
        $p = trim($_POST['password'] ?? '');
        if($u === $ADMIN_USER && $p === $ADMIN_PASS) {
            $_SESSION['user'] = $u;
            send_flash('Erfolgreich angemeldet.');
            header("Location: " . $_SERVER['PHP_SELF']); exit;
        } else {
            send_flash('Falsche Anmeldedaten.', 'err');
        }
    }
}
if(isset($_GET['logout'])) {
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']); exit;
}
ensure_dirs($DIRS);
$flash = null;
if(isset($_POST['create_file'])) {
    $rawname = $_POST['filename'] ?? '';
    $filename = safe_filename($rawname);
    $content = $_POST['content'] ?? '';
    if($filename === '') {
        send_flash('Ungültiger Dateiname.', 'err');
    } elseif(!is_allowed_ext($filename, $ALLOWED_EXT)) {
        send_flash('Dateiendung nicht erlaubt.', 'err');
    } else {
        // backup current to history
        if(file_exists($filename)) {
            $ts = date('Ymd_His');
            $base = pathinfo($filename, PATHINFO_FILENAME);
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            $backup = "history/{$base}_{$ts}.{$ext}";
            copy($filename, $backup);
        }
        // write new content
        if(file_put_contents($filename, $content) !== false) {
            send_flash("Datei '$filename' gespeichert und gesichert.");
        } else {
            send_flash("Fehler beim Schreiben von '$filename'.", 'err');
        }
    }
    header("Location: " . $_SERVER['PHP_SELF']); exit;
}

if(isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === 0) {
    $orig = $_FILES['upload_file']['name'];
    $safe = safe_filename($orig);
    if($safe === '') {
        send_flash('Ungültiger Dateiname beim Upload.', 'err');
    } elseif(!is_allowed_ext($safe, $ALLOWED_EXT)) {
        send_flash('Upload-Typ nicht erlaubt.', 'err');
    } else {
        if(move_uploaded_file($_FILES['upload_file']['tmp_name'], $safe)) {
            send_flash("Datei '$safe' erfolgreich hochgeladen.");
        } else send_flash("Fehler beim Hochladen von '$safe'.", 'err');
    }
    header("Location: " . $_SERVER['PHP_SELF']); exit;
}
if(isset($_GET['restore']) && isset($_GET['file'])) {
    $restore = safe_filename($_GET['restore']);
    $original = safe_filename($_GET['file']);
    $restorePath = "history/{$restore}";
    if(!file_exists($restorePath) || !file_exists($original)) {
        send_flash('Wiederherstellung fehlgeschlagen: Dateipfad ungültig.', 'err');
    } else {
        $ts = date('Ymd_His');
        $base = pathinfo($original, PATHINFO_FILENAME);
        $ext = pathinfo($original, PATHINFO_EXTENSION);
        $bak = "history/{$base}_{$ts}.{$ext}";
        copy($original, $bak);
        if(copy($restorePath, $original)) {
            send_flash("Datei '$original' auf Version '$restore' zurückgesetzt.");
        } else send_flash('Fehler beim Zurücksetzen.', 'err');
    }
    header("Location: " . $_SERVER['PHP_SELF']); exit;
}
function render_file_list($dir = '.') {
    $items = array_diff(scandir($dir), ['.','..', basename(__FILE__)]);
    $out = [];
    foreach($items as $it) {
        if(is_file($dir . '/' . $it)) $out[] = $it;
    }
    sort($out);
    return $out;
}
function get_versions_for($file) {
    $name = pathinfo($file, PATHINFO_FILENAME);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $matches = glob("history/{$name}_*.{$ext}");
    rsort($matches);
    return $matches ?: [];
}
$flash = get_and_clear_flash();
?><!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>Dreamcodes - <?php echo htmlspecialchars($SITE_TITLE); ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="assets/css/style.css?ver=1">
  <script src="assets/js/app.js?ver=1" defer></script>
  <style>
    /* small extra styles inline for master layout */
    .sidebar {position:sticky; top:20px;}
    .files-list {max-height:420px; overflow:auto}
    .login-box {max-width:420px; margin:40px auto}
  </style>
</head>
<body>
<header>
  <div style="max-width:1100px;margin:0 auto;display:flex;align-items:center;justify-content:space-between">
    <div>
      <strong style="font-size:18px">Dreamcodes</strong> <span class="small">Modular File Creator</span>
    </div>
    <div class="small"><?php echo htmlspecialchars(date('d.m.Y H:i')); ?></div>
  </div>
</header>

<div class="container">
<?php if(!isset($_SESSION['user'])): ?>
  <div class="card login-box">
    <h2>Anmelden</h2>
    <?php if($flash): ?>
      <div class="<?php echo $flash['type'] === 'err' ? 'error' : 'message'; ?>"><?php echo htmlspecialchars($flash['msg']); ?></div>
    <?php endif; ?>
    <form method="post">
      <div class="field"><input type="text" name="username" placeholder="Benutzer" required></div>
      <div class="field"><input type="password" name="password" placeholder="Passwort" required></div>
      <div><button type="submit" name="login">Login</button></div>
    </form>
    <div class="small" style="margin-top:12px">Demo-Anmeldedaten: <?php echo $ADMIN_USER; ?> / <?php echo $ADMIN_PASS; ?></div>
  </div>
<?php else: ?>
  <div style="display:flex;gap:20px;align-items:flex-start">
    <div style="flex:1">
      <?php if($flash): ?>
        <div class="<?php echo $flash['type'] === 'err' ? 'error' : 'message'; ?>"><?php echo htmlspecialchars($flash['msg']); ?></div>
      <?php endif; ?>
      <?php if(file_exists('modules/editor.php')) include 'modules/editor.php'; else: ?>
        <!-- fallback editor if module missing -->
        <div class="card">
          <h3>Datei erstellen</h3>
          <form method="post">
            <div class="field"><input type="text" name="filename" placeholder="Dateiname" required></div>
            <div class="field">
              <select id="filetype" name="filetype">
                <option value="html">HTML</option><option value="css">CSS</option><option value="js">JS</option><option value="php">PHP</option>
              </select>
            </div>
            <div class="field"><textarea id="content" name="content" rows="12" required></textarea></div>
            <div style="display:flex;gap:8px"><button type="button" onclick="previewContent()">Live-Vorschau</button><button type="submit" name="create_file">Speichern</button></div>
          </form>
          <iframe id="preview" class="preview-iframe"></iframe>
        </div>
      <?php endif; ?>
      <?php if(file_exists('modules/upload.php')) include 'modules/upload.php'; else: ?>
        <div class="card">
          <h3>Upload</h3>
          <form method="post" enctype="multipart/form-data">
            <div class="field"><input type="file" name="upload_file" required></div>
            <div><button type="submit">Hochladen</button></div>
          </form>
        </div>
      <?php endif; ?>
      <div class="card">
        <h3>History & Wiederherstellung</h3>
        <div class="small">Klicke "Vorschau" um ältere Versionen anzusehen. "Wiederherstellen" setzt sie zurück.</div>
        <?php
          $allFiles = render_file_list('.');
          if(empty($allFiles)) {
            echo "<div class='small'>Keine Dateien vorhanden.</div>";
          } else {
            foreach($allFiles as $f) {
              echo "<div style='margin-top:10px'><strong>" . htmlspecialchars($f) . "</strong>";
              $versions = get_versions_for($f);
              if(!$versions) {
                echo "<div class='small'>Keine Versionen</div>";
              } else {
                foreach($versions as $v) {
                  $bn = basename($v);
                  // show preview link using src to file and restore link
                  echo "<div class='version-link'>";
                  echo "<span class='small'>".htmlspecialchars($bn)."</span>";
                  echo "<span style='display:flex;gap:8px'>";
                  echo "<a class='small' href='$v' target='_blank'>Vorschau</a>";
                  echo "<a class='small' href='?restore=".urlencode($bn)."&file=".urlencode($f)."' onclick='return confirm(\"Version wiederherstellen? Dies sichert die aktuelle Version zuerst.\")'>Wiederherstellen</a>";
                  echo "</span></div>";
                }
              }
              echo "</div>";
            }
          }
        ?>
      </div>
    </div>
    <aside style="width:360px" class="sidebar">
      <div class="card files-list">
        <h3>Bestehende Dateien</h3>
        <?php
          $files = render_file_list('.');
          if(!$files) echo "<div class='small'>Keine Dateien</div>";
          else {
            foreach($files as $fi) {
              $ext = ext_of($fi);
              $icon = in_array($ext, ['php']) ? 'PHP' : strtoupper($ext);
              echo "<a href='".htmlspecialchars($fi)."' target='_blank' class='files-list'><div style='display:flex;justify-content:space-between;align-items:center;padding:8px 4px'><div><strong>$fi</strong><div class='small'>.$ext</div></div><div class='small'>$icon</div></div></a>";
            }
          }
        ?>
      </div>
      <div class="card">
        <h3>Vorlagen</h3>
        <?php
          $tpls = list_files_dir('templates');
          if(!$tpls) echo "<div class='small'>Keine Templates</div>";
          else {
            foreach($tpls as $t) {
              $content = htmlspecialchars(file_get_contents('templates/'.$t));
              // We provide quick insert links
              echo "<div style='margin-bottom:6px'>";
              echo "<div class='small'>".htmlspecialchars($t)."</div>";
              echo "<div style='display:flex;gap:6px;margin-top:6px'><button onclick=\"insertTemplate(`".addslashes($content)."`)\">Einfügen</button>";
              echo "<a class='small' href='templates/".urlencode($t)."' target='_blank' style='align-self:center;margin-left:6px'>Ansehen</a></div>";
              echo "</div>";
            }
          }
        ?>
      </div>
      <div class="card">
        <h3>Aktionen</h3>
        <div class="small" style="margin-bottom:8px">Schnellaktionen:</div>
        <div style="display:flex;flex-direction:column;gap:8px">
          <a href="?logout=1"><button>Abmelden</button></a>
          <a href="<?php echo htmlspecialchars($LINK_DREAMCODES); ?>" target="_blank"><button>Mehr von Dreamcodes</button></a>
        </div>
      </div>
      <div class="card">
        <h3>Info</h3>
        <div class="small">Self-install: <?php echo htmlspecialchars(file_exists($INSTALL_MARKER) ? 'fertig' : 'ausstehend'); ?></div>
      </div>
    </aside>
  </div>
<?php endif; ?>
  <div class="footer">
    &copy; <?php echo date('Y'); ?> | <a href="<?php echo htmlspecialchars($LINK_DREAMCODES); ?>" target="_blank">Powered by Dreamcodes</a>
  </div>
</div>
</body>
</html>
Vorheriges Tutorial
Nächstes Tutorial

Lesetipps für dich