search
HomeBackend DevelopmentPHP ProblemRecommend 9 commonly used php codes (remember to collect them)

收集一些日常开发中一些有用的PHP代码段,会持续更新。今天就向大家介绍一下,有需要的小伙伴可以参考参考。

Recommend 9 commonly used php codes (remember to collect them)

收集一些日常开发中一些有用的PHP代码段,会持续更新。
如果代码有BUG或者任何建议,欢迎在评论区评论!

1、把一个数字限定在某个范围内,比如要限定$a在区间[1, 12]内,当$a=17时,就令$a=12:

min(max($a, 1), 12);

2、检查一个日期是不是有效,比如非闰年时给了个2月29日:

$date = '2016-2-29';
list($year, $month, $day) = explode('-', $date);
echo checkdate($month, $day, $year) ? 'yes' : 'no';

3、下划线风格的字符串转驼峰风格:

$a = 'long_under_line_name';
echo lcfirst(str_replace('_', '', ucwords($a, '_')));

4、驼峰风格字符串转下划线风格:

$a = 'longCamelCaseName';
echo strtolower(preg_replace('/[A-Z]/', '_$0', $a));

5、连接MySQL并查询数据:

$link = new mysqli('127.0.0.1', '用户名', '密码', '数据库名');
$link->query('SET NAMES utf8');
$rs = $link->query('SELECT * FROM table');
while ($row = $rs->fetch_assoc()) {
    // $row为查出的每一行
}
$link->close();

6、获得客户端IP

echo $_SERVER['REMOTE_ADDR'];

7、一万亿以内数字转中文串:

  $dict = ['零', '一','二','三','四','五','六','七','八','九','十','百','千','万','亿'];
  $num = 1234567890;
  $string = strrev($num);

  $text = '';
  for ($i = 0; $i !== 12; $i += 4) {
      $s = substr($string, $i, 4);
      $t = '';
      for ($j = 0; $j != 4; $j++) {
          if (!isset($s[$j])) continue;
          $u = $j && $s[$j] ? $dict[9 + $j] : '';
          $t = (($t || $s[$j]) && ($s[$j] !== '1' || $j !== 1) ? $dict[$s[$j]] : '') . $u . $t;
      }
      if ($t) {
          $text = preg_replace('/零+/u', '零', $t) . ($i ? $dict[12+$i/4]: '') . $text;
      }
  }

  echo $text . PHP_EOL;

8、字符串”true”, “false”转bool值
注意,如果直接用(bool) "false"转的话会返回true,任何非空字符串都会被转成true

$str = 'false';
$bool = filter_var($str, FILTER_VALIDATE_BOOLEAN);

9、如果获得PHP当前运行操作系统的信息

// 两种方式
echo php_uname();
// Windows 输出 Windows NT PC115080 6.1 build 7601 (Windows 7 Professional Edition Service Pack 1) AMD64
// Linux 输出 Linux VM_238_239_centos 3.10.0-514.21.1.el7.x86_64 #1 SMP Thu May 25 17:04:51 UTC 2017 x86_64

echo PHP_OS;
// Windows 输出 WINNT
// Linux 输出 Linux

推荐学习:php视频教程

The above is the detailed content of Recommend 9 commonly used php codes (remember to collect them). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools