Бесчувственный create account php.

Итак, представим, что у нас есть уже готовое php+mysql приложение. Для начала регистрируемся . На почту придет письмо с подтверждением регистрации. Далее переходим по ссылке, вводим пароль и подтверждение, жмем save. Первый этап пройден, идем дальше.

После успешной регистрации сервис предлагает нам скачать клиент. Естественно, для каждой ОСи свой вариант установки. Далее будем рассматривать пример для UNIX.

Пишем в консоли:

Wget -qO- https://toolbelt.heroku.com/install.sh | sh

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

После установки нужно войти в приложение:

$ heroku login

Вводим email и пароль. Приложение должно вас авторизовать и автоматически загрузить ваш публичный ssh ключ. Если этого не произошло, заходим в свой аккаунт (https://dashboard.heroku.com/account) и добавляем публичный ssh:

Чтобы посмотреть публичный ssh, пишем в консоли:

$ cat ~/.ssh/id_rsa.pub

Ключи также можно добавить с помощью команды:

$ heroku keys:add

Итак, все готово для того, чтобы создать свое первое «heroku приложение». Заходим в директорию, где хранится наше приложение, и пишем в консоли:

$ heroku create

В результате вы должны увидеть что-то похоже на это:

$ git push heroku master

После чего пишем в консоли:

$ heroku open

Наш сайт откроется в браузере. Если бы мы не юзали mysql, то на этом все бы и закончилось, но нам придется еще чуть попотеть. Скорее всего, на экране полезли ошибки о том, что невозможно соединиться с mysql. Также ошибки можно посмотреть, открыв логи:

$ heroku logs

Для работы с mysql будем использовать аддон ClearDB . Чтобы его установить, для начала необходимо заполнить данные о вашей кредитной карте на странице dashboard.heroku.com/account :

Если этого не сделать, при установке ClearDB вы будете видеть ошибку:

Adding cleardb:ignite on dry-taiga-2649... failed
! Please verify your account to install this add-on
! For more information, see devcenter.heroku.com/categories/billing
! Verify now at heroku.com/verify

Ниже команда для установки ClearDB:

$ heroku addons:add cleardb:ignite в

ClearDB установлен, теперь посмотрим доступы к базе данных:

$ heroku config

Получим результат в виде:

CLEARDB_DATABASE_URL:mysql://USER:PASSWORD@HOSTNAME/DBASENAME?reconnect=true

Используя полученные доступы через любой удобный MySQL клиент заливаем дамп БД на сервер.

Доступы к базе в php можно получить следующим образом:

$url=parse_url(getenv("CLEARDB_DATABASE_URL")); $server = $url["host"]; $username = $url["user"]; $password = $url["pass"]; $db = substr($url["path"],1); mysqli_connect($server, $username, $password); mysqli_select_db($db);

Чтобы каждый раз не менять конфиг для локального сайта и heroku, можно добавить проверку:

If ($_SERVER["SERVER_NAME"] == "thawing-island-242342379.herokuapp.com") { $url = parse_url(getenv("CLEARDB_DATABASE_URL")); $host = $url["host"]; $username = $url["user"]; $password = $url["pass"]; $dbname = substr($url["path"], 1); } else { $host = "localhost"; $dbname = "db"; $username = "user"; $password = "123"; }

Было бы правильней это сделать через APPLICATION_ENV, но я не нашел информации о том, как это сделать. Если кто-то в курсе - напишите.

Почти все готово. Осталось добавить в корень файл composer.json:

{ "require": { "ext-mysql": "*" } }

Если такой уже есть, нужно просто дописать "ext-mysql": "*"

Пишем в консоли:

$ git add . $ git commit -am "added db credentials" $ git push heroku master $ heroku open

Открывается браузер, видим рабочий сайт.

Буду рад если этот «мануал» кому то поможет.

Всем спасибо з а внимание.

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.


Account verification is very important whenever new user registered or signup on your website. Whenever a new user register a verification code with link is sent on his email id and if the user is genuine he clicks on link with code sent on his email id and then he verified himself for website.In this tutorial we will create and Account Verification System through Email using PHP.You may also like Send Email Using PHP

To Create Account Verification System it takes only Two steps:-

  1. Make a HTML file and define markup and script for Registration form
  2. Make a PHP file to insert data and email the code

Step 1.Make a HTML file and define markup and script for Registration form

We make a HTML file and save it with a name registration.html

< form method="post" action="verification.php"> < input type="text" name="email"> < input type="password" name="password"> < input type="submit" name="register" Value="Register"> < /form>


In this step we make a registration form that sends all the user data to verification.php page

Step 2.Make a PHP file to insert data and email the code

We make a PHP file named verification.php

Verify.php?id=".$db_id."&code=".$code."< /a> to activate your account."; $headers = "From:".$from; mail($to,$subject,$body,$headers); echo "An Activation Code Is Sent To You Check You Emails"; } if(isset($_GET["id"]) && isset($_GET["code"])) { $id=$_GET["id"]; $code=$_GET["id"]; mysql_connect("localhost","root",""); mysql_select_db("sample"); $select=mysql_query("select email,password from verify where id="$id" and code="$code""); if(mysql_num_rows($select)==1) { while($row=mysql_fetch_array($select)) { $email=$row["email"]; $password=$row["password"]; } $insert_user=mysql_query("insert into verified_user values("","$email","$password")"); $delete=mysql_query("delete from verify where id="$id" and code="$code""); } } ?>


In this step we make two isset() conditions to insert and verify the user.In first condition we get all user submitted data and insert in our verify table which is used as temporary user table and then we send the code with activation link to the user email id which he enters in registration form we use simple mail() function to send email you can also use SMTP to send email.In second condition we get the id and code value from the link when user clicks on link send to his email id and and then get all the user data from verify table and insert in verified_user table and then delete that user from verify table beacuse user verified his account.You may also like validate email and password using jQuery .


Remember always validate data before inserting in database if you want to know to how to validate you can refer our tutorial


Thats all, this is how to Create Account Verification System Through Email Using PHP.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Hello, My Name is Mudit Jain. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of TalkersCode. I started this blog in february 2015 to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers.

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.

If you prefer a video, you can watch it on my YouTube channel

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.