search
HomeWeb Front-endJS Tutorial13 super practical PHP functions, which ones do you know?

This article will introduce you to 13 super practical PHP functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

13 super practical PHP functions, which ones do you know?

1. PHP encryption and decryption

PHP encryption and decryption functions can be used to encrypt some useful strings and store them in the database , and by reversibly decrypting the string, this function uses base64 and MD5 encryption and decryption.

function encryptDecrypt($key, $string, $decrypt){ 
  if($decrypt){ 
    $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); 
    return $decrypted; 
  }else{ 
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); 
    return $encrypted; 
  } 
}

The usage method is as follows:

//以下是将字符串“Helloweba欢迎您”分别加密和解密 
 //加密: 
 echo encryptDecrypt('password', 'jb51欢迎您',0); 
 //解密: 
 echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);

2. PHP generates a random string

When we need to generate a random name, temporarily The following function can be used when entering strings such as passwords:

function generateRandomString($length = 10) { 
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
  $randomString = ''; 
  for ($i = 0; $i < $length; $i++) { 
    $randomString .= $characters[rand(0, strlen($characters) - 1)]; 
  } 
  return $randomString; 
}

The usage method is as follows:

echo generateRandomString(20);

3. PHP gets the file extension (suffix)

The following function can quickly obtain the file extension or suffix.

