etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

How to encrypt password in PHP

In this article, you will learn different ways to encrypt password using PHP. Generally, data is most vulnerable when it is being moved from one location to another. Encryption is the process through which information is encoded so it stays hidden from the unauthorized users. It ensures private data, sensitive data, and can improve the security of communication between client apps and servers. Today, almost every applications need password encryption technique to protect sensitive information of its users.

PHP has hash algorithm to encrypt the password. The mostly used functions for password encrypting are md5(), crypt() and password_hash().

How to encrypt password in PHP

Suppose, we have the registration form data containing username and password in the POST. If we insert the same password as received in the POST in the database, this is not the secure way. If the database falls into the wrong hands, then they can misuse the data.



Encrypting password using md5()

These are one way encryption algorithm. The password encrypted with this algorithm can never be decrypted. The md5 is most commonly used encryption method. The md5() function is used to calculate the md5 hash of a string. The syntax of the md5 function is -

md5(string,raw)

Here, string is the string to be encrypted and row is optional parameter. It specifies the output format which can either be TRUE or FALSE. The default is FALSE.

The given code encrypts the password value and store in the database.


 <?php
 $conn = new mysqli('hostname', 'username', 'password', 'databasename');
 $pwd = $_POST['password'];
 $encrypted_pwd = md5($pwd);
 $username = $_POST['username']; 
 $insert ="INSERT into an_users (id, username, password) 
 VALUES  ('', '$username', '$encrypted_pwd')";
 if($conn->query($insert)){
  echo 'Data inserted successfully';
 }
 else{
  echo 'Error '.$conn->error;  
 }
?>




Encrypting password using crypt()

The crypt() function returns a hashed string using salt. This method generates weak password without salt. It takes a second parameter for the salt which is an optional parameter. The salt is a formatted string that tells the crypt() method which algorithm is use to do the hashing

Syntax -
crypt($string, $salt);

There are many salt constants, but here we have used CRYPT_MD5. This generates 12 characters salt.

<?php
  $conn = new mysqli('hostname', 'username', 'password', 'databasename');
  $pwd = $_POST['password'];
  if(CRYPT_MD5 == 1) {
      $encrypted_pwd = crypt($pwd, '$12$hrd$reer');
  }
  $username = $_POST['username'];
  $insert = "INSERT INTO  an_users (id, username, password) 
		  VALUES('', '$username', '$encrypted_pwd')";
  if($conn->query($insert)){
	echo 'Data inserted successfully';
  }
  else{
	echo 'Error '.$conn->error;  
  }
?>


Encrypting password using password_hash()

The password_hash() creates a new password hash using a strong one-way hashing algorithm. The password_hash() function is compatible with crypt() function. It is implemented in PHP 5.1. The syntax of password_hash() is -

password_hash(string, algorithm, options)

Here, string is the string to be encrypted, algorithm denotes the algorithm to use when hashing the password and options is an associative array containing options.


The given code encrypts the password value using password_hash() and stores in the database.

<?php
// Database connection
 $conn = new mysqli('hostname', 'username', 'password', 'databasename');

 $pwd = $_POST['password'];

// hash it with PASSWORD_DEFAULT
$hash = password_hash($pwd,  
          PASSWORD_DEFAULT); 
$username = $_POST['username']; 

$insert ="INSERT into an_users (id, username, password) 
 VALUES  ('', '$username', '$hash')";

if($conn->query($insert)){
  echo 'Data inserted successfully';
}
 else{
  echo 'Error '.$conn->error;  
}
?>




Related Articles

JavaScript display PDF in the browser using Ajax call
How to display PDF file in PHP from database
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
CRUD operations in Python using MYSQL Connector
Windows commands to Create and Run first Django app
How to send emojis in email subject and body using PHP
PHP7.3 New Features, Functions and Deprecated Functions
Create pie chart using google api




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
Characteristics of a Good Computer Program
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
PHP Create Word Document from HTML
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
How to encrypt password in PHP
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
How to add multiple custom markers on google map
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Simple PHP File Cache
-----------------
How to generate QR Code in PHP
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Server Side Form Validation
-----------------
Detect Mobile Devices in PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Set and Get Cookies in PHP
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
How to print specific part of a web page in javascript
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview





General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.