Шаблон регистрации php. Создаем невероятную простую систему регистрации на PHP и MySQL

Здравствуйте! Сейчас мы попробуем реализовать самую простую регистрацию на сайте с помощью 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 ) и так далее. Удачи!

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

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

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

Этот урок рассчитан для начинающих изучение php где мы рассмотрим основы управления пользователями.

Шаг-1

Создадим в базе таблицу user в которой, мы будем хранить информацию о пользователях в таблице 4 поля

  • UserID
  • Username
  • Password
  • EmailAddress

Используйте SQL запрос ниже для создания базы данных

CREATE TABLE `users` ( `UserID` INT(25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `Username` VARCHAR(65 ) NOT NULL , `Password` VARCHAR(32 ) NOT NULL , `EmailAddress` VARCHAR(255 ) NOT NULL ) ;

session_start () ; $dbhost = "localhost" ; // Имя хоста где расположен сервер mysql обычно localhost $dbname = "database" ; // Имя базы данных $dbuser = "username" ; // Имя пользователя базы данных $dbpass = "password" ; // Пароль для доступа к базе данных mysql_connect ($dbhost , $dbuser , $dbpass ) or die ("MySQL Error: " . mysql_error () ) ; mysql_select_db ($dbname ) or die ("MySQL Error: " . mysql_error () ) ; ?>

Этот файл отвечает за подключение к базе данных и будет выводиться на всех страницах. Рассмотрим строки кода более подробно

session_start();

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

mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());

mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

Каждая из этих функций выполняет отдельные, но связанные задачи.

Функция mysql_connect выполняет соединение с сервером баз данных MySQL в качестве параметров в скобках указаны переменные которым присвоены соответствующие значения Хост, Имя пользователя, Пароль если данные не верные выдаст сообщение об ошибке

Функция mysql_select_db выбирает базу данных имя которой мы присвоили переменной $dbname , в случае если не удаётся найти базу выводит сообщение об ошибке

Шаг-2 Создаем файл index.php

Немало важным элементом на нашей странице – является первая строка PHP; эта строка будет включать файл, который мы создали выше (base.php ), и по существу позволим нам обращаться к чему-нибудь от того файла в нашем текущем файле. Мы сделаем это со следующей строкой кода PHP. Создайте файл, названный index.php, и поместите этот код наверху.

Создайте новый файл index.php и вставите в самое начало следующий код

Эта строка будет подключать фаил который мы создали выше (base.php), что позволит нам обращаться к коду того файла в нашем текущем файле.

Это осуществляет функция include()

Теперь мы займёмся созданием внешнего интерфейса, где пользователь будет вводить свои данные для регистрации, а если он уже зарегистрирован дать возможность изменения данных. Так как этот урок нацелен на PHP мы не будем разбираться с кодом HTML/CSS внешний вид сделаем потом когда мы создадим нашу таблицу стилей CSS, а пока просто вставим этот код после предыдущей строки.

