Parsing register form php. PHP scripts for processing HTML forms. You are already registered

Basically, methods are used to pass parameters POST And GET.
The main difference between the methods POST And GET lies in the method of transmitting information. In method GET parameters are passed via the address bar ( URL), i.e. V HTTP-request header, while in the method POST parameters are transmitted through the body HTTP-request and are not reflected in the address bar in any way.

1. Buttons – Tag

Tag required.
Options:
disabled– blocks access and modification of an element.
type– button type
value– The value of the button that will be sent to the server or read using sprips.


Parameter DISABLED
Blocks access and modification of the button. In this case, it is displayed gray and cannot be activated by the user. In addition, such a button cannot receive focus by pressing the key Tab, mouse or other method. However, this button state can be changed through scripts.

Parameter TYPE
Defines the button type, which sets its behavior on the form. The different types of buttons do not differ in appearance in any way, but each button has its own functions. Default value: button.
Arguments:
button– Regular button.
reset– A button to clear the entered form data and return the values ​​to their original state.

Submit – Button for sending form data to the server.

Parameter VALUE Defines the button value that will be sent to the server. A pair of " name=value", where the name is specified by the name parameter of the tag

1.1. Button (input type=button)
1.2. Button with an image (input type=image)

Buttons with images are similar in action to a button Submit, but represent a drawing. To do this we set type=image And src="image.gif".

When the user clicks anywhere on the image, the corresponding form will be submitted to the server with two additional variables − sub_x And sub_y. They contain the coordinates of the user clicking on the image. Experienced programmers may notice that the variable names sent by the browser actually contain a dot rather than an underscore, but PHP automatically converts the dot to an underscore.

1.3. Form submit button (input type=submit)

Serves to submit the form to the script. When creating a button to submit a form, you must specify 2 attributes: type="submit" And value="Button text" !}. The name attribute is required if there is not one button, but several and they are all created for different operations, for example, the “Save”, “Delete”, “Edit” buttons, etc. After clicking the button, the script is passed the string name=button text.


No PHP script required.

1.4. An array of buttons (submit) for selecting an action option
2. Reset button

When you press the reset button ( reset), all form elements will be set to the state that was specified in the default attributes, and the form will not be submitted.


No PHP script required.

3. Checkbox

Checkboxes present the user with a number of options, and allow arbitrary selection (none, one, or more of them).

