Создаем невероятную простую систему регистрации на PHP и MySQL. Создание и проверка форм Точный users registration php

Создаем невероятную простую систему регистрации на PHP и MySQL. Создание и проверка форм Точный users registration php

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

Создание форм в Laravel

Создавать формы в Laravel неожиданно просто. По большей части ничего не мешает вам использовать стандартные теги HTML, но Laravel может значитель облегчить вам жизнь. Скажем, класс PHP Form имеет метод PHP label () , позволяющий вам связать метки с полями формы используя соответствующие (автосгенерированные) ID. Давайте в качестве примера создадим простую форму:

PHP

Register!



?>

Всё очевидно, не так ли? Мы открываем форму POST -запроса на маршруте register , создаём несколько меток и полей ввода и добавляем CSRF-ключ, после чего закрываем форму. Если нам нужен безопасный маршрут (с использованием HTTPS ), то заменим вызов PHP Form :: open () на вызов PHP Form :: open_secure () , а если нам нужно создать форму для загрузки файлов, то пригодится PHP Form :: open_for_files () .

Вы наверняка заметили некие вызовы PHP Input :: old () - о них мы поговорим , а пока просто запомните, что они здесь есть.

Класс Form содержит множество методов для простого создания форм - вы можете ознакомиться с ними в документации .

Подделка межсайтовых запросов (CSRF)

Я не буду вдаваться в подробности о CSRF - Jeff Atwood написал очень наглядную статью о том, что это такое и как этого избежать.

Метод Form::token() создаёт случайную последовательность символов, сохраняет её в данных сессии (это значит, что вам нужно включить их поддержку в application/config/session.php) и выводит её в виде скрытого поля формы. При обработке запроса от формы, использующей CSRF-ключ мы можем использовать встроенный фильтр csrf для проверки того, что никто не «поработал» над запросом и он действительно исходит от пользователя.

Вот как выглядит код фильтра (файл application/routes.php ):

PHP Route :: filter ("csrf" , function () {
if (Request :: forged ()) return Response :: error ("500" );
});

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

PHP Route :: post ("register" , array("before" => "csrf" , function () {
// регистрация нового пользователя.
}));

Вот и всё, что нам нужно для включения CSRF-фильтра - просто убедится, что он указан в списке before .

Проверка введённых данных

Теперь, когда мы удостоверились, что пришедшему запросу можно доверять, нам нужно проверить данные, которые ввёл в форму пользователь. Вернёмся к нашему марштуру register , добавим туда проверку, а затем я объясню, что к чему.

Несколько человек заметили, что проверка не должна выполняться в контроллере. Обычно лучше всего делать это в модели - моя следующая статья «Продвинутая проверка ввода в Laravel » описывает именно этот способ решения задачи.

PHP // файл application/routes.php.

Route :: post ("register" , array("before" => "csrf" , function () {
$rules = array(
"username" => array("required" , "unique:users,username" ),
"email" => array("required" , "email" , "unique:users,email" ),
"password" => array("required" , "min:7" )
);

$validation = Validator :: make (Input :: all (), $rules );

If ($validation -> fails ()) {
// проверка не пройдена.
return Redirect :: to ("register" )-> with_input ()-> with_errors ($validation );
}

// данные прошли проверку - можем создавать нового пользователя.
}));

  1. Определяем массив правил - ключи соответствуют именам полей ввода формы, значения - правилам, которым они должны соответствовать. В нашем случае поле username («имя пользователя» ) должно быть заполнено (required) и уникально (unique).
  2. Создаём объект PHP Validator - первым параметром он принимает данные для проверки (в нашем случае данные формы, полученные через POST ), вторым - набор правил.
  3. Затем мы выполняем проверку - если она не прошла, переадресуем пользователя обратно к маршруту register (используя GET ) со старым вводом и сообщениями об ошибках.
  4. Если же все поля заполнены верно - регистрируем новую учётную запись, авторизуем пользователя, либо делаем что-то ещё.

Последовательность действий, которые мы здесь выполняем, называют шаблоном «Post/Redirect/Get » (PRG) - это отличный способ предотвратить двойную отправку формы.

Теперь посмотрим на правила, которые мы определили выше.

required - обозначает, что поле должно быть заполнено - иными словами, оно должно иметь значение.

unique - здесь немного более сложный момент. Это правило принимает 3 параметра, 2 из которых можно опустить. Первый параметр - имя таблицы, в котором нужно проверять значение на уникальность; второй - имя поля в таблице, если оно не соответствует имени поля в форме (в этом случае его можно пропустить); третий и последний параметр - значение (id ) для первичного ключа.

Предположим, что мы обновляем существующий профиль пользователя - мы точно так же хотим, чтобы его e-mail был уникальным, но если он решил не изменять свой адрес, то нам не стоит говорить, что введённый e-mail уже занят - им самим. Для этого мы и передаём ID пользователя - Laravel исключит соответствующую запись из проверки.

PHP $rules = array(
"email" => array("required" , "email" , "unique:users,email," . $user -> id )
);

e-mail - проверяет, что введённое значение похоже на правильный e-mail адрес, но не проверяет его на существование .

min - устанавливает минимально допустимую длину значения данного поля.

Полный список доступных правил можно найти в документации .

Отображение ошибок

Свойство PHP $validation -> errors содержит тот же объект Messages со всеми ошибками, найденными во входных данных. Laravel определит, что была выполнена переадресация с ошибками и автоматически привяжет этот объект к представлению . Вы скоро поймёте, что я имею в виду.

Помните вызовы PHP Input :: old () в ? Когда мы переадресовываем запрос со вводом они вернут значения, которые пользователь ввёл в форму ранее. Поэтому если я сказал, что моё имя - «Jason» , но регистрация не произошла, «Jason» останется введённым даже после переадресации меня обратно на форму. Отлично!

Поля ввода паролей изначально не имеют значения по умолчанию, но вы можете задать его явно используя массив атрибутов :

PHP echo Form :: password ("password" , array("value" => Input :: old ("password" )));

Вернёмся к нашей форме. Как вы помните, у нас есть переменная $errors - объект PHP Messages . Давайте сделаем нашу форму более дружелюбной, отображая ошибки, когда она была неверно заполнена:

PHP

Register!

Echo Form :: open ("register" , "POST" );

echo Form :: label ("username" , "Username" ) . Form :: text ("username" , Input :: old ("username" ));

if ($errors -> has ("username" )) {
echo $errors -> first ("username" );
}

echo Form :: label ("email" , "E-mail" ) . Form :: text ("email" , Input :: old ("email" ));

if ($errors -> has ("email" )) {
echo $errors -> first ("email" );
}

echo Form :: label ("password" , "Password" ) . Form :: password ("password" );

if ($errors -> has ("password" )) {
echo $errors -> first ("password" );
}

echo Form :: submit ("Register!" );

echo Form :: token () . Form :: close ();

?>

Сообщения будут показаны только в случае, когда определённое поле содержит ошибки.

Вы можете отформатировать сообщение в нужный HTML передав его во втором параметре:

PHP echo $errors -> first ("username" , ":message" );

Либо, если вы хотите отобразить первое сообщение об ошибке для любого поля, а не только для username : )); ?>

PHP $errors -> all () возвращает массив отформатированных сообщений, поэтому мы объединяем его в строку.

Собственные правила и ошибки

Часто вам понадобится создавать собственные правила для проверки ввода. До Laravel 3 это делалось наследованием класса Validator и добавлением к нему методов. С поддержкой пакетов потребовалось более надёжное решение, чтобы не создавать множество подклассов. Laravel 3 позволяет регистрировать произвольные правила с помощью PHP Validator :: register () :

PHP // этот код может быть помещён, например, в application/start.php:
Validator :: register ("starts_with" , function ($attribute , $value , $parameters ) {
return starts_with ($value , $parameters [ 0 ]);
});

В этом простом обработчике мы просто возвращаем true , если значение начинается на указанную строку (переданную в первом и единственном параметре), и false в противном случае. Здесь используется одна из немногих глобальных функций Laravel - PHP starts_with () .

Использование нового правила:

PHP $rules = array(
"website" => array("required" , "starts_with:http://" )
);