Система управления пользователями <title> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <span><div id="main">Сюда вставим php код </div> </p> <p>Теперь прежде чем пристать php программу разберём принцип её работы, что в той или иной ситуации надо выводит на экран:</p> <ol><li>Если пользователь уже вошёл то показываем страницу с различными опциями которые были скрыты до регистрации.</li> <li>Если пользователь еще не вошёл но прошёл регистрацию то показываем форму для ввода логина и пароля.</li> <li>Если 1 и 2 пункт не выполнен выводим форму для регистрации.</li> </ol><p>Выглядеть это будет так:</p> <p><?php </span> <span>if (! empty empty </span> <span>{ </span> <span>// Здесь выводиться скрытые опции </span> <span>} </span> <span>elseif (! empty empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>// Выводим форму для входа </span> <span>} </span> <span>else </span> <span>{ </span> <span>// Выводим форму для регистрации </span> <span>} </span> <span>?> </p> <p>Когда пользователь проходит авторизацию на нашем сайте, информация сохраняется в сессии получить к ней доступ мы можем через глобальный массив <b>$ _SESSION </b>. С помощью функции empty и знака! в условии if мы проверяем имеет ли переменная значение, если переменная имеет значение выполняем код между фигурных скобок.</p> <p>В следующей строке всё работает тем же образом, только на этот раз с помощью <b>$ _POST </b> глобального массива. Этот массив содержит какие либо данные переданные через форму входа которую мы создадим позже. Последняя условие else выполниться в том случае если предыдущие условия не удовлетворяются.</p> <p>Теперь когда мы понимаем логику давайте вставим следующий код в файл index.php между тегами <div></p> <p><?php </span> <span>if (! empty ($_SESSION [ "LoggedIn" ] ) && ! empty ($_SESSION [ "Username" ] ) ) </span> <span>{ </span> <span>?> </span> <span> <h1>Пользовательская зона</h1> </span> <span> <p Спасибо что вошли! Вы <b><?= $_SESSION [ "Username" ] ?> </b> и Ваш адрес электронной почты <b><?= $_SESSION [ "EmailAddress" ] ?> </b>.</p> </span> <span><?php </span> <span>} </span> <span>elseif (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string </span> <span>$checklogin = mysql_query (</span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span> echo <span>"<h1>Вы успешно вошли</h1>" </span>; </span> <span> echo <span>"<p>Сейчас вы будете переадресованы в ваш профиль.</p>" </span>; </span> <span> echo <span>"<meta content="=2;index.php" />" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Ваша учётная запись не найдена или вы неправильно ввели логин или пароль. <a href=\" index.php\" >Попробовать снова </a>.</p>" </span>; </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <h1>Вход</h1> <span> <p>Хорошо что зашли Регистрация .</p> </span> <span> <form method="post" action="index.php" name="loginform" id="loginform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <input type="submit" name="login" id="login" value="Войти" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </p> <p>В этом участке кода две функции,это<b>mysql _real _escape _string </b>которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и <b>md 5 </b> эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве <b>$_POST </b>. Всё результаты работы функций мы присваиваем переменным<b>$username , <span>$password </span> </b>.</p> <p>$checklogin = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . "" AND Password = "" . $password . """ ) ; </span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span>$email = $row [ "EmailAddress" ] ; </span> <span>$_SESSION [ "Username" ] = $username ; </span> <span>$_SESSION [ "EmailAddress" ] = $email ; </span> <span>$_SESSION [ "LoggedIn" ] = 1 ; </p> <p>В этом участке кода нам надо проверить существует ли такой пользователь,для этого направляем запрос в базу данных, вытащить все поля из таблицы users где поля Username и Password равны переменным<b>$username и $password </b>. Результат запроса заносим в переменную<b>$checklogin </b> далее в условии <b>if </b> функция <b>mysql _num _row </b>s считает количество строк в запросе к базе и если равно 1 то есть пользователь найденвыполняем код в фигурных скобках, функция <b>mysql _fetch _array </b>преобразовывает результат запроса из <b>$checklogin </b>в ассоциативный массив, присваиваеваем значение поля EmailAddress переменной <b>$email </b>для использовать в дальнейшем.</p> <p>Заносим логин и email в текущею сессию после этого пользователь перенаправляется в свою учётную запись.</p> <p><b>Шаг-3 </b></p> <p>Теперь надо сделать страницу где пользователи будут регистрироваться.</p> <p>Создаем файл register.phpи скопируйте в него следующий код:</p> <p><?php include "base.php" ; ?> </span> <span><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> </span> <span><html xmlns="http://www.w3.org/1999/xhtml"> </span> <span><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </span> <span><title> Система управления пользователями - Регистрацияtitle> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <div id="main"> <span><?php </span> <span>if (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string ($_POST [ "password" ] ) ) ; </span> <span>$email = mysql_real_escape_string ($_POST [ "email" ] ) ; </span> <span>$checkusername = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . """ ) ; </span> <span>if (mysql_num_rows ($checkusername ) == 1 ) </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Такой логин уже занят p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span>$registerquery = mysql_query (<span>"INSERT INTO users (Username, Password, EmailAddress) VALUES("" </span>. $username . "", "" . $password . "", "" . $email . "")" ) ; </span> <span>if ($registerquery ) </span> <span>{ </span> <span> echo "<h1>Отлично</h1>" ; </span> <span> echo <span>"<p>Ваша учетная запись была успешно создана. Вы можете<a href=\" index.php\" >Воити</a>.</p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Попробуйте повторить регистрацию снова.</p>" </span>; </span> <span>} </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <span> <h1>Регистрация</h1> </span> <span> <form method="post" action="register.php" name="registerform" id="registerform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <label for="email">Email:</label><input type="text" name="email" id="email" /><br /> </span> <span> <input type="submit" name="register" id="register" value="Регистрация" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </span> </div> </body> </html> </p> <p>В этом коде есть немного нового, запись в базу данных</p> <p>Это такой же запрос к базе данных который был раньше только теперь мы не получаеминформацию, а записываем командой INSERT , первым деломнадо указать в какие поля будет вноситься информация а в область VALUES информация которая будет записана в нашем случае это переменные со значением которые были переданы пользователем.Обратите особое внимание правила формирования запросов.</p> <p><b>Шаг-4 Завершение </b></p> <p>Для того чтобы пользователь мог выйти создайте файл logout.php и скопируйте в него код:</p> <p><?php include "base.php; <span>$_SESSION = array(); session_destroy(); ?> </span> <meta http-equiv=" refresh" content=" 0 ; index. php" </p> <p>В результате этого кода происходит сбросглобального массива $_SESSION и разрушение сессии, не забудьтев опция пользователя поставить ссылку на этот фаил.</p> <p>И наконец придадим стиль всему вышеописанному, создайте файл style.css и поместите туда следующий ниже код.</p> <p>* { </span> <span>margin : 0 ; </span> <span>padding : 0 ; </span> <span>} </span> body <span>{ </span> <span>} </span> a <span>{ </span> <span>color : #000 ; </span> <span>} </span> a<span>:hover , a:active , a:visited { </span> <span>text-decoration : none ; </span> <span>} </span> <span>#main { </span> <span>width : 780px ; </span> <span>margin : 0 auto ; </span> <span>margin-top : 50px ; </span> <span>padding : 10px ; </span> <span>background-color : #EEE ; </span> <span>} </span> form fieldset <span>{ border : 0 ; } </span> form fieldset p br <span>{ clear : left ; } </span> label <span>{ </span> <span>margin-top : 5px ; </span> <span>display : block ; </span> <span>width : 100px ; </span> <span>padding : 0 ; </span> <span>float : left ; </span> <span>} </span> input <span>{ </span> <span>font-family : Trebuchet MS; </span> <span>border : 1px solid #CCC ; </span> <span>margin-bottom : 5px ; </span> <span>background-color : #FFF ; </span> <span>padding : 2px ; </span> <span>} </span> input<span>:hover { </span> <span>border : 1px solid #222 ; </span> <span>background-color : #EEE ; </span> <span>} </p> <p>Вот в принципе и всё конечно приведенный в этом уроке пример далёк от совершенства но он и был рассчитан для начинающих чтобы дать понятие основ.</p> <p>Разберём некоторые части данного кода</p> <p>$username = mysql_real_escape_string($_POST["username"]); </p> <p>$password = md5(mysql_real_escape_string($_POST["password"])); </p> <p>В этом участке кода две функции,этоmysql _real _escape _string которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и md 5 эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве $_POST . Всё результаты работы функций мы присваиваем переменным$username , <span>$password </span>.</p> <p>Вполне вероятно, что Вы уже слышали про <b>директиву register_globals </b> и знаете, что она делает. Если кто-то этого не знает, то Вы узнаете об этом из данной статьи, однако, главная задача этой статьи доказать, что <b>директиву register_globals </b> лучше всегда держать отключённой в целях безопасности.</p> <p>Позволяет регистрировать переменные, полученные из <b>GET-запроса </b>. Допустим, был такой запрос: <b>index.php?a=15 </b>. Таким образом, безусловно, создаётся переменная <b>$_GET["a"] </b> и переменная <b>a </b>. Вот создание переменной <b>a </b> и произошло в результате <b>включённой директивы register_globals </b>.</p> <p>Теперь о том, почему данную директиву надо всегда держать отключённой. Предположим, что Вы делаете авторизацию пользователя, и Вы написали такой код:</p><p> <?php<br> if (($_POST["login"] == "Admin") && ($_POST["password"] == "123456")) $check_user = true;<br> if ($check_user) echo "Авторизация прошла успешно";<br> else echo "Ошибка авторизации";<br> ?> </p><p>Теперь если файл называется, например, <b>auth.php </b>, то, обратившись к нему следующим образом: <b>auth.php?check_user=1 </b>, то получится успешная авторизация, независимо от того, какие логин и пароль были отправлены и были ли отправлены вообще.</p> <p>Безусловно, данный пример является слегка мистическим, поскольку так никто не пишет (хотя бы из-за отсутствия <b>else $check_user = false; </b>), однако, данный пример наглядно показывает, к чему может привести <b>включённая директива register_globals </b>.</p> <p>Теперь о том, как же <b>отключить директиву register_globals </b>. Для этого надо добавить в файл <b>.htaccess </b> всего одну строчку:</p><p>Php_value register_globals 0 </p><p>Есть небольшая вероятность, что если директива была раньше включена, то у Вас может что-нибудь сломаться, поэтому всё внимательно проверьте и устраните все возникшие ошибки, поскольку безопасность того действительно стоит.</p> <p>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. </p> <p><b>Reseller Hosting </b> </p> <p>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. </p> <p>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. </p> <p>1. Customization </p> <p>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. </p> <p>2. Applications </p> <p>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. </p> <p>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. </p> <p>3. Stability </p> <p>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. </p> <p>4. .NET compatibility </p> <p>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. </p> <p>5. Cost advantages </p> <p>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. </p> <p>6. Ease of setup </p> <p>Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years. </p> <p>7. Security </p> <p>Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses. </p> <p><b>Conclusion </b> </p> <p>Choosing between the two </span><span> 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. </p> <br><h2></h2> <p><img src='https://i2.wp.com/1.bp.blogspot.com/-mxibWQ7h54A/W3G4bcnqRjI/AAAAAAAABo0/h3EEBVFXm5o5PzX6d-ZRtZ9z9e4CkOd7ACLcBGAs/s400/homepge.JPG' width="100%" loading=lazy></p> <br> 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.<p>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.</p><p>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.</p><p>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.</p><p>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:</p><p>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.</p><p>They said that they couldn"t avoid the fee,<b> but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! </b> 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.</p><p>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. </p> <h2></h2> <p>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.<br></p><p><img src='https://i1.wp.com/1.bp.blogspot.com/-SIlr3BAOEwQ/WjQdkeZ01-I/AAAAAAAABVk/sG-kuxu_5XoMezHKS9W-VsHsVTrZ5hK9wCLcBGAs/s320/introducing-kids-to-coding-with-pip1.jpg' height="229" width="320" loading=lazy></p><p>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.</p><h2>Future of Coding</h2> 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.<br> 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.<br> 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.<h2>How Pip Engages Children</h2> 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.<br> 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. <h2>Innovations to Come</h2> 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. <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy>");</script> </div> <div id="yandex_rtb_R-A-236089-4"></div> <div class="navigation"> <div class="alignleft"></div> <div class="alignright"></div> </div> <div class="navigation"> <div class="alignleft"></div> <div class="alignright"></div> </div> </div> </div> <div class="content_right"> <div class="related_right"> <div class="related_right_title">Разделы</div> <ul id="menu-menyu-na-glavnoj" class="nav"> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/works/">Сочинения</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/grade-11/">11 класс</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summary/">Краткие содержания</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/seasons/">Времена года</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/about-nature/">Про природу</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summer/">Лето</a></li> </ul> </div> <div class="related_right_vk"> </div> </div> </div> </div> <div id="footer"> <div class="wrapper"> <div class="ft_widgets"> <div class="ft_widget"> <div class="ft_logo"> <div class="ft_logo_text"> testet.ru<span></span><br> </div> <br><br> </div> <div class="ft_desc"> © 2024 Сайт для учеников и учителей </div> <div class="ft_text"> <div id="text-2" class="widget widget_text"> <div class="textwidget"></div> </div> </div> <div class="ft_menu"> <ul id="menu-nizhnee-menyu" class="menu"> </ul> </div> </div> <div class="ft_widget_menu"> <div class="ft_widget_menu1"> <div id="nav_menu-2" class="widget widget_nav_menu"><div class="menu-futer-1-container"><ul id="menu-futer-1" class="menu"> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/works/">Сочинения</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/grade-11/">11 класс</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summary/">Краткие содержания</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/seasons/">Времена года</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/about-nature/">Про природу</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summer/">Лето</a></li> </ul></div></div> </div> <div class="ft_widget_menu2"> <div id="nav_menu-3" class="widget widget_nav_menu"><div class="menu-futer-2-container"><ul id="menu-futer-2" class="menu"> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/works/">Сочинения</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/grade-11/">11 класс</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summary/">Краткие содержания</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/seasons/">Времена года</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/about-nature/">Про природу</a></li> <li id="menu-item-" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-"><a href="/category/summer/">Лето</a></li> </ul></div></div> </div> </div> <div class="ft_widget_search"> </div> </div> </div> </div> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=4.9.1'></script> <script type='text/javascript'> /* <![CDATA[ */ var ads_fix_params = { "fix_cookie": "7" }; /* ]]> */ </script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-ads/js/ads_fixed.js?ver=2.2.4'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-comments/js/comment_like.js?ver=5.0'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-comments/js/comment_ajax.js?ver=5.0'></script> <script type='text/javascript'> /* <![CDATA[ */ var fix_params = { "fix_top": "50", "fix_bottom": "450", "fix_left": "" }; /* ]]> */ </script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-common/js/fixed.js?ver=1.0.0'></script> <script type='text/javascript' src='/assets/scripts1.js'></script> <script type='text/javascript'> /* <![CDATA[ */ var top_params = { "wrap_class": "false", "top_text": "\u041d\u0430\u0432\u0435\u0440\u0445" }; /* ]]> */ </script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-common/js/top.js?ver=1.0.0'></script> <script type='text/javascript' src='/wp-includes/js/comment-reply.min.js?ver=4.9'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-social/js/jquery.colorbox-min.js?ver=1.0'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-social/js/social.js?ver=1.0'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/sp-questions/ajax.js?ver=1.0.0'></script> <script type='text/javascript' src='/wp-includes/js/wp-embed.min.js?ver=4.9'></script> <script async="async" type='text/javascript' src='https://testet.ru/wp-content/plugins/akismet/_inc/form.js?ver=4.0.1'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/easy-fancybox/fancybox/jquery.fancybox-1.3.8.min.js?ver=1.6.2'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/easy-fancybox/js/jquery.easing.min.js?ver=1.4.0'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/easy-fancybox/js/jquery.mousewheel.min.js?ver=3.1.13'></script> <script type='text/javascript' src='https://testet.ru/wp-content/plugins/google-captcha/js/script.js?ver=1.33'></script> <script type="text/javascript"> jQuery(document).on('ready post-load', function() { jQuery('.nofancybox,a.pin-it-button,a[href*="pinterest.com/pin/create"]').addClass('nolightbox'); }); jQuery(document).on('ready post-load', easy_fancybox_handler); jQuery(document).on('ready', easy_fancybox_auto); </script> </body> </html>