Пропойца member register php.

A tutorial for the very beginner! No matter where you go on the Internet, there"s a staple that you find almost everywhere - user registration. Whether you need your users to register for security or just for an added feature, there is no reason not to do it with this simple tutorial. In this tutorial we will go over the basics of user management, ending up with a simple Member Area that you can implement on your own website.

If you need any extra help or want a shortcut, check out the range of PHP service providers on Envato Studio. These experienced developers can help you with anything from a quick bug fix to developing a whole app from scratch. So just browse the providers, read the reviews and ratings, and pick the right one for you.

Introduction

In this tutorial we are going to go through each step of making a user management system, along with an inter-user private messaging system. We are going to do this using PHP, with a MySQL database for storing all of the user information. This tutorial is aimed at absolute beginners to PHP, so no prior knowledge at all is required - in fact, you may get a little bored if you are an experienced PHP user!

This tutorial is intended as a basic introduction to Sessions, and to using Databases in PHP. Although the end result of this tutorial may not immediately seem useful to you, the skills that you gain from this tutorial will allow you to go on to produce a membership system of your own; suiting your own needs.

Before you begin this tutorial, make sure you have on hand the following information:

  • Database Hostname - this is the server that your database is hosted on, in most situations this will simply be "localhost".
  • Database Name, Database Username, Database Password - before starting this tutorial you should create a MySQL database if you have the ability, or have on hand the information for connecting to an existing database. This information is needed throughout the tutorial.

If you don"t have this information then your hosting provider should be able to provide this to you.

Now that we"ve got the formalities out of the way, let"s get started on the tutorial!

Step 1 - Initial Configuration

Setting up the database

As stated in the Introduction, you need a database to continue past this point in the tutorial. To begin with we are going to make a table in this database to store our user information.

The table that we need will store our user information; for our purposes we will use a simple table, but it would be easy to store more information in extra columns if that is what you need. In our system we need the following four columns:

  • UserID (Primary Key)
  • Username
  • Password
  • EmailAddress

In database terms, a Primary Key is the field which uniquely identifies the row. In this case, UserID will be our Primary Key. As we want this to increment each time a user registers, we will use the special MySQL option - auto_increment .

The SQL query to create our table is included below, and will usually be run in the "SQL" tab of phpMyAdmin.

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);

Creating a Base File

In order to simplify the creation of our project, we are going to make a base file that we can include in each of the files we create. This file will contain the database connection information, along with certain configuration variables that will help us out along the way.

Start by creating a new file: base.php , and enter in it the following code:

Let"s take a look at a few of those lines shall we? There"s a few functions here that we"ve used and not yet explained, so let"s have a look through them quickly and make sense of them -- if you already understand the basics of PHP, you may want to skip past this explanation.

Session_start();

This function starts a session for the new user, and later on in this tutorial we will store information in this session to allow us to recognize users who have already logged in. If a session has already been created, this function will recognize that and carry that session over to the next page.

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

Each of these functions performs a separate, but linked task. The mysql_connect function connects our script to the database server using the information we gave it above, and the mysql_select_db function then chooses which database to use with the script. If either of the functions fails to complete, the die function will automatically step in and stop the script from processing - leaving any users with the message that there was a MySQL Error.

Step 2 - Back to the Frontend

What Do We Need to Do First?

The most important item on our page is the first line of PHP; this line will include the file that we created above (base.php), and will essentially allow us to access anything from that file in our current file. We will do this with the following line of of PHP code. Create a file named index.php , and place this code at the top.

Begin the HTML Page

The first thing that we are going to do for our frontend is to create a page where users can enter their details to login, or if they are already logged in a page where they can choose what they then wish to do. In this tutorial I am presuming that users have basic knowledge of how HTML/CSS works, and therefore am not going to explain this code in detail; at the moment these elements will be un-styled, but we will be able to change this later when we create our CSS stylesheet.

Using the file that we have just created (index.php), enter the following HTML code below the line of PHP that we have already created.

What Shall We Show Them?