function getExtension($filename){ 
 $myext = substr($filename, strrpos($filename, &#39;.&#39;)); 
 return str_replace(&#39;.&#39;,&#39;&#39;,$myext); 
}

The usage method is as follows:

$filename = &#39;我的文档.doc&#39;; 
echo getExtension($filename);

4. PHP gets the file size and formats

below The function used can get the size of the file and convert it into easy-to-read KB, MB and other formats.

function formatSize($size) { 
  $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); 
  if ($size == 0) { 
    return(&#39;n/a&#39;); 
  } else { 
   return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); 
  } 
}

is used as follows:

$thefile = filesize(&#39;test_file.mp3&#39;); 
echo formatSize($thefile);

5. PHP replaces tag characters

Sometimes we need to To replace strings and template tags with specified content, you can use the following function:

function stringParser($string,$replacer){ 
  $result = str_replace(array_keys($replacer), array_values($replacer),$string); 
  return $result; 
}

The usage method is as follows:

$string = &#39;The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself&#39;; 
$replace_array = array(&#39;{b}&#39; => &#39;<b>&#39;,&#39;{/b}&#39; => &#39;</b>&#39;,&#39;{br}&#39; => &#39;<br />&#39;); 
echo stringParser($string,$replace_array);

6. PHP lists the directory The file name is

If you want to list all the files in the directory, use the following code:

function listDirFiles($DirPath){ 
  if($dir = opendir($DirPath)){ 
     while(($file = readdir($dir))!== false){ 
        if(!is_dir($DirPath.$file)) 
        { 
          echo "filename: $file<br />"; 
        } 
     } 
  } 
}

The usage is as follows:

 listDirFiles(&#39;home/some_folder/&#39;);

7. PHP gets the current page URL

The following function can get the URL of the current page, whether it is http or https.

function curPageURL() { 
  $pageURL = &#39;http&#39;; 
  if (!empty($_SERVER[&#39;HTTPS&#39;])) {$pageURL .= "s";} 
  $pageURL .= "://"; 
  if ($_SERVER["SERVER_PORT"] != "80") { 
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
  } else { 
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
  } 
  return $pageURL; 
}

The usage method is as follows:

 echo curPageURL();

8. PHP force downloads files

Sometimes we don’t want to If the browser directly opens a file, such as a PDF file, but wants to download the file directly, the following function can force the file to be downloaded. The application/octet-stream header type is used in the function.

function download($filename){ 
  if ((isset($filename))&&(file_exists($filename))){ 
    header("Content-length: ".filesize($filename)); 
    header(&#39;Content-Type: application/octet-stream&#39;); 
    header(&#39;Content-Disposition: attachment; filename="&#39; . $filename . &#39;"&#39;); 
    readfile("$filename"); 
  } else { 
    echo "Looks like file does not exist!"; 
  } 
}

The usage method is as follows:

 download(&#39;/down/test_45f73e852.zip&#39;);

9. PHP intercepts the string length

We often When you encounter a situation where you need to intercept the length of a string (including Chinese characters), for example, the title cannot display more than a few characters, and the excess length is represented by..., the following function can meet your needs.

 /* 
 Utf-8、gb2312都支持的汉字截取函数 
 cut_str(字符串, 截取长度, 开始长度, 编码); 
 编码默认为 utf-8 
 开始长度默认为 0 
*/ 
function cutStr($string, $sublen, $start = 0, $code = &#39;UTF-8&#39;){ 
  if($code == &#39;UTF-8&#39;){ 
    $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/"; 
    preg_match_all($pa, $string, $t_string); 

    if(count($t_string[0]) - $start > $sublen) return join(&#39;&#39;, array_slice($t_string[0], $start, $sublen))."..."; 
    return join(&#39;&#39;, array_slice($t_string[0], $start, $sublen)); 
  }else{ 
    $start = $start*2; 
    $sublen = $sublen*2; 
    $strlen = strlen($string); 
    $tmpstr = &#39;&#39;; 

    for($i=0; $i<$strlen; $i++){ 
      if($i>=$start && $i<($start+$sublen)){ 
        if(ord(substr($string, $i, 1))>129){ 
          $tmpstr.= substr($string, $i, 2); 
        }else{ 
          $tmpstr.= substr($string, $i, 1); 
        } 
      } 
      if(ord(substr($string, $i, 1))>129) $i++; 
    } 
    if(strlen($tmpstr)<$strlen ) $tmpstr.= "..."; 
    return $tmpstr; 
  } 
}

The usage method is as follows:

$str = "jQuery插件实现的加载图片和页面效果"; 
echo cutStr($str,16);

10. PHP gets the real IP of the client

We often To record the user's IP in the database, the following code can obtain the real IP of the client:

//获取用户真实IP 
function getIp() { 
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
    $ip = getenv("HTTP_CLIENT_IP"); 
  else 
    if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
      $ip = getenv("HTTP_X_FORWARDED_FOR"); 
    else 
      if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
        $ip = getenv("REMOTE_ADDR"); 
      else 
        if (isset ($_SERVER[&#39;REMOTE_ADDR&#39;]) && $_SERVER[&#39;REMOTE_ADDR&#39;] && strcasecmp($_SERVER[&#39;REMOTE_ADDR&#39;], "unknown")) 
          $ip = $_SERVER[&#39;REMOTE_ADDR&#39;]; 
        else 
          $ip = "unknown"; 
  return ($ip); 
}

The usage is as follows:

 echo getIp();

11 , PHP prevents SQL injection

When we query the database, for security reasons, we need to filter some illegal characters to prevent malicious SQL injection. Please take a look at the function:

function injCheck($sql_str) { 
  $check = preg_match(&#39;/select|insert|update|delete|\&#39;|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/&#39;, $sql_str); 
  if ($check) { 
    echo &#39;非法字符!!&#39;; 
    exit; 
  } else { 
    return $sql_str; 
  } 
}

Use The method is as follows:

echo injCheck(&#39;1 or 1=1&#39;);

12. PHP page prompts and jumps

When we perform form operations, sometimes we need prompts for the sake of friendliness The user operates the results and jumps to the relevant page. Please see the following function:

function message($msgTitle,$message,$jumpUrl){ 
  $str = &#39;<!DOCTYPE HTML>&#39;; 
  $str .= &#39;<html>&#39;; 
  $str .= &#39;<head>&#39;; 
  $str .= &#39;<meta charset="utf-8">&#39;; 
  $str .= &#39;<title>页面提示</title>&#39;; 
  $str .= &#39;<style type="text/css">&#39;; 
  $str .= &#39;*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial, sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}&#39;; 
  $str .= &#39;</style>&#39;; 
  $str .= &#39;</head>&#39;; 
  $str .= &#39;<body>&#39;; 
  $str .= &#39;<div>&#39;; 
  $str .= &#39;<h3 id="msgTitle">&#39;.$msgTitle.&#39;</h3>&#39;; 
  $str .= &#39;<div>&#39;; 
  $str .= &#39;<h4 id="message">&#39;.$message.&#39;</h4>&#39;; 
  $str .= &#39;<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>&#39;; 
  $str .= "<script>setTimeout(&#39;location.replace(\&#39;".$jumpUrl."\&#39;)&#39;,2000)</script>"; 
  $str .= &#39;</div>&#39;; 
  $str .= &#39;</div>&#39;; 
  $str .= &#39;</body>&#39;; 
  $str .= &#39;</html>&#39;; 
  echo $str; 
}

The usage method is as follows:

message(&#39;操作提示&#39;,&#39;操作成功!&#39;,&#39;http://www.php.cn&#39;);

13. PHP calculation time

When we process time, we need to calculate the length of time from the current time to a certain point in time. For example, calculating the running time of the client is usually represented by hh:mm:ss.

function changeTimeType($seconds) { 
  if ($seconds > 3600) { 
    $hours = intval($seconds / 3600); 
    $minutes = $seconds % 3600; 
    $time = $hours . ":" . gmstrftime(&#39;%M:%S&#39;, $minutes); 
  } else { 
    $time = gmstrftime(&#39;%H:%M:%S&#39;, $seconds); 
  } 
  return $time; 
}

The usage method is as follows:

$seconds = 3712; 
echo changeTimeType($seconds);

Recommended learning: "PHP Video Tutorial"

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor