← Back to Chapters

PHP MD5 & SHA1 Functions

? PHP MD5 & SHA1 Functions

? Quick Overview

PHP provides hashing functions like md5() and sha1() to create fixed-length hash values from strings. These hashes are commonly used for data integrity checks, identifiers, and legacy systems.

? Key Concepts

  • md5() generates a 32-character hexadecimal hash
  • sha1() generates a 40-character hexadecimal hash
  • Hashes are one-way and cannot be reversed
  • Not suitable for secure password storage

? Syntax / Theory

  • string md5(string $data)
  • string sha1(string $data)
  • hash(string $algo, string $data)

? Example 1: Using md5()

? View Code Example
// Generate an MD5 hash from a password
<?php
$password = "mySecret123";
$hash = md5($password);
echo $hash;
?>

Explanation: The md5() function converts the string into a 32-character hexadecimal hash. MD5 is fast but insecure for password storage.

? Example 2: Using sha1()

? View Code Example
// Generate a SHA1 hash from a password
<?php
$password = "mySecret123";
$hash = sha1($password);
echo $hash;
?>

Explanation: sha1() produces a longer hash than MD5 but is still considered outdated for secure applications.

? Example 3: Using SHA-256

? View Code Example
// Generate a stronger SHA-256 hash
<?php
$password = "mySecret123";
$hash = hash("sha256", $password);
echo $hash;
?>

? Interactive Concept

Try hashing the same password using MD5, SHA1, and SHA-256. Notice how the length and complexity increase, improving resistance to brute-force attacks.

? Use Cases

  • File integrity checks
  • Legacy system compatibility
  • Checksum generation
  • Unique identifiers (non-sensitive)

✅ Tips & Best Practices

  • Avoid MD5 and SHA1 for passwords
  • Use password_hash() and password_verify()
  • Prefer SHA-256 or bcrypt for security

? Try It Yourself

  • Hash the same input with MD5, SHA1, and SHA-256
  • Compare hash lengths and formats
  • Experiment with password_hash()