Вход Регистрация
Файл: train.php
Строк: 142
<?php

/**
 * @author Oleg Isaev
 * @contacts vk.com/id50416641, t.me/pandcar, github.com/pandcar
 */

error_reporting(0);
set_time_limit(3600);
ob_start();
session_start();

// Пароль для входа
$password '12345';

// Если папка в которой находится этот скрипт закрыта для записи, укажите здесь путь для временных файлов
$tmp_path null;

$title 'Train '.$_SERVER['HTTP_HOST'];

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $title ?></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <style>
        body, input {
            font-family: monospace, Verdana, Arial, Tahoma, Sans-Serif;
        }
        input[type="text"] {
            padding: 4px
        }
        .seri {
            color:#999999
        }
        .small {
            font-size: small;
        }
        .blackout {
            z-index: 100;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }
        .blackout-content {
            position: absolute; 
            color: #ffffff;
            width:100%; 
            top:50%; 
            text-align:center;
        }
        .mb-3 {margin-bottom: 3px !important;}
        .mb-5 {margin-bottom: 5px !important;}
        .mb-8 {margin-bottom: 8px !important;}
        .mb-10 {margin-bottom: 10px !important;}
        .mb-15 {margin-bottom: 15px !important;}
    </style>
<?php

if (isset($_SESSION['msg']))
{
    echo 
'<div class="mb-15">'.$_SESSION['msg'].'</div>';
    unset(
$_SESSION['msg']);
}

if (! isset(
$_SESSION['tr_auth']) || $_SESSION['tr_auth'] != $password)
{
    if (isset(
$_POST['ok_pass']))
    {
        if (
mb_strtoupper($_POST['password']) == mb_strtoupper($password)) {
            
$_SESSION['tr_auth'] = $password;
        } else {
            
msg('Неверный пароль');
        }
        
        
redirect('?');
    }
    
    
?>
    <form method="post">
        <div class="mb-8">Введите пароль:<br><input type="text" name="password"></div>
        <div><input type="submit" name="ok_pass" value="Вход"></div>
    </form>
    <?php
    
    
goto dot_end;
}

if (isset(
$_GET['logout']))
{
    unset(
$_SESSION['tr_auth']);
    
redirect('?');
}

if (! 
class_exists('ZipArchive'))
{
    echo 
'<div class="mb-10" style="color:red">Подключите класс ZipArchive, без него штатное функционирование инструмента невозможно.</div>';
}

if (isset(
$_POST['submit-import']))
{
    
$tmp = (! empty($tmp_path) ? $tmp_path __DIR__) .'/tmp'.time().'.zip';
    
$save normal_dir_path($_POST['path']);
    
    try {
        
load_file_url($tmp$_POST['url']);
        
        
mkdir_rec($save);
        
        
zip_unpack($tmp$save);
        
        
msg('Архив успешно загружен и рапакован');
    }
    catch (
Exception $e) {
        
msg$e->getMessage() );
    }
    
    if (
file_exists($tmp))
    {
        
unlink($tmp);
    }
    
    
redirect('?');
}

if (isset(
$_POST['submit-create']))
{
    
$get normal_dir_path($_POST['get-path']);
    
$save normal_dir_path($_POST['save-path']);
    
    try {
        
mkdir_recdirname($save) );
        
        
zip_create($get$save);
        
        
msg('Архив успешно создан');
    }
    catch (
Exception $e) {
        
msg$e->getMessage() );
    }
    
    
redirect('?');
}

?>
<div class="mb-10"><b><?= $title ?></b></div>
<div class="mb-15">
    <div><a href="?logout">Выйти</a></div>
    <div><a href="#" class="menu" data-act="import">Импортировать и распокавать .zip</a></div>
    <div><a href="#" class="menu" data-act="create">Создать .zip</a></div>
</div>
<div class="act import">
    <div class="mb-8"><b>Импортировать и распокавать .ZIP</b></div>
    <form method="post">
        <div class="mb-8">
            <div class="mb-3">URL:<br><span class="seri small">http://ваш-сайт.ru/folder/имя-архива.zip</span></div>
            <div><input type="text" name="url" size="60" value=""></div>
        </div>
        <div class="mb-8">
            <div class="mb-3">Распокавать в:<br><span class="seri small">/var/www/html/имя-папки</span></div>
            <div><input type="text" name="path" size="60" value="<?= $_SERVER['DOCUMENT_ROOT'?>"></div>
        </div>
        <div><input type="submit" name="submit-import" value="Загрузить"></div>
    </form>
</div>
<div class="act create" style="display:none">
    <div class="mb-8"><b>Создать .ZIP</b></div>
    <form method="post">
        <div class="mb-8">
            <div class="mb-3">Путь к папке или файлу:<br><span class="seri small">/var/www/html/имя-папки</span></div>
            <div><input type="text" name="get-path" size="60" value="<?= $_SERVER['DOCUMENT_ROOT'?>"></div>
        </div>
        <div class="mb-8">
            <div class="mb-3">Сохранить архив как:<br><span class="seri small">/var/www/html/имя-архива.zip</span></div>
            <div><input type="text" name="save-path" size="60" value="<?= $_SERVER['DOCUMENT_ROOT'?>"></div>
        </div>
        <div><input type="submit" name="submit-create" value="Создать"></div>
    </form>
</div>
<br>
<div>
Инструкция<br>
1. Сразу смените пароль! (в начале $password)<br>
2. Если папка в которой находится этот скрипт закрыта для записи, пропишите путь для временных файлов (в начале $tmp_path)<br>
3. Пути рекомендуется указывать полные<br>
4. Папки сохренений создаются рекурсивно если их нет<br>
</div>
<script>
    $(".menu").click(function(){
        $(".act").hide();
        $(".act." + $(this).attr("data-act")).show();
        return false;
    });
    
    $("form").submit(function(){
        $("html,body").css("overflow","hidden");
        $("#now-load").show();
    });
</script>
<?php

dot_end
:

?>
    <div id="now-load" class="blackout" style="display:none">
        <div class="blackout-content">
            Загрузка...
        </div>
    </div>
</body>
</html>
<?php

function msg($string)
{
    
$_SESSION['msg'] = $string;
}

function 
redirect($url)
{
    
header('Location: '.$url);
    exit;
}

function 
mkdir_rec($path)
{
    if (! 
file_exists($path))
    {
        if (! 
mkdir($path0755true))
        {
            throw new 
Exception('Не удалось создать директории...');
        }
    }
}

function 
normal_dir_path($path)
{
    return 
preg_replace('~/+$~i'''str_replace('\', '/', $path));
}

function load_file_url($filename, $url)
{
    if (! $fp = fopen($filename, "w+"))
    {
        throw new Exception('
Ошибка при создании файла');
    }
    
    if (! $ch = curl_init())
    {
        throw new Exception('
ОшибкаcURL не инициировался');
    }
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_exec($ch);
    curl_close($ch);
    
    fclose($fp);
    
    return true;
}

function zip_unpack($zip_path, $save_path)
{
    $zip = new ZipArchive;
    
    if ($zip->open($zip_path) !== true)
    {
        throw new Exception('
Ошибка чтения архива');
    }
    
    $zip->extractTo($save_path);
    $zip->close();
    
    return true;
}

function zip_create($get_path, $save_path)
{
    //создание zip архива
    $zip = new ZipArchive();
    
    if ($zip->open($save_path, ZIPARCHIVE::CREATE) !== true)
    {
        throw new Exception('
Ошибка при создании файла архива');
    }
    
    $filerecmap = function($path, $base_path = false) use (&$filerecmap, &$zip)
    {
        if (! $base_path) $base_path = $path;
        
        if ($handle = opendir($path))
        {
            while (false !== ($file = readdir($handle)))
            {
                if ($file != '
.' && $file != '..')
                {
                    $scrap = str_replace($base_path, '', $path.'
/'.$file);
                    
                    $scrap = trim($scrap, '
/');
                    
                    $scrap = iconv('
utf-8', 'cp866', $scrap);
                    
                    if (is_file($path.'
/'.$file))
                    {
                        $zip->addFile($path.'
/'.$file, $scrap);
                    }
                    else
                    {
                        $zip->addEmptyDir($scrap);
                        
                        $filerecmap($path.'
/'.$file, $base_path);
                    }
                }
            }
            
            closedir($handle);
        }
    };
    
    $filerecmap($get_path);
    
    //закрываем архив
    $zip->close();
    
    return true;
}
Онлайн: 1
Реклама