3v4l.org

run code in 300+ PHP versions simultaneously
<?php setlocale(LC_CTYPE, "ru_RU.UTF-8"); require '../include/config.php'; require '../include/functions.php'; session_start(); // Если пользователь не авторизован, но выставлена // cookie-переменная autologin - входим на форум if ( !isset( $_SESSION['user'] ) and isset( $_COOKIE['autologin'] ) ) autoLogin(); // Подключаем дополнительную таблицу стилей если передан параметр if ( !isset( $style ) ) { $style = '<style type="text/css">'."\r\n"; $style = $style. file_get_contents( '../style/admin.css' )."\r\n"; $style = $style.'</style>'."\r\n"; } // Загрузка шаблона и замена переменных $html = file_get_contents( '../templates/admin.html' ); $html = str_replace( '{title}', $pageTitle, $html ); $html = str_replace( '{description}', $description, $html ); $html = str_replace( '{nav}', $nav, $html ); $html = str_replace( '{content}', $content, $html ); $html = str_replace( '{style}', $style, $html ); echo $html; // Функция возвращает html формы для авторизации function getLoginForm( &$style ) { $html = $html.'<form class="form-signin" action="?action=login" method="post">'."\r\n"; if ( isset( $_SESSION['loginForm']['error'] ) ) { $info = file_get_contents( '../templates/info.html' ); $info = str_replace( '{infoMessage}', $_SESSION['loginForm']['error'], $info ); $html = $html.$info."\r\n"; unset( $_SESSION['loginForm']['error'] ); } $html = $html.'<h2 class="form-signin-heading">Вход</h2>'."\r\n"; $html = $html.' <input class="input-block-level" placeholder="Логин" name="login" type="text" size="15" maxlength="15">'."\r\n"; $html = $html.'<input class="input-block-level" placeholder="Пароль" name="password" type="password" size="15" maxlength="40">'."\r\n"; $html = $html.'<label class="checkbox">'."\r\n"; $html = $html.'<input name="autologin" type="checkbox" value="1"> Запомнить меня'."\r\n"; $html = $html.'</label>'."\r\n"; $html = $html.'<button class="btn btn-large btn-primary" type="submit" name="submit">Войти</button>'."\r\n"; $html = $html.'</form>'."\r\n"; $style = '<style type="text/css">'."\r\n"; $style = $style. file_get_contents( '../style/login.css' )."\r\n"; $style = $style.'</style>'."\r\n"; return $html; } // Обработчик формы авторизации function login() { global $connection; // Если не переданы данные формы - значит функция была вызвана по ошибке if ( !isset( $_POST['login'] ) or !isset( $_POST['password'] ) ) { header( 'Location: '.$_SERVER['PHP_SELF'] ); die(); } // Защита от перебора пароля - при каждой неудачной попытке время задержки увеличивается if ( isset( $_SESSION['loginForm']['count'] ) ) sleep( $_SESSION['loginForm']['count'] ); // Обрезаем переменные до длины, указанной в параметре maxlength тега input $login = substr( $_POST['login'], 0, 40 ); $password = substr( $_POST['password'], 0, 40 ); // Обрезаем лишние пробелы $login = trim( $login ); $password = trim( $password ); // Проверяем, заполнены ли обязательные поля $error = ''; if ( empty( $login ) ) $error = $error.'<li>не заполнено поле "Имя"</li>'."\r\n"; if ( empty( $password ) ) $error = $error.'<li>не заполнено поле "Пароль"</li>'."\r\n"; // Проверяем поля формы на недопустимые символы //if ( !empty( $name ) and !preg_match( "#^[- _0-9a-zА-Яа-я]+$#i", $name ) ) // $error = $error.'<li>поле "Имя" содержит недопустимые символы</li>'."\n"; //if ( !empty( $password ) and !preg_match( "#^[-_0-9a-z]+$#i", $password ) ) // $error = $error.'<li>поле "Пароль" содержит недопустимые символы</li>'."\n"; // Указываем "соль" для пароля и шифруем пароль $salt = "yD4@1bTySXq9vb"; $password = sha1($salt . $password); // Проверять существование такого пользователя есть смысл только в том // случае, если поля не пустые и не содержат недопустимых символов if ( empty( $error ) ) { // Выполняем запрос на получение данных пользователя из БД $query = "SELECT * FROM users WHERE login='".$login."' AND password='".$password."' LIMIT 1"; //извлекаем из базы все данные о пользователе с введенным логином $result = mysqli_query( $connection, $query ); if ( !$result ) { $msg = 'Ошибка при авторизации пользователя'; $err = 'Ошибка при выполнении запроса: <br/>'. $query.'<br/>'.mysqli_errno().':&nbsp;'.mysqli_error().'<br/>'.'(Файл '. __FILE__ .', строка '. __LINE__ .')'; return showErrorMessage( $msg, $err, true, 'action=loginForm' ); } if ( mysqli_num_rows( $result ) == 0 ) $error = $error.'<li>Неправильный логин или пароль</li>'."\n"; } // Если были допущены ошибки при заполнении формы if ( !empty( $error ) ) { if ( !isset( $_SESSION['loginForm']['count'] ) ) $_SESSION['loginForm']['count'] = 1; else $_SESSION['loginForm']['count'] = $_SESSION['loginForm']['count'] + 1; $_SESSION['loginForm']['error'] = '<br>'."\r\n".'При заполнениии формы были допущены ошибки:'. "\r\n".'<ul>'."\r\n".$error.'</ul>'."\r\n"; header( 'Location: '.$_SERVER['PHP_SELF'].'?action=loginForm' ); die(); } // Все поля заполнены правильно и такой пользователь существует - продолжаем unset( $_SESSION['loginForm'] ); $user = mysqli_fetch_assoc( $result ); if ( $user['activation'] == '0' ) return showInfoMessage( 'Ваша учетная запись не активирована', '' ); // Если пользователь заблокирован if ( $user['status'] != 'admin' ) return showInfoMessage( 'Недостаточно прав доступа. Обратитесь к администратору.', '' ); $_SESSION['user'] = $user; // Выставляем cookie, если пользователь хочет входить на форум автоматически if ( isset ( $_POST['autologin'] ) ) { $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); setcookie( 'autologin', 'yes', time() + 3600*24*30, $path ); setcookie( 'login', $_SESSION['user']['login'], time() + 3600*24*30, $path ); setcookie( 'password', $_SESSION['user']['password'], time() + 3600*24*30, $path ); } // Авторизация прошла успешно - перенаправляем посетителя на главную страницу header( 'Location: '.$_SERVER['PHP_SELF'].'?action=pages' ); die(); } // Функция осуществляет автоматический вход на форум function autoLogin() { global $connection; // Если не установлены cookie, содержащие логин и пароль if ( !isset( $_COOKIE['login'] ) or !isset( $_COOKIE['password'] ) ) { $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); if ( isset( $_COOKIE['login'] ) ) setcookie( 'login', '', time() - 1, $path ); if ( isset( $_COOKIE['password'] ) ) setcookie( 'password', '', time() - 1, $path ); if ( isset( $_COOKIE['autologin'] ) ) setcookie( 'autologin', '', time() - 1, $path ); return false; } // Проверяем переменные cookie на недопустимые символы //$login = preg_replace( "#[^- _0-9a-zА-Яа-я]#i", '', $_COOKIE['login'] ); $login = $_COOKIE['login']; // Т.к. пароль зашифрован с помощью sha1, то он представляет собой // 40-значное шестнадцатеричное число $password = substr( $_COOKIE['password'], 0, 40 ); //$password = preg_replace( "#[^0-9a-f]#i", '', $password ); // Выполняем запрос на получение данных пользователя из БД $query = "SELECT * FROM users WHERE login='".$login."' AND password='".$password."' LIMIT 1"; $result = mysqli_query( $connection, $query ); if ( !$result ) { $msg = 'Ошибка при авторизации пользователя'; $err = 'Ошибка при выполнении запроса: <br/>'. $query.'<br/>'.mysqli_errno().':&nbsp;'.mysqli_error().'<br/>'.'(Файл '. __FILE__ .', строка '. __LINE__ .')'; return showErrorMessage( $msg, $err, true, '' ); } // Если пользователь с таким логином и паролем не найден - // значит данные неверные и надо их удалить if ( mysqli_num_rows( $result ) == 0 ) { $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); setcookie( 'autologin', '', time() - 1, $path ); setcookie( 'login', '', time() - 1, $path ); setcookie( 'password', '', time() - 1, $path ); return false; } $user = mysqli_fetch_assoc( $result ); if ( $user['activation'] == '0' ) { $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); setcookie( 'autologin', '', time() - 1, $path ); setcookie( 'login', '', time() - 1, $path ); setcookie( 'password', '', time() - 1, $path ); return showInfoMessage( 'Ваша учетная запись не активирована', '' ); } if ( $user['status'] != 'admin' ) { $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); setcookie( 'autologin', '', time() - 1, $path ); setcookie( 'login', '', time() - 1, $path ); setcookie( 'password', '', time() - 1, $path ); return showInfoMessage( 'Недостаточно прав доступа. Обратитесь к администратору.', '' ); } $_SESSION['user'] = $user; return true; } // Выход из системы function logout() { unset( $_SESSION['user'] ); $tmppos = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1; $path = substr( $_SERVER['PHP_SELF'], 0, $tmppos ); if ( isset( $_COOKIE['autologin'] ) ) setcookie( 'autologin', '', time() - 1, $path ); if ( isset( $_COOKIE['login'] ) ) setcookie( 'login', '', time() - 1, $path ); if ( isset( $_COOKIE['password'] ) ) setcookie( 'password', '', time() - 1, $path ); header( 'Location: '.$_SERVER['PHP_SELF'] ); die(); } // Загрузчик файлов (массив $_FILES) // Используется при добавлении и редактировании страниц, новостей function uploader($id, $marker, $path) { global $connection; $filepath = array(); $filename = array(); for( $i = 0; $i < count($_FILES['file']); $i++) { if ( !empty( $_FILES['file']['tmp_name'][$i] ) and $_FILES['file']['error'][$i] == 0 ) { $filepath = $_FILES['file']['tmp_name'][$i]; $filename = $_FILES['file']['name'][$i]; $upload_path = $path;//папка, куда будет загружаться начальная картинка $target = $upload_path . $filename; move_uploaded_file($filepath, $target);//загрузка оригинала в папку $path_to $path_parts = pathinfo($filename); $ext = $path_parts['extension']; $name = $path_parts['filename']; $new_name = translitIt($name).".".$ext; chmod($target, 0755); rename($target, $upload_path.$new_name); $query= "INSERT INTO files (parent, marker, file_name, file_url) VALUES ('".$id."', '".$marker."', '".$name."', '".$new_name."')"; $result = mysqli_query( $connection, $query ); //обработчик ошибки if(!$result) { echo "Возникла ошибка - ".mysqli_error()."\n"; echo $query; exit(); } } } } ?>
Output for 8.0.0 - 8.0.12, 8.0.14 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Warning: require(): open_basedir restriction in effect. File(../include/config.php) is not within the allowed path(s): (/tmp:/in:/etc) in /in/qNYKH on line 4 Warning: require(../include/config.php): Failed to open stream: Operation not permitted in /in/qNYKH on line 4 Fatal error: Uncaught Error: Failed opening required '../include/config.php' (include_path='.:') in /in/qNYKH:4 Stack trace: #0 {main} thrown in /in/qNYKH on line 4
Process exited with code 255.
Output for 8.0.13
Warning: require(../include/config.php): Failed to open stream: No such file or directory in /in/qNYKH on line 4 Fatal error: Uncaught Error: Failed opening required '../include/config.php' (include_path='.:') in /in/qNYKH:4 Stack trace: #0 {main} thrown in /in/qNYKH on line 4
Process exited with code 255.
Output for 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.10, 7.3.32 - 7.3.33, 7.4.33
Warning: require(../include/config.php): failed to open stream: No such file or directory in /in/qNYKH on line 4 Fatal error: require(): Failed opening required '../include/config.php' (include_path='.:') in /in/qNYKH on line 4
Process exited with code 255.
Output for 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.32
Warning: require(): open_basedir restriction in effect. File(../include/config.php) is not within the allowed path(s): (/tmp:/in:/etc) in /in/qNYKH on line 4 Warning: require(../include/config.php): failed to open stream: Operation not permitted in /in/qNYKH on line 4 Fatal error: require(): Failed opening required '../include/config.php' (include_path='.:') in /in/qNYKH on line 4
Process exited with code 255.
Output for 7.1.20
Warning: require(): open_basedir restriction in effect. File(../include/config.php) is not within the allowed path(s): (/tmp:/in) in /in/qNYKH on line 4 Warning: require(../include/config.php): failed to open stream: Operation not permitted in /in/qNYKH on line 4 Fatal error: require(): Failed opening required '../include/config.php' (include_path='.:') in /in/qNYKH on line 4
Process exited with code 255.

preferences:
197.68 ms | 401 KiB | 318 Q