White
Green
Blue
Red
Black
$go) ( echo $index." - > ".$go."
"; }; };

4. Switch(radio)

Radio switches offer the user a number of options, but only allow one to be selected.
Example 1.

White
Green
Blue
Red
Black

Example 2.
// first set of buttons
// second set of buttons
// third set of buttons
\n"; ?>

5. Text field (text)

When creating a regular text field with size size and maximum allowed length maxlength characters, the type attribute takes the value text. If the parameter is specified value, then the field will display the value specified in the variable. When creating a field, do not forget to specify the field name, because... this attribute is required.

6. Password field

Exactly the same as a text field, except that the characters typed by the user will not be displayed on the screen.

7. Hidden text field (hidden)

Allows you to pass some service information to the script without displaying it on the page.

8. Dropdown list (select)

Tag . Tags allow you to determine the contents of the list, and the parameter value defines the value of the string. If in a tag parameter specified selected, then the row will be initially selected. The size parameter specifies how many lines the list will occupy. If size equals 1 , then the list will be drop-down. If attribute is specified multiple, then you are allowed to select multiple elements from the list. But this scheme is practically not used, and when size = 1 doesn't make sense.

If you need to create a drop-down with a predictable sequence. For example, a list with years from 2000 to 2050. Then the following technique is used.

9. Multiline text input field (textarea)

A multi-line text input field allows you to send not just one line, but several at once. If necessary, you can specify the attribute readonly, which prohibits editing, deleting and changing text, i.e. the text will be read-only. If it is necessary for the text to be initially displayed in a multi-line input field, then it must be placed between the tags .
There is a parameter wrap– task of line breaks. Possible values:
off– disables line wrapping;
virtuals– shows line breaks, but sends the text as it was entered;
physical– line breaks are left in their original form.
Default tag

In order for a multi-line text field to comply with html formatting (line wrapping using the tag
or
), then use the function nl2br():

10. Button for uploading files (browse)

Serves to implement uploading files to the server. When creating a text field, you must also specify the field type type How "file".

Upload file:

Ways the browser communicates with the server

Methods provided by the protocol HTTP, A little. This is important information. There are no other ways. In practice, two are used:
GET- This is when data is transferred in the address bar, for example, when the user clicks a link.
POST– when he presses a button on the form.

GET method

To pass data using the method GET no need to create a form on the HTML page (use forms for requests using the GET no one is stopping you) - just a link to the document with the addition of a query string, which can look like variable=value. Pairs are concatenated using the ampersand &, and the string is appended to the page URL using a question mark " ? ».
But you don’t have to use key=value pairs if you need to pass just one variable - to do this, you need to write the VALUE (not the name) of the variable after the question mark.
Advantage passing parameters this way is that clients who cannot use the method POST(for example, search engines) will still be able, simply by following the link, to pass parameters to the script and receive the content.
Flaw is that simply by changing the parameters in the address bar, the user can turn the script around in an unpredictable way and this creates a huge security hole, combined with undefined variables and register_globals on or someone can find out the value of an important variable (for example ID-sessions), just by looking at the monitor screen.
:
- to access public pages with passing parameters (increased functionality)
- transfer of information that does not affect the level of security
:
- to access protected pages with parameter transfer
- to transmit information affecting the level of security
- to transmit information that cannot be modified by the user (some transmit the text of SQL queries.

POST method

Pass data using method POST This is only possible using a form on an HTML page. Main difference POST from GET the fact that the data is not transmitted in the request header but in the body, therefore, the user does not see it. You can only modify it by changing the form itself.
Advantage:
- greater security and functionality of requests using forms using the POST method.
Flaw:
- less availability.
What should you use it for?:
- for transmitting a large amount of information (text, files..);
- to transmit any important information;
- to restrict access (for example, use only the form for navigation - an option that is not available to all robot programs or content grabbers).
What it should not be used for:

PHP is capable of accepting a file downloaded using any browser. This makes it possible to upload both text and binary files. Combined with PHP authentication and file system functions, you have complete control over who is allowed to upload files and what to do with the file once it has been uploaded.
The file upload page can be implemented using a special form that looks something like this:

//Form for uploading files

Send this file:

In the above example "URL" must be replaced with a link to a PHP script. Hidden field MAX_FILE_SIZE(value must be specified in bytes) must precede the file selection field, and its value is the maximum allowed file size to be accepted. You should also make sure that in the form attributes you specify enctype="multipart/form-data", otherwise files will not be uploaded to the server.
Attention
Option MAX_FILE_SIZE is a browser recommendation, even if PHP would also check for this condition. Bypassing this limitation on the browser side is fairly easy, so you should not rely on this feature to block all larger files. However, there is no way to bypass PHP's maximum size limitation. You should add the form variable anyway MAX_FILE_SIZE, as it prevents users from waiting anxiously while transferring huge files, only to find out that the file is too large and the transfer actually failed.

How to define a request method?

Directly:

Getenv("REQUEST_METHOD");

will return GET or POST.

Which method should be used?

If the form is used to request some information, for example, during a search, then it should be sent using the method GET. To keep the page updated, you can bookmark it and/or send the link to a friend.
If, as a result of submitting a form, data is written or changed on the server, then it should be sent using the method POST, and it is imperative, after processing the form, to redirect the browser using the method GET. Also, POST may be necessary if a large amount of data needs to be transferred to the server (for GET it is very limited), as well as if the transmitted data should not be “shown” in the address bar (when entering a login and password, for example).
In any case, after processing POST You should always redirect the browser to some page, even the same one, but without the form data, so that when the page is refreshed, they are not recorded again.

How to transfer data to another file directly from the body of a PHP program using the GET and POST methods?

An example to demonstrate sending data using the POST and GET methods simultaneously and receiving a response from the server.

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 are either 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 features more 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 twowill 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 to 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 honestly a breath 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 with 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.

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 mine 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:

register.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-radius: 10px 10px 0px 0px; form, .content (width: 30%; margin: 0px auto; padding: 20px ; border: 1px solid #B0C4DE; border-radius: 0px 0px 10px 10px; .input-group ( margin: 10px 0px 10px 0px; ) ; 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; background: #5F9EA0; border: border-radius: 5px; width: 92%; margin: 0px auto; border: 1px solid # a94442; color: #a94442; border-radius: 5px; text-align: left;

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. users 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 out the form. Passwords are also compared to make sure they match.

0) : ?>

If no errors were encountered, the user is registered in the

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.

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) ," " ")"; 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 backUserFullName(); ?>!

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.

What is Form?

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

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

The diagram below illustrates the form handling process.

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

The form is defined using the

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

In this tutorial, you will learn-

When and why we are using forms?

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

Create a form

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

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

The code below creates a simple registration form

Registration Form

Registration Form

First name:
Last name:

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


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

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

Submitting the form data to the server

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

PHP POST method

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

It has the following syntax.

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

PHP GET method

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

It has the following syntax.

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

GET vs POST Methods

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

The below diagram shows the difference between get and post



Processing the registration form data

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

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

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

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

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

Thank You

You have been registered as

Go back to the form

Registration Form

First name:
Last name:

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

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

More examples

Simple search engine

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

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

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

Simple Search Engine

Search Results For

The GET method displays its values ​​in the URL

Sorry, no matches found for your search term

Go back to the form

Simple Search Engine - Type in GET

Search Term:

View the above page in a web browser

The following form will be shown

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

The following will be shown

The diagram below shows the URL for the above results

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

Working with check boxes, radio buttons

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

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

Registration Form

You have not accepted our terms of service

Thank You

You have been registered as

Go back to the form

Registration Form

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

View the above form in a browser