Analysis of some common operation code in PHP

Some common operation code examples in PHP 1
1. PHP can read random strings
This code will create a human-readable string that is closer to the word in the dictionary, practical, and has password verification capabilities.
2. PHP generates a random string
If you do not need a readable string, use this function instead to create a random string as the user's random password, etc.
/**@length - length of random string (must be a multiple of 2)**/
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1;$i<=$max; $i++){
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}3. PHP Encoded Email Address
Using this code, any email address can be encoded as an html character entity to prevent it from being collected by spam programs.
/************* *@l - length of random string */
function generate_rand($l){
$c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
for($i=0; $i<$l; $i++) {
$rand.=
$c[rand()%strlen($c)];
}
return $rand;
}4. PHP verification email address
Email verification is perhaps the most commonly used web form verification. In addition to verifying the email address, this code can also choose to check the DNS of the email domain. MX records make email verification more powerful.
function encode_email($email='info@domain.com', $linkText='Contact Us',$attrs ='class="emailencoder"' ) {
// remplazar aroba y puntos $email =
str_replace('@', '@', $email);
$email = str_replace('.', '.', $email);
$email =
str_split($email, 5);
$linkText = str_replace('@', '@', $linkText);
$linkText =
str_replace('.', '.', $linkText);
$linkText = str_split($linkText, 5);
$part1 = 'part2 = 'ilto:';
$part3 = '" '. $attrs .' >';
$part4 = ''; $encoded = '';
$encoded .= "document.write('$part1');";
$encoded .= "document.write('$part2');";
foreach($email as $e) {
$encoded .= "document.write('$e');";
}
$encoded .= "document.write('$part3');";
foreach($linkText as $l) {
$encoded .= "document.write('$l');";
}
$encoded .= "document.write('$part4');";
$encoded .= '';
return $encoded;
}5. PHP lists directory contents
function is_valid_email($email, $test_mx = false) {
if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
if($test_mx) {
list($username, $domain) = split("@", $email);
return getmxrr($domain, $mxrecords);
} else {
return true;
}
} else {
return false;
}6. PHP destroys directory
Deletes a directory, including its contents.
function list_files($dir){
if(is_dir($dir)) {
if($handle = opendir($dir)) {
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != ".." && $file != "Thumbs.db") {
echo ''.$file.'a> '."\n";
}
} closedir($handle);
}
}
}7. PHP parses JSON data
Like most popular web services such as twitter that provide data through open APIs, it always knows how to parse the various transmission formats of API data. , including JSON, XML, etc.
/***** *@dir - Directory to destroy *@virtual[optional]- whether a virtual directory */
function destroyDir($dir, $virtual = false) {
$ds = DIRECTORY_SEPARATOR;
$dir = $virtual ? realpath($dir) : $dir;
$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
if (is_dir($dir) && $handle = opendir($dir)) {
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..') {
continue;
} elseif (is_dir($dir.$ds.$file)) {
destroyDir($dir.$ds.$file);
} else {
unlink($dir.$ds.$file);
}
}
closedir($handle);
rmdir($dir);
return true;
} else {
return false;
}
}8. PHP parses XML data
$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo echo
$obj->interest[1]; //prints php9. PHP creates log abbreviation
Create user-friendly log abbreviation.
//xml string $xml_string="xml version='1.0'?> Fooname> foo@bar.comname> user> Foobarname> foobar@foo.comname> user>users>";
//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);
//loop through the each node of user
foreach ($xml->user as $user) {
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email,'';
}Recommended tutorial: "
PHP Video TutorialThe above is the detailed content of Analysis of some common operation code in PHP. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1384
52
Alipay PHP SDK transfer error: How to solve the problem of 'Cannot declare class SignData'?
Apr 01, 2025 am 07:21 AM
Alipay PHP...
Explain JSON Web Tokens (JWT) and their use case in PHP APIs.
Apr 05, 2025 am 12:04 AM
JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,
Describe the SOLID principles and how they apply to PHP development.
Apr 03, 2025 am 12:04 AM
The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.
How to automatically set permissions of unixsocket after system restart?
Mar 31, 2025 pm 11:54 PM
How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
Explain the concept of late static binding in PHP.
Mar 21, 2025 pm 01:33 PM
Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo
How to send a POST request containing JSON data using PHP's cURL library?
Apr 01, 2025 pm 03:12 PM
Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
Framework Security Features: Protecting against vulnerabilities.
Mar 28, 2025 pm 05:11 PM
Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.
Customizing/Extending Frameworks: How to add custom functionality.
Mar 28, 2025 pm 05:12 PM
The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.