Здесь нам потребовалось определить поле как обязательное («required» ). Крмое этого нам также нужно добавить сообщение об ошибке в файл application/language/en/validation.php :

PHP "custom" => array(
"website_starts_with" => "Website must start with http://"
)

Либо можно это сделать при создании экземпляра Validator , передав его в третьем параметре :

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

В основном, для передачи параметров используются методы POST и GET .
Главное отличие методов POST и GET заключается в способе передачи информации. В методе GET параметры передаются через адресную строку (URL ), т.е. в HTTP -заголовке запроса, в то время как в методе POST параметры передаются через тело HTTP -запроса и никак не отражаются в адресной строке.

1. Кнопки – Тег

Тег обязателен.
Параметры:
disabled – блокирует доступ и изменение элемента.
type – тип кнопки
value – Значение кнопки, которое будет отправлено на сервер или прочитано с помощью сприптов.


Параметр DISABLED
Блокирует доступ и изменение кнопки. Она в таком случае отображается серой и недоступной для активации пользователем. Кроме того, такая кнопка не может получить фокус путем нажатия на клавишу Tab , мышью или другим способом. Тем не менее, такое состояние кнопки можно изменять через скрипты.

Параметр TYPE
Определяет тип кнопки, который устанавливает ее поведение в форме. По внешнему виду кнопки разного типа никак не различаются, но у каждой такой кнопки свои функции. Значение по умолчанию: button .
Аргументы:
button – Обычная кнопка.
reset – Кнопка для очистки введенных данных формы и возвращения значений в первоначальное состояние.

Submit – Кнопка для отправки данных формы на сервер.

Параметр VALUE Определяет значение кнопки, которое будет отправлено на сервер. На сервер отправляется пара «имя=значение », где имя задается параметром name тега

1.1. Кнопка (input type=button)
1.2. Кнопка с изображением (input type=image)

Кнопки с изображениями аналогичны по действию кнопке Submit , но представляют собой рисунок. Для этого задаем type=image и src="image.gif" .

Когда пользователь щелкнет где-нибудь на изображении, соответствующая форма будет передана на сервер с двумя дополнительными переменными – sub_x и sub_y . Они содержат координаты нажатия пользователя на изображение. Опытные программисты могут заметить, что на самом деле имена переменных, отправленных браузером, содержат точку, а не подчеркивание, но PHP автоматически конвертирует точку в подчеркивание.

1.3. Кнопка отправки формы (input type=submit)

Служит для отправки формы сценарию. При создании кнопки для отправки формы необходимо указать 2 атрибута: type="submit" и value="Текст кнопки" . Атрибут name необходим, если кнопка не одна, а несколько и все они созданы для разных операций, например кнопки "Сохранить", "Удалить", "Редактировать" и т.д. После нажатия на кнопку сценарию передается строка имя=текст кнопки.


РНР -сценарий не требуется.

1.4. Массив кнопок (submit) для выбора варианта действий
2. Кнопка сброса формы (Reset)

При нажатии на кнопку сброса (reset ), все элементы формы будут установлены в то состояние, которое было задано в атрибутах по умолчанию, причем отправка формы не производиться.


РНР -сценарий не требуется.

3. Флажок (checkbox)

Флажки checkbox предлагают пользователю ряд вариантов, и разрешает произвольный выбор (ни одного, одного или нескольких из них).

Белый
Зеленый
Синий
Красный
Черный
$go) { echo $index." - > ".$go."
"; }; };

4. Переключатель(radio)

Переключатели radio предлагают пользователю ряд вариантов, но разрешает выбрать только один из них.
Пример 1.

Белый
Зеленый
Синий
Красный
Черный

Пример 2.
// первый набор кнопок
// второй набор кнопок
// третий набор кнопок
\n"; ?>

5. Текстовое поле (text)

При создании обычного текстового поля размером size и максимальной допустимой длины maxlength символов, атрибут type принимает значение text . Если указан параметр value , то поле будет отображать указанный в переменной value. При создании поля не забывайте указывать имя поля, т.к. этот атрибут является обязательным.

6. Поле для ввода пароля (password)

Полностью аналогичен текстовому полю, за исключением того, что символы, набираемые пользователем, не будут отображаться на экране.

7. Скрытое текстовое поле (hidden)

Позволяет передавать сценарию какую то служебную информацию, не отображая её на странице.

8. Выпадающий список (select)

Тэг . Теги позволяют определить содержимое списка, а параметр value определяет значение строки. Если в теге указан параметр selected , то строка будет изначально выбранной. Параметр size задает, сколько строк будет занимать список. Если size равен 1 , то список будет выпадающим. Если указан атрибут multiple , то разрешено выбирать несколько элементов из списка. Но эта схема практически не используется, а при size = 1 не имеет смысла.

Если необходимо создать выпадающий с предсказуемой последовательностью. Например, список с годами с 2000 по 2050. То используется следующий прием.

9. Многострочное поле ввода текста (textarea)

Многострочное поле ввода текста позволяет отправлять не одну строку, а сразу несколько. При необходимости можно указать атрибут readonly , который запрещает редактировать, удалять и изменять текст, т.е. текст будет предназначен только для чтения. Если необходимо чтобы текст был изначально отображен в многострочном поле ввода, то его необходимо поместить между тэгами .
Существует параметр wrap – задание переноса строк. Возможные значения:
off – отключает перенос строк;
virtuals – показывает переносы строк, но отправляет текст как он введен;
physical – переносы строк оставляются в исходном виде.
По умолчанию тег

Для того, чтобы в многострочном текстовом поле соблюдалось html-форматирование (перенос строк по средством тега
или
), то используйте функцию nl2br() :

10. Кнопка для загрузки файлов (browse)

Служит для реализации загрузки файлов на сервер. При создании текстового поля также необходимо указать тип поля type как "file" .

Загрузить файл:

Способы общения браузера с сервером

Способов, предоставляемых протоколом HTTP , немного. Это важная информация. Никаких других способов нет. На практике используются два:
GET – это когда данные передаются в адресной строке, например, когда пользователь жмет ссылку.
POST – когда он нажимает кнопку в форме.

Метод GET

Чтобы передать данные методом GET не надо создавать на HTML -странице форму (использовать формы для запросов методом GET вам никто не запрещает) – достаточно ссылки на документ с добавлением строки запроса, которая может выглядеть как переменная=значение. Пары объединяются с помощью амперсанда &, а к URL страницы строка присоединяется с помощью вопросительного знака «? ».
Но можно не использовать пары ключ=значение, если надо передать всего одну переменную – для этого надо после знака вопроса написать ЗНАЧЕНИЕ (не имя) переменной.
Преимущество передачи параметров таким способом заключается в том, что клиенты, которые не могут использовать метод POST (например, поисковые машины), все же смогут, просто пройдя по ссылке, передать параметры скрипту и получить содержимое.
Недостаток в том, что просто изменив параметры в адресной строке, пользователь может повернуть ход сценария непредсказуемым образом и это создает огромную дыру в безопасности, в сочетании с неопределенными переменными и register_globals on или кто-нибудь может узнать значение важной переменной (например ID -сеcсии), просто посмотрев на экран монитора.
:
- для доступа к общедоступным страницам с передачей параметров (повышение функциональности)
- передача информации, не влияющей на уровень безопасности
:
- для доступа к защищенным страницам с передачей параметров
- для передачи информации, влияющей на уровень безопасности
- для передачи информации, не подлежащей модифицированию пользователем (некоторые передают текст SQL -запросов.

Метод POST

Передать данные методом POST можно только с помощью формы на HTML странице. Основное отличие POST от GET в том, что данные передаются не в заголовке запроса а в теле, следовательно, пользователь их не видит. Модифицировать можно только изменив саму форму.
Преимущество :
- большая безопасность и функциональность запросов с помощью форм методом POST .
Недостаток :
- меньшая доступность.
Для чего следует использовать :
- для передачи большого объема информации (текст, файлы..);
- для передачи любой важной информации;
- для ограничения доступа (например, использовать для навигации только форму – возможность, доступная не всем программам-роботам или грабберам-контента).
Для чего не следует использовать :

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

//Форма для загрузки файлов

Отправить этот файл:

В приведенном выше примере "URL " необходимо заменить ссылкой на PHP -скрипт. Скрытое поле MAX _FILE_SIZE (значение необходимо указывать в байтах) должно предшествовать полю для выбора файла, и его значение является максимально допустимым размером принимаемого файла. Также следует убедиться, что в атрибутах формы вы указали enctype="multipart/form-data" , в противном случае загрузка файлов на сервер выполняться не будет.
Внимание
Опция MAX _FILE_SIZE является рекомендацией браузеру, даже если бы PHP также проверял это условие. Обойти это ограничение на стороне браузера достаточно просто, следовательно, вы не должны полагаться на то, что все файлы большего размера будут блокированы при помощи этой возможности. Тем не менее, ограничение PHP касательно максимального размера обойти невозможно. Вы в любом случае должны добавлять переменную формы MAX _FILE_SIZE , так как она предотвращает тревожное ожидание пользователей при передаче огромных файлов, только для того, чтобы узнать, что файл слишком большой и передача фактически не состоялась.

Как определить метод запроса?

Напрямую:

Getenv("REQUEST_METHOD");

вернет GET или POST .

Какой способ следует применять?

Если форма служит для запроса некой информации, например – при поиске, то ее следует отправлять методом GET . Чтобы можно было обновлять страницу, можно было поставить закладку и/или послать ссылку другу.
Если же в результате отправки формы данные записываются или изменяются на сервере, то следует их отправлять методом POST , причем обязательно, после обработки формы, надо перенаправить браузер методом GET . Так же, POST может понадобиться, если на сервер надо передать большой объём данных (у GET он сильно ограничен), а так же, если не следует "светить" передаваемые данные в адресной строке (при вводе логина и пароля, например).
В любом случае, после обработки POST надо всегда перенаправить браузер на какую-нибудь страницу, пусть ту же самую, но уже без данных формы, чтобы при обновлении страницы они не записывались повторно.

Как передать данные в другой файл непосредственно из тела PHP -программы методом GET и POST ?

Пример, для демонстрации отправки данных методом POST и GET одновременно и получения ответа от сервера.

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. 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.

In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged-in users. Any other user not logged in will not be able to access the page.

Learn how to create a complete blog with PHP and MySQL database with my free course on YouTube .

The first thing we"ll need to do is set up our database.

Create a database called registration . In the registration database, add a table called users . The users table will take the following four fields.

  • username - varchar(100)
  • email - varchar(100)
  • password - varchar(100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;

And that"s it with the database.

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).

Inside the folder registration, create the following files:

Open these files up in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the register.php file and paste the following code in it:

regiser.php:

Register

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

First is that our form"s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that"s why we are including it at the very top of the register.php file.

Notice also that we are including the errors.php file to display form errors. We will come to that soon.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:

* { margin: 0px; padding: 0px; } body { font-size: 120%; background: #F8F8FF; } .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px; } form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px; } .input-group { margin: 10px 0px 10px 0px; } .input-group label { display: block; text-align: left; margin: 3px; } .input-group input { height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray; } .btn { padding: 10px; font-size: 15px; color: white; background: #5F9EA0; border: none; border-radius: 5px; } .error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left; } .success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px; }

Now the form looks beautiful.

Let"s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.

Open server.php and paste this code in it:

server.php

Sessions are used to track logged in users and so we include a session_start() at the top of the file.

The comments in the code pretty much explain everything, but I"ll highlight a few things here.

The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.

All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

0) : ?>

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that"s it for registration. Let"s look at user login.

Login user

Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:

Registration system PHP and MySQL

Login

Not yet a member? Sign up

Everything on this page is quite similar to the register.php page.

Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:

// ... // LOGIN USER if (isset($_POST["login_user"])) { $username = mysqli_real_escape_string($db, $_POST["username"]); $password = mysqli_real_escape_string($db, $_POST["password"]); if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM users WHERE username="$username" AND password="$password""; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { $_SESSION["username"] = $username; $_SESSION["success"] = "You are now logged in"; header("location: index.php"); }else { array_push($errors, "Wrong username/password combination"); } } } ?>

Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.

Now let"s see what happens in the index.php file. Open it up and paste the following code in it:

Home

Home Page

Welcome

logout

The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you"d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.

The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.