Создаем невероятную простую систему регистрации на PHP и MySQL. Создание и проверка форм Назидательный index php registration form

Здравствуйте! Сейчас мы попробуем реализовать самую простую регистрацию на сайте с помощью PHP + MySQL. Для этого на вашем компьютере должен быть установлен Apache. Принцип работы нашего скрипта изображен ниже.

1. Начнем с создания таблички users в базе . Она будет содержать данные пользователя (логин и пароль). Зайдем в phpmyadmin (если вы создаете базу на своем ПК http://localhost/phpmyadmin/ ). Создаем таблицу users , в ней будет 3 поля.

Я создаю ее в базе mysql, вы можете создавать в другой базе. Далее устанавливаем значения, как на рисунке:

2. Необходимо соединение с этой таблицей. Давайте создадим файл bd.php . Его содержание:

$db = mysql_connect ("ваш MySQL сервер","логин к этому серверу","пароль к этому серверу");
mysql_select_db ("имя базы, к которой подключаемся",$db);
?>

В моем случае это выглядит так:

$db = mysql_connect ("localhost","user","1234");
mysql_select_db ("mysql",$db);
?>

Сохраняем bd.php .
Отлично! У нас есть таблица в базе, соединение к ней. Теперь можно приступать к созданию странички, на которой пользователи будут оставлять свои данные.

3. Создаем файл reg.php с содержанием (все комментарии внутри):



Регистрация


Регистрация
















4. Создаем файл , который будет заносить данные в базу и сохранять пользователя. save_user.php (комментарии внутри):



{
}
//если логин и пароль введены, то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести


//удаляем лишние пробелы
$login = trim($login);
$password = trim($password);
// подключаемся к базе
// проверка на существование пользователя с таким же логином
$result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
if (!empty($myrow["id"])) {
exit ("Извините, введённый вами логин уже зарегистрирован. Введите другой логин.");
}
// если такого нет, то сохраняем данные
$result2 = mysql_query ("INSERT INTO users (login,password) VALUES("$login","$password")");
// Проверяем, есть ли ошибки
if ($result2=="TRUE")
{
echo "Вы успешно зарегистрированы! Теперь вы можете зайти на сайт. Главная страница";
}
else {
echo "Ошибка! Вы не зарегистрированы.";
}
?>

5. Теперь наши пользователи могут регистрироваться! Далее необходимо сделать "дверь" для входа на сайт уже зарегистрированным пользователям. index.php (комментарии внутри) :

// вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
session_start();
?>


Главная страница


Главная страница











Зарегистрироваться



// Проверяем, пусты ли переменные логина и id пользователя
if (empty($_SESSION["login"]) or empty($_SESSION["id"]))
{
// Если пусты, то мы не выводим ссылку
echo "Вы вошли на сайт, как гость
Эта ссылка доступна только зарегистрированным пользователям";
}
else
{

В файле index.php мы выведем ссылочку, которая будет открыта только для зарегистрированных пользователей. В этом и заключается вся суть скрипта - ограничить доступ к каким-либо данным.

6. Остался файл с проверкой введенного логина и пароля. testreg.php (комментарии внутри):

session_start();// вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
if (isset($_POST["login"])) { $login = $_POST["login"]; if ($login == "") { unset($login);} } //заносим введенный пользователем логин в переменную $login, если он пустой, то уничтожаем переменную
if (isset($_POST["password"])) { $password=$_POST["password"]; if ($password =="") { unset($password);} }
//заносим введенный пользователем пароль в переменную $password, если он пустой, то уничтожаем переменную
if (empty($login) or empty($password)) //если пользователь не ввел логин или пароль, то выдаем ошибку и останавливаем скрипт
{
exit ("Вы ввели не всю информацию, вернитесь назад и заполните все поля!");
}
//если логин и пароль введены,то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
//удаляем лишние пробелы
$login = trim($login);
$password = trim($password);
// подключаемся к базе
include ("bd.php");// файл bd.php должен быть в той же папке, что и все остальные, если это не так, то просто измените путь

$result = mysql_query("SELECT * FROM users WHERE login="$login"",$db); //извлекаем из базы все данные о пользователе с введенным логином
$myrow = mysql_fetch_array($result);
if (empty($myrow["password"]))
{
//если пользователя с введенным логином не существует
}
else {
//если существует, то сверяем пароли
if ($myrow["password"]==$password) {
//если пароли совпадают, то запускаем пользователю сессию! Можете его поздравить, он вошел!
$_SESSION["login"]=$myrow["login"];
$_SESSION["id"]=$myrow["id"];//эти данные очень часто используются, вот их и будет "носить с собой" вошедший пользователь
echo "Вы успешно вошли на сайт! Главная страница";
}
else {
//если пароли не сошлись

Exit ("Извините, введённый вами login или пароль неверный.");
}
}
?>

Ну вот и все! Может урок и скучный, но очень полезный. Здесь показана только идея регистрации, далее Вы можете усовершенствовать ее: добавить защиту, оформление, поля с данными, загрузку аватаров, выход из аккаунта (для этого просто уничтожить переменные из сессии функцией unset ) и так далее. Удачи!

Все проверил, работает исправно!

What is Form?

When you login into a website or into your mail box, you are interacting with a form.

Forms are used to get input from the user and submit it to the web server for processing.

The diagram below illustrates the form handling process.

A form is an HTML tag that contains graphical user interface items such as input box, check boxes radio buttons etc.

The form is defined using the

...
tags and GUI items are defined using form elements such as input.

In this tutorial, you will learn-

When and why we are using forms?

  • Forms come in handy when developing flexible and dynamic applications that accept user input.
  • Forms can be used to edit already existing data from the database

Create a form

We will use HTML tags to create a form. Below is the minimal list of things you need to create a form.

  • Opening and closing form tags
  • Form submission type POST or GET
  • Submission URL that will process the submitted data
  • Input fields such as input boxes, text areas, buttons,checkboxes etc.

The code below creates a simple registration form

Registration Form

Registration Form

First name:
Last name:

Viewing the above code in a web browser displays the following form.


  • … are the opening and closing form tags
  • action="registration_form.php" method="POST"> specifies the destination URL and the submission type.
  • First/Last name: are labels for the input boxes
  • are input box tags

  • is the new line tag
  • is a hidden value that is used to check whether the form has been submitted or not
  • is the button that when clicked submits the form to the server for processing

Submitting the form data to the server

The action attribute of the form specifies the submission URL that processes the data. The method attribute specifies the submission type.

PHP POST method

  • This is the built in PHP super global array variable that is used to get values submitted via HTTP POST method.
  • This method is ideal when you do not want to display the form post values in the URL.
  • A good example of using post method is when submitting login details to the server.

It has the following syntax.

  • “$_POST[…]” is the PHP array

PHP GET method

  • This is the built in PHP super global array variable that is used to get values submitted via HTTP GET method.
  • The array variable can be accessed from any script in the program; it has a global scope.
  • This method displays the form values in the URL.
  • It’s ideal for search engine forms as it allows the users to book mark the results.

It has the following syntax.

  • “$_GET[…]” is the PHP array
  • “"variable_name"” is the URL variable name.

GET vs POST Methods

POST GET
Values not visible in the URL Values visible in the URL
Has not limitation of the length of the values since they are submitted via the body of HTTP Has limitation on the length of the values usually 255 characters. This is because the values are displayed in the URL. Note the upper limit of the characters is dependent on the browser.
Has lower performance compared to Php_GET method due to time spent encapsulation the Php_POST values in the HTTP body Has high performance compared to POST method dues to the simple nature of appending the values in the URL.
Supports many different data types such as string, numeric, binary etc. Supports only string data types because the values are displayed in the URL
Results cannot be book marked Results can be book marked due to the visibility of the values in the URL

The below diagram shows the difference between get and post



Processing the registration form data

The registration form submits data to itself as specified in the action attribute of the form.

When a form has been submitted, the values are populated in the $_POST super global array.

We will use the PHP isset function to check if the form values have been filled in the $_POST array and process the data.

We will modify the registration form to include the PHP code that processes the data. Below is the modified code

Registration Form //this code is executed when the form is submitted

Thank You

You have been registered as

Go back to the form

Registration Form

First name:
Last name:

  • checks if the form_submitted hidden field has been filled in the $_POST array and display a thank you and first name message.

    If the form_fobmitted field hasn’t been filled in the $_POST array, the form is displayed.

More examples

Simple search engine

We will design a simple search engine that uses the PHP_GET method as the form submission type.

For simplicity’s sake, we will use a PHP If statement to determine the output.

We will use the same HTML code for the registration form above and make minimal modifications to it.

Simple Search Engine

Search Results For

The GET method displays its values in the URL

Sorry, no matches found for your search term

Go back to the form

Simple Search Engine - Type in GET

Search Term:

View the above page in a web browser

The following form will be shown

Type GET in upper case letter then click on submit button.

The following will be shown

The diagram below shows the URL for the above results

Note the URL has displayed the value of search_term and form_submitted. Try to enter anything different from GET then click on submit button and see what results you will get.

Working with check boxes, radio buttons

If the user does not select a check box or radio button, no value is submitted, if the user selects a check box or radio button, the value one (1) or true is submitted.

We will modify the registration form code and include a check button that allows the user to agree to the terms of service.

Registration Form

You have not accepted our terms of service

Thank You

You have been registered as

Go back to the form

Registration Form

First name:
Last name:
Agree to Terms of Service:

View the above form in a browser

Если вам необходимо сделать один из разделов своего сайта доступным ограниченному, но неопределенному кругу лиц, проще всего это сделать с помощью регистрации и авторизации пользователей. Есть множество способов авторизации пользователей. Можно использовать как инструменты веб-сервера, так и инструменты языка программирования. Мы поговорим о случае, когда используются сессии PHP .

Вероятно, вы хотели бы увидеть более современный способ создания такой формы. Полное его современное и актуальное представление у меня пока что еще в планах, но зато вы можете увидеть, что форму обратной связи можно построить с помощью объектно-ориентированных приемов в PHP.

Для начала давайте оговорим все шаги, которые сделаем далее. Что нам вообще нужно? Нам нужен сценарий, который будет регистрировать пользователя, авторизовать пользователя, переадресовывать пользователя куда-либо после авторизации. Также нам нужно будет создать страницу, которая будет защищена от доступа неавторизованных пользователей. Для регистрации и авторизации нам необходимо будет создать HTML -формы. Информацию о зарегистрированных пользователях мы будем хранить в базе данных. Это значит, что нам еще нужен скрипт подключения к СУБД . Всю работу у нас будут выполнять функции, которые мы сами напишем. Эти функции мы сохраним в отдельный файл.

Итак, нам нужны следующие файлы:

  • соединение с СУБД;
  • пользовательские функции;
  • авторизация;
  • регистрация;
  • защищенная страница;
  • сценарий завершения работы пользователя;
  • сценарий, проверяющий статус авторизации пользователя;
  • таблица стилей для простейшего оформления наших страниц.

Всё это будет бессмысленно, если у вас нет соответствующей таблицы в базе данных. Запустите инструмент управления своим СУБД (PhpMyAdmin или командную строку, как удобнее) и выполните в нем следующий запрос:

CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT, `login` char(16) NOT NULL, `password` char(40) NOT NULL, `reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Наши файлы со сценариями я назову так (все они будут лежать в одном каталоге):

  • database.php;
  • functions.php;
  • login.php;
  • registration.php;
  • index.php;
  • logout.php;
  • checkAuth.php;
  • style.css.

Назначение каждого из них, я уверен, вам понятно. Начнем со скрипта соединения с СУБД. Вы его уже видели . Просто сохраните код этого скрипта в файле с именем database.php . Пользовательские функции мы будем объявлять в файле functions.php . Как это всё будет работать? Неавторизованный пользователь пытается получить доступ к защищенному документу index.php , система проверяет авторизован ли пользователь, если пользователь не авторизован, он переадресовывается на страницу авторизации. На странице авторизации пользователь должен видеть форму авторизации. Давайте сделаем её.

Авторизация пользователей

зарегистрируйтесь.

Теперь нашей форме нужно придать некий вид. Заодно определим правила для других элементов. Я, забегая вперед, приведу содержимое таблицы стилей полностью.

/* файл style.css */ .row { margin-bottom:10px; width:220px; } .row label { display:block; font-weight:bold; } .row input.text { font-size:1.2em; padding:2px 5px; } .to_reg { font-size:0.9em; } .instruction { font-size:0.8em; color:#aaaaaa; margin-left:2px; cursor:default; } .error { color:red; margin-left:3px; }

Если всё сделано верно, у вас в броузере должно быть следующее:

Конечно же у нас нет пока ни одного зарегистрированного пользователя, и чтобы авторизоваться, нужно зарегистрироваться. Давайте сделаем форму регистрации.

Регистрация пользователей

" />

Вы, наверное, обратили внимание на то, что в HTML -коде присутствуют переменные PHP . Они являются содержимым атрибутов текстовых полей форм, содержимом контейнеров, предназначенных для вывода ошибок. Но мы не инициализировали эти переменные. Давайте сделаем это.

Регистрация пользователей

" />
В имени пользователя могут быть только символы латинского алфавита, цифры, символы "_", "-", ".". Длина имени пользователя должна быть не короче 4 символов и не длиннее 16 символов
В пароле вы можете использовать только символы латинского алфавита, цифры, символы "_", "!", "(", ")". Пароль должен быть не короче 6 символов и не длиннее 16 символов
Повторите введенный ранее пароль

В атрибуте action тега form не указан параметр. В этом случае при отправке данных формы обрабатываться они будут в том же сценарии, из которого они и отправлялись. Значит нам нужно написать код, обрабатывающий данные формы. Но давайте сначала оговорим алгоритм их обработки.

Нам нужно, чтобы поля логина и пароля не были пустыми. Затем необходимо проверить логин на соответствие требованиям. Пароль также должен соответствовать описанным требованиям, а повторно указанный пароль должен с ним совпадать и, кроме того, они должны быть идентичны. Если какое-то из этих условий не выполняется, обработка данных формы должна быть прекращена, в массив сообщений об ошибке должно быть записано соответствующее оповещение, и оно должно быть отображено пользвателю. Для удобства пользователя мы сохраним введенный им логин (если он его указал), записав его значение в массив $fields .

Если всё нормально, в окне вашего броузера, обратившись к документу registration.php, вы должны увидеть примерно такую форму:

Теперь, допустим, пользователь нажал на кнопку регистрации, не заполнил поля формы. Согласно нашему алгоритму, логин и пароль не могут быть пустыми. Если это условие не выполняется, регистрация невозможно. Мы помним о том, что обработка данных формы происходит в текущем сценарии. Значит нам нужно изменить его код, добавив соответствующие проверки. Сразу же оговорим и следующие проверки. Если введены и логин, и пароль, нужно проверить их соответствие указанным требованиям. Для проверки логина и пароля мы создадим пользовательские функции в файле functions.php.

/** * functions.php * Файл с пользовательскими функциями */ // Подключаем файл с параметрами подключения к СУБД require_once("database.php"); // Проверка имени пользователя function checkLogin($str) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$str) { $error = "Вы не ввели имя пользователя"; return $error; } /** * Проверяем имя пользователя с помощью регулярных выражений * Логин должен быть не короче 4, не длиннее 16 символов * В нем должны быть символы латинского алфавита, цифры, * в нем могут быть символы "_", "-", "." */ $pattern = "/^[-_.a-z\d]{4,16}$/i"; $result = preg_match($pattern, $str); // Если проверка не прошла, возвращаем сообщение об ошибке if(!$result) { $error = "Недопустимые символы в имени пользователя или имя пользователя слишком короткое (длинное)"; return $error; } // Если же всё нормально, вернем значение true return true; } // Проверка пароля пользователя function checkPassword($str) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$str) { $error = "Вы не ввели пароль"; return $error; } /** * Проверяем пароль пользователя с помощью регулярных выражений * Пароль должен быть не короче 6, не длиннее 16 символов * В нем должны быть символы латинского алфавита, цифры, * в нем могут быть символы "_", "!", "(", ")" */ $pattern = "/^[_!)(.a-z\d]{6,16}$/i"; $result = preg_match($pattern, $str); // Если проверка не прошла, возвращаем сообщение об ошибке if(!$result) { $error = "Недопустимые символы в пароле пользователя или пароль слишком короткий (длинный)"; return $error; } // Если же всё нормально, вернем значение true return true; }

Теперь нам нужно изменить файл registration.php, чтобы задействовать объявленные нами функции. В сценарий мы добавим условие, проверяющее нажатие кнопки регистрации. Внутри этого условия запускается проверка логина и паролей. В случае, если какая-то из проверок завершается неудачей, мы вновь отображаем форму, и выводим сообщение об ошибке. Если ошибок нет, мы регистрируем пользователя, форму регистрации при этом уже не отображаем, сообщаем пользователю об успешной регистрации, и с помощью функции header() переадресовываем его к форме авторизации.

Вы успешно зарегистрировались в системе. Сейчас вы будете переадресованы к странице авторизации. Если это не произошло, перейдите на неё по прямой ссылке.

"; header("Refresh: 5; URL = login.php"); } // Иначе сообщаем пользователю об ошибке else { $errors["full_error"] = $reg; } } } ?> Регистрация пользователей
" />
В имени пользователя могут быть только символы латинского алфавита, цифры, символы "_", "-", ".". Длина имени пользователя должна быть не короче 4 символов и не длиннее 16 символов
В пароле вы можете использовать только символы латинского алфавита, цифры, символы "_", "!", "(", ")". Пароль должен быть не короче 6 символов и не длиннее 16 символов
Повторите введенный ранее пароль

В скрипте вы должны были заметить еще одну новую функцию — registration() . А мы её еще не объявляли. Давайте сделаем это.

// Функция регистрации пользователя function registration($login, $password) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$login) { $error = "Не указан логин"; return $error; } elseif(!$password) { $error = "Не указан пароль"; return $error; } // Проверяем не зарегистрирован ли уже пользователь // Подключаемся к СУБД connect(); // Пишем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="" . $login . """; // Делаем запрос к базе $query = mysql_query($sql) or die(""); // Смотрим на количество пользователей с таким логином, если есть хоть один, // возвращаем сообщение об ошибке if(mysql_num_rows($query) > 0) { $error = "Пользователь с указанным логином уже зарегистрирован"; return $error; } // Если такого пользователя нет, регистрируем его // Пишем строку запроса $sql = "INSERT INTO `users` (`id`,`login`,`password`) VALUES (NULL, "" . $login . "","" . $password . "")"; // Делаем запрос к базе $query = mysql_query($sql) or die("

Невозможно добавить пользователя: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Не забываем отключиться от СУБД mysql_close(); // Возвращаем значение true, сообщающее об успешной регистрации пользователя return true; }

Если всё нормально, ваш пользователь будет зарегистрирован. Можете потестировать форму. Попробуйте зарегистрировать пользователей с одинаковыми логинами. После успешной регистрации пользователь будет перееадресован к форме авторизации. Ранее мы просто создали разметку для отображения этой формы. Так как в её атрибуте action не указан никакой параметр, данные, отправленные формой, будут обрабатываться в этом же сценарии. Значит нам нужно написать код для обработки, и добавить его в документ login.php.

Авторизация пользователей

;">

Если вы не зарегистрированы в системе, зарегистрируйтесь.

Вы, наверное, заметили, что в скрипте авторизации у нас появилась ещё одна незнакомая функция — authorization() . Эта функция должна авторизовать пользователя, предварительно проверив, существует ли в базе данных зарегистрированный пользователь с таким логином и паролем. Если такой пользователь не будет найден, авторизация будет прервана, на экран будет выведено сообщение о неудаче. При успешной проверки функция authorization() запустит сессию, и запишет в неё значения логина и пароля пользователя, сообщит сценарию об успешности авторизации, и сценарий перенаправит пользователя на защищенную страницу ресурса.

/** * Функция авторизации пользователя. * Авторизация пользователей у нас будет осуществляться * с помощью сессий PHP. */ function authorization($login, $password) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$login) { $error = "Не указан логин"; return $error; } elseif(!$password) { $error = "Не указан пароль"; return $error; } // Проверяем не зарегистрирован ли уже пользователь // Подключаемся к СУБД connect(); // Нам нужно проверить, есть ли такой пользователь среди зарегистрированных // Составляем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="".$login."" AND `password`="".$password."""; // Выполняем запрос $query = mysql_query($sql) or die("

Невозможно выполнить запрос: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Если пользователя с такими данными нет, возвращаем сообщение об ошибке if(mysql_num_rows($query) == 0) { $error = "Пользователь с указанными данными не зарегистрирован"; return $error; } // Если пользователь существует, запускаем сессию session_start(); // И записываем в неё логин и пароль пользователя // Для этого мы используем суперглобальный массив $_SESSION $_SESSION["login"] = $login; $_SESSION["password"] = $password; // Не забываем закрывать соединение с базой данных mysql_close(); // Возвращаем true для сообщения об успешной авторизации пользователя return true; }

Когда пользователь попадает на защищенную страницу, следует проверить корректность данных о его авторизации. Для этого нам потребуется еще одна пользовательская функция. Назовем её checkAuth() . Её задачей будет сверка данных авторизации пользователя с теми, которые хранятся в нашей базе. Если данные не совпадут, пользователь будет перенаправлен на страницу авторизации.

Function checkAuth($login, $password) { // Если нет логина или пароля, возвращаем false if(!$login || !$password) return false; // Проверяем зарегистрирован ли такой пользователь // Подключаемся к СУБД connect(); // Составляем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="".$login."" AND `password`="".$password."""; // Выполняем запрос $query = mysql_query($sql) or die("

Невозможно выполнить запрос: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Если пользователя с такими данными нет, возвращаем false; if(mysql_num_rows($query) == 0) { return false; } // Не забываем закрывать соединение с базой данных mysql_close(); // Иначе возвращаем true return true; }

Теперь, когда пользователь попал на защищенную страницу, мы должны вызвать функцию проверки данных авторизации. Сценарий вызова и проверки мы поместим в отдельный файл checkAuth.php и будем подключать его к тем страницам, которые будут закрытыми для общего доступа.

/** * Скрипт проверки авторизации пользователей */ // Запускаем сессию, из которой будем извлекать логин и пароль // авторизовавшихся пользователей session_start(); // Подлючаем файл с пользовательскими функциями require_once("functions.php"); /** * Чтобы определить авторизован ли пользователь, нам нужно * проверить существуют ли в базе данных записи для его логина * и пароля. Для этого воспользуемся пользовательской функцией * проверки корректности данных авторизовавшегося пользователя. * Если эта функция вернет false, значит авторизации нет. * При отсутствии авторизации мы просто переадресовываем * пользователя к странице авторизации. */ // Если в сессии присуствуют данные и о логине, и о пароле, // проверяем их if(isset($_SESSION["login"]) && $_SESSION["login"] && isset($_SESSION["password"]) && $_SESSION["password"]) { // Если проверка существующих данных завершается неудачей if(!checkAuth($_SESSION["login"], $_SESSION["password"])) { // Переадресовываем пользователя на страницу авторизации header("location: login.php"); // Прекращаем выполнение скрипта exit; } } // Если данных либо о логине, либо о пароле пользователя нет, // считаем что авторизации нет, переадресовываем пользователя // на страницу авторизации else { header("location: login.php"); // Прекращаем выполнение сценария exit; }

А теперь давайте создадим код нашей защищенной страницы. Он будет довольно-таки прост.

Авторизация и регистрация пользователей

Успешная авторизация.

Вы получили доступ к защищенной странице. Вы можете выйти из системы.

Как видите, в защищенном документе мы подключаем только один файл — checkAuth.php. Все остальные файлы подключаются уже в других сценариях. Поэтому наш код не выглядит громоздким. Регистрацию и авторизацию пользователей мы организовали. Теперь необходимо позволить пользователям выходить из системы. Для этого мы создадим сценарий в файле logout.php.

/** * Скрипт выхода пользователя из системы. Так как пользователи * авторизуются через сессии, их логин и пароль хранятся * в суперглобаном массиве $_SESSION. Чтобы осуществить * выход из системы, достаточно просто уничтожить значения * массива $_SESSION["login"] и $_SESSION["password"], после * чего мы переадресовываем пользователя к странице авторизации */ // Обязательно запускаем сессию session_start(); unset($_SESSION["login"]); unset($_SESSION["password"]); header("location: login.php");

Скрипт регистрации, авторизации и проверки пользователей готов. Вы можете использовать его у себя, дополнять, изменять под ваши нужды. Если у вас будут вопросы, можете задавать их в комментариях. Вы можете скачать себе все файлы, о которых здесь велась речь, упакованные в один архив .

P.S. Я в курсе, что лучше писать объектно-ориентированный код, знаю, что передавать и хранить пароль в открытом виде не стоит, что информацию, заносимую в базу данных, необходимо предварительно проверять. Знаю. Об этом я здесь не буду говорить.

PHP | 25 Jan, 2017 | Clever Techie

In this lesson, we learn how to create user account registration form with PHP validation rules, upload profile avatar image and insert user data in MySQL database. We will then retrieve the information from the database and display it on the user profile welcome page. Here is what the welcome page is going to look like:

Setting up Form CSS and HTML

First, go ahead and copy the HTML source from below codepen and place the code in a file called form.php. Also create another file named form.css in the same directory and copy and paste all of the CSS code from the codepen below into it:

Once you"ve saved form.php and form.css, you may go ahead and run form.php to see what the form looks like. It should look exactly the same as the one showing in the "Result" tab from the codepen above.

Creating the Database and Table

Before we start adding PHP code to our form, let"s go ahead and create the database with a table which will store our registered users information in it. Below in the SQL script to create the database "accounts" and table "users":

CREATE DATABASE accounts; CREATE TABLE `accounts`.`users` (`id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) NOT NULL, `email` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `avatar` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`));

Below is a complete code with error checking for connecting to MySQL database and running above SQL statements to create the database and users table:

//connection variables $host = "localhost"; $user = "root"; $password = "mypass123"; //create mysql connection $mysqli = new mysqli($host,$user,$password); if ($mysqli->connect_errno) { printf("Connection failed: %s\n", $mysqli->connect_error); die(); } //create the database if (!$mysqli->query("CREATE DATABASE accounts2")) { printf("Errormessage: %s\n", $mysqli->error); } //create users table with all the fields $mysqli->query(" CREATE TABLE `accounts2`.`users` (`id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) NOT NULL, `email` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `avatar` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`));") or die($mysqli->error);

With our HTML, CSS and the database table in place, we"re now reading to start working on our form. The first step is to create a place for error messages to show up and then we"ll start writing some form validation.

Starting New Session for Error Messages

Open up the form.php and add the following lines to it at the very top, make sure to use the php opening and closing tags (I have not included the html part of form.php to keep things clean).

We have created new session because we"re going to need to access $_SESSION["message"] on the "welcome.php" page after user successfully registers. MySQL connection has also been created right away, so we can work with the database later on.

We also need to print out $_SESSION["message"] on the current page. From the beginning the message is set to "" (empty string) which is what we want, so nothing will be printed at this point. Let"s go ahead and add the message inside the proper DIV tag:

Creating Validation Rules

This form already comes with some validation rules, the keyword "required" inside the HTML input tags, is checking to make sure the field is not empty, so we don"t have to worry about empty fields. Also, by setting input type to "email and "password", HTML5 validates the form for proper email and password formatting, so we don"t need to create any rules for those fields either.

However, we still need to write some validation rules, to make sure the passwords are matching, the avatar file is in fact an image and make sure the user has been added to our database.

Let"s create another file and call it validate.php to keep things well organized. We"ll also include this file from our form.php.

The first thing we"re going to do inside validate.php is to make sure the form is being submitted.

/* validate.php */ //the form has been submitted with post method if ($_SERVER["REQUEST_METHOD"] == "POST") { }

Then we"ll check if the password and confirm password are equal to each other

if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if two passwords are equal to each other if ($_POST["password"] == $_POST["confirmpassword"]) { } }

Working with Super Global Variables

Note how we used super global variables $_SERVER and $_POST to get the information we needed. The keys names inside the $_POST variable is available because we used method="post" to submit our form.

The key names are all the named HTML input fields with attribute name (eg: name="password", name="confirmpassword"):

/>

To clarify a bit more, here is what the $_POST would look like (assuming all the fields in the form have been filled out) if we used a print_r($_POST) function on it, followed by die(); to terminate the script right after printing it. This is a good way of debugging your script and seeing what"s going on:

if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_POST); die(); /*output: Array ( => clevertechie => [email protected] => mypass123 => mypass123 => Register) */

Now we"re going to get the rest of our submitted values from $_POST and get them properly formatted so they can be inserted to our MySQL database table

//the form has been submitted with post if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_POST["password"] == $_POST["confirmpassword"]) { //define other variables with submitted values from $_POST $username = $mysqli->real_escape_string($_POST["username"]); $email = $mysqli->real_escape_string($_POST["email"]); //md5 hash password for security $password = md5($_POST["password"]); //path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); } }

In the above code, we used real_escape_string() method to make sure our username, email and avatar_path are formatted properly to be inserted as a valid SQL string into the database. We also used md5() hash function to create a hash string out of password for security.

How File Uploading Works

Also, notice the new super global variable $_FILES, which holds the information about our image, which is the avatar being uploaded from the user"s computer. The $_FILES variable is available because we used enctype="multipart/form-data" in our form:

Here is the output if we use the print_r($_FILES) followed by die(); just like we did for the $_POST variable:

if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_FILES); die(); /*output: Array ( => Array ( => guldan.png => image/png => C:\Windows\Temp\php18D8.tmp => 0 => 98823)) */ //this is how we"re able to access the image name: $_FILES["avatar"]["name"]; //guldan.png

When the file is first uploaded, using the post method, it will be stored in a temporary directory. That directory can be accessed with $_FILES[ "avatar "][ "tmp_name" ] which is "C:\Windows\Temp\php18D8.tmp" from the output above.

We can then copy that file from the temporary directory, to the directory that we want which is $avatar_path. But before we copy the file, we should check if the file is in fact image, for that we"ll check another key called from our $_FILES variable.

//path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); //make sure the file type is image if (preg_match("!image!",$_FILES["avatar"]["type"])) { //copy image to images/ folder if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)) { } }

The preg_match function matches the image from the [ "type" ] key of $_FILES array, we then use copy() function to copy our image file which takes in two parameters. The first one is the source file path which is our ["tmp_name"] directory and the second one is the destination path which is our "images/guldan.png" file path.

Saving User Data in a MySQL Database

We can now set some session variables which we"ll need on the next page, which are username and avatar_path, and we"ll also create the SQL query which will insert all the submitted data into MySQL database:

if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)) { //set session variables to display on welcome page $_SESSION["username"] = $username; $_SESSION["avatar"] = $avatar_path; //create SQL query string for inserting data into the database $sql = "INSERT INTO users (username, email, password, avatar) " . "VALUES ("$username", "$email", "$password", "$avatar_path")"; }

The final step is turn our query, using the query() method and check if it"s successful. If it is, that means the user data has been saved in the "users" table successfully! We then set the final session variable $_SESSION[ "message" ] and redirect the user to the welcome.php page using the header() function:

//check if mysql query is successful if ($mysqli->query($sql) === true) { $_SESSION[ "message" ] = "Registration succesful! Added $username to the database!"; //redirect the user to welcome.php header("location: welcome.php"); }

That"s pretty much all we need for the validation, we just need to add all the "else" keywords in case things don"t go as planned from all the if statements we have created. Here is what the full code for validate.php looks so far:

/* validate.php */ //the form has been submitted with post if ($_SERVER["REQUEST_METHOD"] == "POST") { //two passwords are equal to each other if ($_POST["password"] == $_POST["confirmpassword"]) { //define other variables with submitted values from $_POST $username = $mysqli->real_escape_string($_POST["username"]); $email = $mysqli->real_escape_string($_POST["email"]); //md5 hash password for security $password = md5($_POST["password"]); //path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); //make sure the file type is image if (preg_match("!image!",$_FILES["avatar"]["type"])) { //copy image to images/ folder if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)){ //set session variables to display on welcome page $_SESSION["username"] = $username; $_SESSION["avatar"] = $avatar_path; //insert user data into database $sql = "INSERT INTO users (username, email, password, avatar) " . "VALUES ("$username", "$email", "$password", "$avatar_path")"; //check if mysql query is successful if ($mysqli->query($sql) === true){ $_SESSION["message"] = "Registration successful!" . "Added $username to the database!"; //redirect the user to welcome.php header("location: welcome.php"); } } } } }

Setting Session Error Messages When Things Go Wrong

Let"s go ahead and add all the else statements at once where we simply set the $_SESSION[ "message" ] error messages which will be printed out when any of our if statements fail. Add the following code right after the last if statement where we checked for successful mysqli query and within the last curly bracket like this:

If ($mysqli->query($sql) === true){ $_SESSION["message"] = "Registration succesful!" . "Added $username to the database!"; header("location: welcome.php"); } else { $_SESSION["message"] = "User could not be added to the database!"; } $mysqli->close(); } else { $_SESSION["message"] = "File upload failed!"; } } else { $_SESSION["message"] = "Please only upload GIF, JPG or PNG images!"; } } else { $_SESSION["message"] = "Two passwords do not match!"; } } //if ($_SERVER["REQUEST_METHOD"] == "POST")

The session message will then display the error message in the div tag where we put our $_SESSION["message"] if you recall:

Below is an example of what the error message is going to look like when two passwords don"t match. Feel free to play around with it to trigger other error messages:


Creating User Profile Welcome Page

We"re now done with the validate.php. The final step is to create welcome.php page which will display the username, avatar image and some users that have already been registered previously along with their own user names and mini avatar thumbnails. Here is what the complete welcome.php should look like, I will explain parts of it that may be confusing:

">
Welcome query($sql); ?>
All registered users: fetch_assoc()){ echo "
".$row["username"]."
"; echo "
"; } ?>

The $_SESSION variable part from above should be easy to understand, we simply transfer over the variables from our validate.php page to this welcome.php page, if you"re still confused by that, please check out page for complete break down.

Working with MySQL Result Object

Whenever we use "SELECT" statement in our SQL query and then run that SQL with $mysqli->query($sql) command, the returned value is a MySQL result object. Once we have the result object, there are a few methods that become available so we can further start working with the data.

$sql = "SELECT username, avatar FROM users"; $result = $mysqli->query($sql); //$result = mysqli_result object

One of those methods is $result->fetch_assoc() which fetches the current row and returns an array with all the row data. So we"re putting that in a conditional expression, which will become false when it reaches the last row in the result set, and storing the returned value from $result->fetch_assoc() inside the $row variable.

//returns associative array of fetched row while($row = $result->fetch_assoc()){ echo "

".$row["username"]."
"; echo "
"; }

Conclusion

And that"s how we"re able to access $row["username"] and $row["avatar"] from the associative array that is being returned, of the users that have already been registered previously and live in our users database table!

The profile welcome page should now look very similar to the one shown in the very beginning of this lesson, and the form is now complete, good job! Please post any questions you may have in the comments below.

Over the past few years, web hosting has undergone a dramatic change. Web hosting services have changed the way websites perform. There are several kinds of services but today we will talk about the options that are available for reseller hosting providers. They are Linux Reseller Hosting and Windows Reseller Hosting. Before we understand the fundamental differences between the two, let’s find out what is reseller hosting.

Reseller Hosting

In simple terms, reseller hosting is a form of web hosting where an account owner can use his dedicated hard drive space and allotted bandwidth for the purpose of reselling to the websites of third parties. Sometimes, a reseller can take a dedicated server from a hosting company (Linux or Windows) on rent and further let it out to third parties.

Most website users either are with Linux or Windows. This has got to do with the uptime. Both platforms ensure that your website is up 99% of the time.

1. Customization

One of the main differences between a Linux Reseller Hostingplan and the one provided by Windows is about customization. While you can experiment with both the players in several ways, Linux is way more customizable than Windows. The latter has more features than its counterpart and that is why many developers and administrators find Linux very customer- friendly.

2. Applications

Different reseller hosting services have different applications. Linux and Windows both have their own array of applications but the latter has an edge when it comes to numbers and versatility. This has got to do with the open source nature of Linux. Any developer can upload his app on the Linux platform and this makes it an attractive hosting provider to millions of website owners.

However, please note that if you are using Linux for web hosting but at the same time use the Windows OS, then some applications may not simply work.

3. Stability

While both the platforms are stable, Linux Reseller Hosting is more stable of the two. It being an open source platform, can work in several environments.This platform can be modified and developed every now and then.

4. .NET compatibility

It isn’t that Linux is superior to Windows in every possible way. When it comes to .NET compatibility, Windows steals the limelight. Web applications can be easily developed on a Windows hosting platform.

5. Cost advantages

Both the hosting platforms are affordable. But if you are feeling a cash crunch, then you should opt for Linux. It is free and that is why it is opted by so many developers and system administrators all around the world.

6. Ease of setup

Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years.

7. Security

Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses.

Conclusion

Choosing between the two will depend on your requirement and the cost flexibility. Both the hosting services have unique advantages. While Windows is easy to set up, Linux is cost effective, secure and is more versatile.



Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding

Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.

How Pip Engages Children

When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft.

Innovations to Come

Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.