search
HomeBackend DevelopmentPHP Tutorialphp calculate MD5 hash of string

php calculate MD5 hash of string

Nov 02, 2017 pm 01:22 PM
phpstringcalculate

Example

Calculate the MD5 hash of the string "Hello":

<?php
$str = "Hello";
echo md5($str);
?>

Definition and usage

md5() function calculates the MD5 hash of the string.

The md5() function uses RSA data security, including the MD5 message digest algorithm.

Explanation from RFC 1321 - MD5 message digest algorithm: The MD5 message digest algorithm takes information of any length as an input value and converts it into a 128-bit length "fingerprint information" or "message" Summary" value to represent this input value, and the converted value as the result. The MD5 algorithm is primarily designed for digital signature applications where larger files are encrypted using a public key in a cryptographic system such as RSA. (done by setting a private key) before compressing in a secure manner.

To calculate the MD5 hash of a file, use the md5_file() function.

Syntax

md5(string,raw)

Parameters Description

##string Required. Specifies the string to be calculated. ​

raw ​ ​ Optional. Specifies hexadecimal or binary output format:

              TRUE - raw 16-character binary format

                                                                                                                use   use using using using ’         use using ’ s ’ s ’ s ‐   ‐ ‐ ‐ to be output in hexadecimal format. 32 characters Sixteen -in -made numbers

Technical Details

This Return Value: If successful, return the calculated MD5 scale, if it fails, it will Return FALSE.

PHP Version: 4+

##Change Log: In PHP 5.0, raw Parameters become optional.

More examples

Example 1

Output the result of md5():

<?php 
$str = "Hello"; 
echo "The string: ".$str."<br>"; 
echo "TRUE - Raw 16 character binary format: ".md5($str, TRUE)."<br>"; 
echo "FALSE - 32 character hex number: ".md5($str)."<br>"; 
?>

Example 2

Output the result of md5() and test it:

<?php
$str = "Hello";
echo md5($str);

if (md5($str) == "8b1a9953c4611296a827abf8c47804d7")
{
echo "<br>Hello world!";
exit;
}
?>

 一般来说,一个提供会员注册的网站必定需要采集用户的密码,如何保存用户密码就是个问题。我们当然不能将密码以明文的方式储存在数据库中,因为这样的话,一般的管理员就可以查看到用户密码,显然对用户来说是件相当危险的事情。 

    那如何解决这个问题呢,我们可以采取这样的策略。 

    首先介绍一下PHP中MD5函数的使用方法: 

<?php  
$pswd1=md5("cenusdesign");  
echo $pswd1;     //运行结果为:fc60ec37d1c08d5b0fb67a8cd934d5ba  

$pswd2=md5("Cenusdesign");  
echo $pswd2;     //运行结果为:067577d9fc109c80538c81d6f02bd293  
?>


    显然,经过md5加密后,原本“cenusdesign”转变成了一组32位的字符串,而且,即使是一个字母的大小写变化,这组字符串就会发生巨大的变化。 

    Cenus Design建议把用户注册时,将密码首先经过MD5转换,然后将转换加密后的数据库。在用户登陆时,也将密码先进行MD5转化,再和数据库中那组经过MD5加密的字符串进行比较。这样,就可以做到在不知道用户确切密码的情况下完成密码的比对操作。 

The above is the detailed content of php calculate MD5 hash of string. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor