Home Backend Development PHP Tutorial Analysis of some common operation code in PHP

Analysis of some common operation code in PHP

Jun 10, 2020 am 09:23 AM

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;
  }
Copy after login

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; 
}
Copy after login

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=&#39;info@domain.com&#39;, $linkText=&#39;Contact Us&#39;,$attrs =&#39;class="emailencoder"&#39; ) { 
    // remplazar aroba y puntos $email = 
str_replace(&#39;@&#39;, &#39;@&#39;, $email); 
    $email = str_replace(&#39;.&#39;, &#39;.&#39;, $email); 
    $email = 
str_split($email, 5); 
    $linkText = str_replace(&#39;@&#39;, &#39;@&#39;, $linkText); 
    $linkText = 
str_replace(&#39;.&#39;, &#39;.&#39;, $linkText); 
    $linkText = str_split($linkText, 5); 
    $part1 = &#39;part2 = &#39;ilto:&#39;; 
    $part3 = &#39;" &#39;. $attrs .&#39; >&#39;; 
    $part4 = &#39;&#39;; $encoded = &#39;&#39;; 
$encoded .= "document.write(&#39;$part1&#39;);"; 
    $encoded .= "document.write(&#39;$part2&#39;);"; 
    foreach($email as $e) { 
        $encoded .= "document.write(&#39;$e&#39;);"; 
    } 
    $encoded .= "document.write(&#39;$part3&#39;);"; 
foreach($linkText as $l) { 
        $encoded .= "document.write(&#39;$l&#39;);"; 
    } 
    $encoded .= "document.write(&#39;$part4&#39;);"; 
    $encoded .= &#39;&#39;; 
    return $encoded;
}
Copy after login

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; 
}
Copy after login

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 &#39;&#39;.$file.&#39;a>  &#39;."\n"; 
                 } 
            } closedir($handle); 
        } 
   } 
}
Copy after login

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 == &#39;.&#39; || $file == &#39;..&#39;) { 
                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; 
    } 
}
Copy after login

8. PHP parses XML data

$json_string=&#39;{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} &#39;; 
$obj=json_decode($json_string); 
echo $obj->name; //prints foo echo 
$obj->interest[1]; //prints php
Copy after login

9. PHP creates log abbreviation

Create user-friendly log abbreviation.

//xml string $xml_string="xml version=&#39;1.0&#39;?> 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[&#39;id&#39;], &#39; &#39;; 
     
    //subnodes are accessed by -> operator 
    echo $user->name, &#39; &#39;; 
    echo $user->email,&#39;&#39;; 
}
Copy after login

Recommended tutorial: "

PHP Video Tutorial

"

The 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!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. 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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. 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.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? 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�...

How to automatically set permissions of unixsocket after system restart? 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...

See all articles