Before we output the rest of the page we have a few questions to ask ourselves:

  1. Is the user already logged in?
  • Yes - we need to show them a page with options for them to choose.
  • No
  • Has the user already submitted their login details?
    • Yes - we need to check their details, and if correct we will log them into the site.
    • No - we continue onto the next question.
  • If both of the above were answered No , we can now assume that we need to display a login form to the user.
  • These questions are in fact, the same questions that we are going to implement into our PHP code. We are going to do this in the form of if statements . Without entering anything into any of your new files, lets take a look at the logic that we are going to use first.

    Looks confusing, doesn"t it? Let"s split it down into smaller sections and go over them one at a time.

    If(!empty($_SESSION["LoggedIn"]) && !empty($_SESSION["Username"])) { // let the user access the main page }

    When a user logs into our website, we are going to store their information in a session - at any point after this we can access that information in a special global PHP array - $_SESSION . We are using the empty function to check if the variable is empty, with the operator ! in front of it. Therefore we are saying:

    If the variable $_SESSION["LoggedIn"] is not empty and $_SESSION["Username"] is not empty, execute this piece of code.

    The next line works in the same fashion, only this time using the $_POST global array. This array contains any data that was sent from the login form that we will create later in this tutorial. The final line will only execute if neither of the previous statements are met; in this case we will display to the user a login form.

    So, now that we understand the logic, let"s get some content in between those sections. In your index.php file, enter the following below what you already have.

    Member Area

    and your email address is .

    Success"; echo "

    We are now redirecting you to the member area.

    "; echo ""; } else { echo "

    Error

    "; echo "

    Sorry, your account could not be found. Please click here to try again.

    "; } } else { ?>

    Member Login

    Thanks for visiting! Please either login below, or click here to register.



    Hopefully, the first and last code blocks won"t confuse you too much. What we really need to get stuck into now is what you"ve all come to this tutorial for - the PHP code. We"re now going to through the second section one line at a time, and I"ll explain what each bit of code here is intended for.

    $username = mysql_real_escape_string($_POST["username"]); $password = md5(mysql_real_escape_string($_POST["password"]));

    There are two functions that need explaining for this. Firstly, mysql_real_escape_string - a very useful function to clean database input. It isn"t a failsafe measure, but this will keep out the majority of the malicious hackers out there by stripping unwanted parts of whatever has been put into our login form. Secondly, md5 . It would be impossible to go into detail here, but this function simply encrypts whatever is passed to it - in this case the user"s password - to prevent prying eyes from reading it.

    $checklogin = mysql_query("SELECT * FROM users WHERE Username = "".$username."" AND Password = "".$password."""); if(mysql_num_rows($checklogin) == 1) { $row = mysql_fetch_array($checklogin); $email = $row["EmailAddress"]; $_SESSION["Username"] = $username; $_SESSION["EmailAddress"] = $email; $_SESSION["LoggedIn"] = 1;

    Here we have the core of our login code; firstly, we run a query on our database. In this query we are searching for everything relating to a member, whose username and password match the values of our $username and $password that the user has provided. On the next line we have an if statement, in which we are checking how many results we have received - if there aren"t any results, this section won"t be processed. But if there is a result, we know that the user does exist, and so we are going to log them in.

    The next two lines are to obtain the user"s email address. We already have this information from the query that we have already run, so we can easily access this information. First, we get an array of the data that has been retrieved from the database - in this case we are using the PHP function mysql_fetch_array . I have then assigned the value of the EmailAddress field to a variable for us to use later.

    Now we set the session. We are storing the user"s username and email address in the session, along with a special value for us to know that they have been logged in using this form. After this is all said and done, they will then be redirect to the Member Area using the META REFRESH in the code.

    So, what does our project currently look like to a user?

    Great! It"s time to move on now, to making sure that people can actually get into your site.

    Let the People Signup

    It"s all well and good having a login form on your site, but now we need to let user"s be able to use it - we need to make a login form. Make a file called register.php and put the following code into it.

    User Management System (Tom Cameron for NetTuts)

    Error"; echo "

    Sorry, that username is taken. Please go back and try again.

    "; } else { $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES("".$username."", "".$password."", "".$email."")"); if($registerquery) { echo "

    Success

    "; echo "

    Your account was successfully created. Please click here to login.

    "; } else { echo "

    Error

    "; echo "

    Sorry, your registration failed. Please go back and try again.

    "; } } } else { ?>

    Register

    Please enter your details below to register.




    So, there"s not much new PHP that we haven"t yet learned in that section. Let"s just take a quick look at that SQL query though, and see if we can figure out what it"s doing.

    $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES("".$username."", "".$password."", "".$email."")");

    So, here we are adding the user to our database. This time, instead of retrieving data we"re inserting it; so we"re specifying first what columns we are entering data into (don"t forget, our UserID will go up automatically). In the VALUES() area, we"re telling it what to put in each column; in this case our variables that came from the user"s input. So, let"s give it a try; once you"ve made an account on your brand-new registration form, here"s what you"ll see for the Member"s Area.

    Make Sure That They Can Logout

    We"re almost at the end of this section, but there"s one more thing we need before we"re done here - a way for user"s to logout of their accounts. This is very easy to do (fortunately for us); create a new filed named logout.php and enter the following into it.

    In this we are first resetting our the global $_SESSION array, and then we are destroying the session entirely.

    And that"s the end of that section, and the end of the PHP code. Let"s now move onto our final section.

    Step 3 - Get Styled

    I"m not going to explain much in this section - if you don"t understand HTML/CSS I would highly recommend when of the many excellent tutorials on this website to get you started. Create a new file named style.css and enter the following into it; this will style all of the pages that we have created so far.

    * { margin: 0; padding: 0; } body { font-family: Trebuchet MS; } a { color: #000; } a:hover, a:active, a:visited { text-decoration: none; } #main { width: 780px; margin: 0 auto; margin-top: 50px; padding: 10px; border: 1px solid #CCC; background-color: #EEE; } form fieldset { border: 0; } form fieldset p br { clear: left; } label { margin-top: 5px; display: block; width: 100px; padding: 0; float: left; } input { font-family: Trebuchet MS; border: 1px solid #CCC; margin-bottom: 5px; background-color: #FFF; padding: 2px; } input:hover { border: 1px solid #222; background-color: #EEE; }

    Now let"s take a look at a few screenshots of what our final project should look like:

    The login form.

    The member area.

    The registration form.

    And Finally...

    And that"s it! You now have a members area that you can use on your site. I can see a lot of people shaking their heads and shouting at their monitors that that is no use to them - you"re right. But what I hope any beginners to PHP have learned is the basics of how to use a database, and how to use sessions to store information. The vital skills to creating any web application.

    • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

    Будем учиться делать простую аутентификацию пользователей на сайте. На сайте могут быть страницы только для авторизованных пользователей и они будут полноценно функционировать, если добавить к ним наш блок аутентификации. Чтобы его создать, нужна база данных MySQL. Она может иметь 5 колонок (минимум), а может и больше, если вы хотите добавить информацию о пользователях. Назовём базу данных “Userauth”.

    Создадим в ней следующие поля: ID для подсчёта числа пользователей, UID для уникального идентификационного номера пользователя, Username для имени пользователя, Email для адреса его электронной почты и Password для пароля. Вы можете использовать для авторизации пользователя и уже имеющуюся у Вас базу данных, только, как и в случае с новой базой данных, создайте в ней следующую таблицу.

    Код MySQL

    CREATE TABLE `users` (`ID` int (11) NOT NULL AUTO_INCREMENT, `UID` int (11) NOT NULL, `Username` text NOT NULL, `Email` text NOT NULL, `Password` text NOT NULL, PRIMARY KEY (`ID`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    Теперь создадим файл "sql.php". Он отвечает за подключение к базе данных. Данный код, во первых, создаёт переменные для сервера и пользователя, когда он подключается к серверу. Во-вторых, он выберет базу данных, в данном случае "USERAUTH". Этот файл нужно подключить в "log.php" и "reg.php" для доступа к базе данных.

    Код PHP

    //Ваше имя пользователя MySQL $pass = "redere"; //пароль $conn = mysql_connect ($server, $user, $pass);//соединение с сервером $db = mysql_select_db ("userauth", $conn);//выбор базы данных if (!$db) { //если не может выбрать базу данных echo "Извините, ошибка:(/>";//Показывает сообщение об ошибке exit (); //Позволяет работать остальным скриптам PHP } ?>

    Далее страница входа, пусть она называется "login.php". Во-первых, она проверяет введённые данные на наличие ошибок. Страница имеет поля для имени пользователя, пароля, кнопку отправки и ссылку для регистрации. Когда пользователь нажмёт кнопку «Вход», форма будет обработана кодом из файла "log.php", а затем произойдёт вход в систему.

    Код PHP

    0) { //если есть ошибки сессии $err = "

    "; //Start a table foreach ($_SESSION["ERRMSG"] as $msg) {//распознавание каждой ошибки $err .= ""; //запись её в переменную } $err .= "
    " . $msg . "
    "; //закрытие таблицы unset ($_SESSION["ERRMSG"]); //удаление сессии } ?> Форма входа
    Имя пользователя
    Пароль
    Регистрация

    Затем пишем скрипт для входа в систему. Назовём его "log.php". Он имеет функцию для очистки входных данных от SQL-инъекций, которые могут испортить ваш скрипт. Во-вторых, он получает данные формы и проверяет их на правильность. Если входные данные правильны, скрипт отправляет пользователя на страницу авторизованных пользователей, если нет – устанавливает ошибки и отправляет пользователя на страницу входа.

    Код PHP

    //начало сессии для записи function Fix($str) { //очистка полей $str = trim($str); if (get_magic_quotes_gpc()) { $str = stripslashes ($str); } //массив для сохранения ошибок $errflag = false ; //флаг ошибки $username = Fix($_POST["username"]);//имя пользователя $password = Fix($_POST["password"]);//пароль } //проверка пароля if ($password == "") { $errmsg = "Password missing"; //ошибка $errflag = true ; //поднимает флаг в случае ошибки } //если флаг ошибки поднят, направляет обратно к форме регистрации //записывает ошибки session_write_close(); //закрытие сессии //перенаправление exit (); } //запрос к базе данных $qry = "SELECT * FROM `users` WHERE `Username` = "$username" AND `Password` = "" . md5 ($password) . """; $result = mysql_query ($qry); //проверка, был ли запрос успешным (есть ли данные по нему) if (mysql_num_rows ($result) == 1) { while ($row = mysql_fetch_assoc ($result)) { $_SESSION["UID"] = $row["UID"];//получение UID из базы данных и помещение его в сессию $_SESSION["USERNAME"] = $username;//устанавливает, совпадает ли имя пользователя с сессионным session_write_close(); //закрытие сессии header("location: member.php");//перенаправление } } else { $_SESSION["ERRMSG"] = "Invalid username or password"; //ошибка session_write_close(); //закрытие сессии header("location: login.php"); //перенаправление exit (); } ?>

    Сделаем страницу регистрации, назовём её "register.php". Она похожа на страницу входа, только имеет на несколько полей больше, а вместо ссылки на регистрацию – ссылку на login.php на случай, если у пользователя уже есть аккаунт.

    Код PHP

    0) { //если есть ошибки сессии $err = "

    "; //начало таблицы foreach ($_SESSION["ERRMSG"] as $msg) {//устанавливает каждую ошибку $err .= ""; //записывает их в переменную } $err .= "
    " . $msg . "
    "; //конец таблицы unset ($_SESSION["ERRMSG"]); //уничтожает сессию } ?> Форма регистрации
    Имя пользователя
    E-mail
    Пароль
    Повтор пароля
    У меня есть аккаунт

    Теперь сделаем скрипт регистрации в файле "reg.php". В него будет включён "sql.php" для подключения к к базе данных. Используется и та же функция, что и в скрипте входа для очистки поля ввода. Устанавливаются переменные для возможных ошибок. Далее – функция для создания уникального идентификатора, который никогда ранее не предоставлялся. Затем извлекаются данные из формы регистрации и проверяются. Происходит проверка, что адрес электронной почты указан в нужном формате, а также, правильно ли повторно указан пароль. Затем скрипт проверяет, нет ли в базе данных пользователя с таким же именем, и, если есть, сообщает об ошибке. И, наконец, код добавляет пользователя в базу данных.

    Код PHP

    //начало сессии для записи function Fix($str) { //очистка полей $str = @trim($str); if (get_magic_quotes_gpc()) { $str = stripslashes ($str); } return mysql_real_escape_string ($str); } $errmsg = array (); //массив для хранения ошибок $errflag = false ; //флаг ошибки $UID = "12323543534523453451465685454";//уникальный ID $username = Fix($_POST["username"]);//имя пользователя $email = $_POST["email"]; //Email $password = Fix($_POST["password"]);//пароль $rpassword = Fix($_POST["rpassword"]);//повтор пароля //проверка имени пользователя if ($username == "") { $errmsg = "Username missing"; //ошибка $errflag = true ; //поднимает флаг в случае ошибки } //проверка Email if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@+(\.+)*(\.{2,3})$", $email)) { //должен соответствовать формату: [email protected] $errmsg = "Invalid Email"; //ошибка $errflag = true ; //поднимает флаг в случае ошибки } //проверка пароля if ($password == "") { $errmsg = "Password missing"; //ошибка $errflag = true ; //поднимает флаг в случае ошибки } //проверка повтора пароля if ($rpassword == "") { $errmsg = "Repeated password missing";//ошибка $errflag = true ; //поднимает флаг в случае ошибки } //проверка валидности пароля if (strcmp($password, $rpassword) != 0) { $errmsg = "Passwords do not match";//ошибка $errflag = true ; //поднимает флаг в случае ошибки } //проверка, свободно ли имя пользователя if ($username != "") { $qry = "SELECT * FROM `users` WHERE `Username` = "$username""; //запрос к MySQL $result = mysql_query ($qry); if ($result) { if (mysql_num_rows ($result) > 0) {//если имя уже используется $errmsg = "Username already in use"; //сообщение об ошибке $errflag = true; //поднимает флаг в случае ошибки } mysql_free_result ($result); } } //если данные не прошли валидацию, направляет обратно к форме регистрации if ($errflag) { $_SESSION["ERRMSG"] = $errmsg; //сообщение об ошибке session_write_close(); //закрытие сессии header("location: register.php");//перенаправление exit (); } //добавление данных в базу $qry = "INSERT INTO `userauth`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES("$UID","$username","$email","" . md5 ($password) . "")"; $result = mysql_query ($qry); //проверка, был ли успешным запрос на добавление if ($result) { echo "Благодарим Вас за регистрацию, " .$username . ". Пожалуйста, входите сюда"; exit (); } else { die ("Ошибка, обратитесь позже"); } ?>

    Ещё нужно сделать скрипт для выхода пользователя из системы. Он прекращает сессию для пользователя с данным уникальным идентификатором и именем, а затем перенаправляет пользователя на страницу входа в систему.

    Код PHP

    И, наконец, скрипт "auth.php" можно использовать, чтобы сделать страницы доступными только для авторизованных пользователей. Он проверяет данные входа и, если они верны, позволяет пользователю просматривать страницы, а если нет, просит авторизоваться. Кроме того, если кто-то попытается взломать сайт создав одну из сессий, она будет прервана, как в общем случае.

    Код PHP

    Одно из условий в коде выше является предметом вопроса в .

    Следующий код нужно вставить на страницу для авторизованных пользователей, она называется, например, "member.php", а у Вас может называться как угодно.

    Код PHP

    Вам разрешён доступ к этой странице. Выйти ( )

    Аутентификация пользователей готова!

    When your professor says they need a Turabian style paper, you have even more work to do because this is not a common format in academic writing. Now that your academic papers contribute a large percentage to your final grade, it is important to get insight on the required formatting style to deliver a winning paper. This article explores Turabian style in detail to help you get started on your pending project. Keep reading.

    Turabian Writing Style In Brief

    Turabian writing style is an offshoot of the more common Chicago style of writing. The writing style is a brainchild of Kate Turabian, the dissertation secretary at the University of Chicago. It is a format mostly used in history papers though professors in other disciplines can request you to format their papers in the same style.

    While Chicago writing style focuses on formatting scholarly books, Kate Turabian appreciated the inherent advantages of this writing style. She went to work to refine the rules making them applicable for academic paper writing.

    Creating a title page in Turabian Format

    It is important to understand the main rules to follow when using Turabian format. The first thing that comes to mind is the title page. It is important to follow the Turabian rules as regards the title page because this will give your professor an idea of what to expect inside the paper.

    For the title, page of a Thesis/Dissertation in Turabian style writing the following rules;

    1. The page should include institution name and department; paper title/subtitle; submission statement; class information; your name; and date of submission.
    2. Use standard 12pt. font, which is consistent with the rest of the paper, and center and double-space the content.
    3. Place the paper’s title about one-third of the way down the page.
    4. The title page should not have a page number.

    Headings and Page Numbers

    In your Turabian style research paper, you need headings are used to organize your writing, make it easier to read and give it a hierarchical organization. You can have up to five levels of headings in your paper:

    • Level One: centered, boldface or italic type, headline-style capitalization and on its own line
    • Level two: Centered, standard type, headline-style capitalization on its own line
    • Level two: Left-justified, boldface or italic type, headline-style capitalization and on its own line
    • Level four: Left justified, standard type, sentence-style capitalization on its own line
    • Level five: Not on its own line, left-justified, no blank line after heading, boldface or italic type, sentence-style capitalization, ending with a period.

    When practicing how to write Turabian style, remember the page numbers should begin after the title page, and continue until the end of the body of the paper.

    Turabian Style Citations, End Notes, Footnotes and Bibliography

    One of the distinguishing features of the Turabian style is the use of endnotes and footnotes. It is one of the most important skills when learning how to set up Turabian style paper.

    To denote a footnote, you use a superscript number that follows the cited information in the content and directs the reader to the footnote at the bottom of the page which includes more information.

    Similarly, you need to indicate endnotes with a superscript number that follows the cited information. The number will direct the reader to the endnote at the back of the paper in a separate section. You use an endnote if a footnote will disrupt the flow of the paper.

    You have to cite all sources when using Turabian style to avoid plagiarism. Use Parenthetical citations which is the preferred method to indicate in-text citations. For quotations more than five lines, format the quotation as a block quotation.

    You should also have a reference list compiling sources in one list at the end of the paper. The format for citing books, journals, multi-media sources and other sources differs and you need to get it right.

    Understanding what is Turabian style takes some time and you can use a website that writes papers for you to learn more, read samples and get assistance from writing experts.