Menu

Function list

This article was last updated 37 days ago, please note whether the content is still available

Z-BlogPHP encapsulates numerous helper functions. The file path is: "zb_system/function/c_system_common.php" ← This link allows direct online viewing;

There are also some in zb_system/function/c_system_function.php, but apart from the first two, they are rarely needed for direct invocation;

This chapter will introduce some relatively commonly used ones. Specific definitions can be found by searching within the files.

GetList()

Using GetList(), you can retrieve custom article lists, such as the latest articles in a specific category, pinned articles, etc.;

Note: This function is an upper-level encapsulation of $zbp->GetPostList(), mainly for internal routing calls. It is recommended to directly use $zbp->GetPostList() or encapsulate it according to your needs;

$result = GetList(array('count'=>10)) // Returns array(Post type) or an empty array()

The array parameters are as follows:

array(
  'count' => 10, // (Number of articles, optional)
  'cate' => 1, // (Category ID, optional)
  'auth' => 2, // (Author ID, optional)
  'date' => '2020-1', // (Optional)
  'tags' => 'abc', // (Tag name, optional)
  'search' => 's', // (Search term, optional)
  // The following are keys from the original $option parameter
  'post_type' => null, // Specifies the type of Post table to query (0 for article, 1 for single page, optional)
  'post_status' => null, // Specifies the status of the Post table to query (0 for public, 1 for draft, 2 for review, optional)
  'only_ontop' => false, // Specifies to only retrieve pinned posts (optional)
  'only_not_ontop' => false, // Specifies to only retrieve non-pinned posts (optional)
  'has_subcate' => false, // Specifies to include subcategories (optional)
  'is_related' => 'article id', // Specifies to query related articles (optional)
  'order_by_metas' => false, // Specifies to sort results by Metas values (optional)
  'random' => 5, // Specifies to retrieve 5 records from the Post table (optional)
  'where_custom' => array(array('>', 'log_PostTime', '1657884349')), // Custom WHERE clause
  'order_custom' => array('log_ViewNums' => 'DESC', 'log_CommNums' => 'ASC'), // Custom ORDER BY clause
)

GetPost()

Using GetPost(), you can retrieve specific articles, pages, or other types of data from the Post table;

// Returns a Post object instance with ID 10, or an empty Post object instance if not found
$post = GetPost(array('id'=>10)) // Returns object(Post type)

The array parameters are as follows:

array(
  'id' => 10, // Specifies the ID (optional)
  'title' => 'abc', // Specifies the Post title (optional)
  'alias' => 'cba', // Specifies the Post alias (optional)
  'titleoralias' => 'ddd', // Specifies the Post title or alias (optional)
  'idorname' => 'fff', // Specifies the Post ID or title or alias (optional)
  // The following are keys from the original $option parameter
  'post_type' => null, // Specifies the type of Post table to query (optional)
  'post_status' => null, // Specifies the status of the Post table to query (optional)
  'only_article' => false, // Specifies to only find articles (optional)
  'only_page' => false, // Specifies to only find pages (optional)
  'where_custom' => array(array('=', 'log_Template', '')), // Custom WHERE clause
  'order_custom' => array('log_CommNums' => 'ASC'), // Custom ORDER BY clause
)

GetVars()

  • Can quickly retrieve values passed via GET/POST/COOKIE, etc.;

  • If it does not exist, it will return null by default, so there is no need for an `isset($_GET['act'])` check;

  • The default return value can be determined by the third optional parameter;

  • Actually, the second parameter is case-insensitive, but for some reason, it's still customary to use uppercase;

$act = GetVars("act", "GET");
$name = GetVars("name", "POST");
$password = GetVars("password", "COOKIE", "12345678");

GetValueInArray()

  • Retrieves an element from an array based on a specified key value; (can omit isset check)

  • It internally encapsulates the check for the existence of the required key value and returns the third parameter if it doesn't exist;

  • The third parameter can be omitted; its default value is null;

  $siteInfos = array(
    "url" => "https://docs.zblogcn.com/php/",
    "git" => "https://github.com/zblogcn/docs-zblogphp",
    "engine" => "docsify",
  );
  $siteUrl = GetValueInArray($siteInfos, "url", "");
  // Or
  $siteUrl = GetValueInArray($siteInfos, 'url');
  echo $siteUrl;
  // https://docs.zblogcn.com/php/

GetImagesFromHtml()

Retrieves all images from HTML;

Parameters and return values;

// @param string $html
// @return array

Referrer Information

// IP
GetGuestIP();
// HTTP_USER_AGENT
GetGuestAgent();
// Referrer URL
GetRequestUri();

Get Environment Information

Some of this information is assigned to constants during initialization and can be used directly. See "zb_system\function\c_system_base.php"

// System information overview
var_dump(GetEnvironment());
// string(73) "WINNT10.0; IIS10.0; PHP7.4.21x64; mysqli5.7.23; curl7.70.0; OpenSSL1.1.1k"

// Other related functions below

// Request protocol
GetScheme($_SERVER)

// Web server - Nginx / Apache / IIS
GetWebServer()

// Operating system
GetSystem()

// PHP version
GetPHPVersion()

common.php Function Overview

HTTP Server and System Detection Functions

Get Scheme

GetScheme($array)

Get Server

GetWebServer()

Get Operating System

GetSystem()

Get PHP Parsing Engine

GetPHPEngine()

PHP Version

GetPHPVersion()

Get Current Website Address

GetCurrentHost($blogpath, &$cookiesPath)

Set HTTP Status Header

SetHttpStatusCode($number, $force = false)

Redirect using script tag

RedirectByScript($url)

302 Redirect

Redirect302($url)

HTTP 302 Redirect

Redirect($url)

301 Redirect

Redirect301($url)

Output Http404

Http404()

Output Http500

Http500()

Output Http503

Http503()

Set 304 Cache Header

Http304($filename, $time)

Get Client IP

GetGuestIP()

Get Client Agent

GetGuestAgent()

Get Request Referrer URL

GetRequestUri()

Get Request Script Name

GetRequestScript()

Get Time Zone Name by GMT

GetTimeZoneByGMT($z)

Get System Information

GetEnvironment($more = false)

Get Backend CSP Header

GetBackendCSPHeader()

Check Mobile Device

zbp_is_mobile()

Check Mobile Device

CheckIsMobile()

Get Remote Page Content via URL

GetHttpContent($url)

File and Directory Handling Functions

Autoload Class Files

AutoloadClass($className)

Manage Autoload Class File Directories

AddAutoloadClassDir($dir, $prepend = false)

Get Application URL from File

plugin_dir_url($file)

Get Application Directory Path from File

plugin_dir_path($file)

Get List of Folders in a Directory (Recursive)

GetDirsInDir_Recursive($dir)

Get List of Files of a Specific Type in a Directory (Recursive)

GetFilesInDir_Recursive($dir, $type)

Get List of Folders in the Current Directory

GetDirsInDir($dir)

Get List of Files of a Specific Type in the Current Directory

GetFilesInDir($dir, $type)

Get File Extension

GetFileExt($f)

Get File Permissions (Octal)

GetFilePermsOct($f)

Get File Permissions (Character Representation)

GetFilePerms($f)

Remove BOM Header from File

RemoveBOM($s)

Check for Duplicate Inclusions

CheckIncludedFiles($file)

Array Handling Functions

Get Parameter Values from $_GET, $_POST, etc. arrays

GetVars($name, $type = 'REQUEST', $default = null)

Get Parameter Values from a Series of Specified Environment Variables

GetVarsFromEnv($name, $source = '', $default = '')

Parse env: Set Project to Read Environment Variables to Get Parameter Values

GetOptionVarsFromEnv($value)

Get ID Array from List

GetIDArrayByList($array, $keyname = null)

Check if an array already has $key, if not, set $default once

Array_Isset(&$array, $key, $default)

Convert Array to Object

array_to_object($arr)

Convert Object to Array

object_to_array($obj)

String Handling Functions

Split a string and get a specific item

SplitAndGet($string, $delimiter, $n = 0)

Remove consecutive spaces

RemoveMoreSpaces($s)

Add a new parameter to a string-type parameter list

AddNameInString($s, $name)

Remove a parameter from a string-type parameter list

DelNameInString($s, $name)

Find a parameter within a string parameter value

HasNameInString($s, $name)

Validate if a string matches a regular expression

CheckRegExp($source, $para)

Get substring of a UTF8 encoded string

SubStrUTF8_Start($sourcestr, $start)

Get substring of a UTF8 encoded string

SubStrUTF8($sourcestr, $cutlength)

ZBP Version of Get Substring of a UTF8 Encoded String

Zbp_SubStr($sourcestr, $start)

ZBP Version of StrLen

Zbp_StrLen($string)

ZBP Version of Strpos

Zbp_Strpos($haystack, $needle, $offset = 0)

ZBP Version of Stripos

Zbp_Stripos($haystack, $needle, $offset = 0)

Substring of a UTF8 encoded string with HTML format

SubStrUTF8_Html($source, $length)

Get a string containing only numbers, letters, and hyphens

FilterCorrectName($s)

Check if an object can be converted to a string

CheckCanBeString($obj)

Implement utf84mb4 filtering

utf84mb_filter(&$sql)

Clear all PHP code within a string of code

RemovePHPCode($code)

JSON encoding friendly to Chinese and special characters

JsonEncode($arr)

Convert UCS-2BE to UTF-8, solving JSON Chinese character encoding issues

Ucs2Utf8($matchs)

HTML Text Processing and Conversion Functions

Format String

FormatString($source, $para)

Same as above

TransferHTML($source, $para)

Encapsulate HTML Tags

CloseTags($html)

Apply htmlspecialchars to strings within an array

htmlspecialchars_array($array)

Recursively escape HTML entities

RecHtmlSpecialChars(&$arr)

Get all images from HTML

GetImagesFromHtml($html)

URL Judgment and Processing Functions

Construct Secure URL with Token

BuildSafeURL($url, $appId = '')

Construct Access Link for cmd.php

BuildSafeCmdURL($paramters)

Replace https:// and http:// at the beginning of a URL with //

RemoveProtocolFromUrl($url)

Check if URL is local

CheckUrlIsLocal($url)

Convert URL Host to Local Path

UrlHostToPath($url)

rawurlencode escapes but does not escape /

rawurlencode_without_backslash($s)

SWoole and Workerman Related Functions

Convert $request array from swoole and workerman to $GLOBALS global array

http_request_convert_to_global($request)

Get raw post data in swoole, workerman, or standard php environments

get_http_raw_post_data(&$request = null)

Error Output and Logging Functions

Output error information in JSON format (for ShowError interface)

JsonError4ShowErrorHook($errorCode, $errorString, $file, $line)

Output error information in JSON format. (If err code is (int)0, it's considered no error, so 0 is converted to 1)

JsonError($errorCode, $errorString, $data)

When code runs normally, output information in JSON format

JsonReturn($data)

XML-RPC Response Error Page

RespondError($errorCode, $errorString = '', $file = '', $line = '')

Script Error Page

ScriptError($errorCode, $errorText = '', $file = '', $line = '')

Log a message

Logs($logString, $level = 'INFO', $source = 'system')

Logs the value of a specified variable

Logs_Dump()

Other System Functions

Initialize Statistics Information

RunTime_Begin()

Output page runtime duration

RunTime($isOutput = true)

Get Guid

GetGuid()

Get a random sqlite database name

GetDbName()

Security Detection and Judgment Functions

Simple String Obfuscation Function

zbp_string_auth_code($data, $operation, $password, $additional = null)

Verify if Web Token is Valid

VerifyWebToken($webTokenString, $webTokenId, $key = '')

Create Web Token

CreateWebToken($webTokenId, $time, $key = '')

Check if the source is valid. This includes CSRF detection. When enhanced security mode is enabled, source detection is added.

CheckIsRefererValid()

Verify if CSRF Token is Valid

CheckCSRFTokenValid($fieldName = 'csrfToken', $methods = array('get', 'post'))

Check if HTTP Referer is Valid

CheckHTTPRefererValid()

zbp Throttling Function (depends on zbp_cache plugin)

zbp_throttle($name = 'default', $max_reqs = 60, $period = 60)

Encryption and Decryption Functions

Since 1.7.3, the system has integrated the ZbpEncrypt encryption class

AES Symmetric Encryption Functions

// Encryption function
ZbpEncrypt::encrypt($data, $password, $additional = null, $type = null)
# $data original string
# $password password
# $additional additional authentication data (can be set to null)
# $type can specify the type as aes256gcm, aes256cbc, sm4

// Decryption function
ZbpEncrypt::decrypt($data, $password, $additional = null, $type = null)
# $data string to be decrypted

# Note:
# aes256gcm requires openssl or sodium extension (PHP >= 7.1.0)
# aes256cbc requires mcrypt or openssl extension
# sm4 requires openssl extension (PHP >= 7.2.0)

# Recommended to use aes256gcm
# If $type is not specified, it will be automatically determined, trying aes256gcm > aes256cbc in order
// aes256gcm encryption/decryption function usage example
$endata = ZbpEncrypt::encrypt('original string', '12345', 'add', 'aes256gcm');

$dedata = ZbpEncrypt::decrypt($endata, '12345', 'add', 'aes256gcm');

var_dump($dedata); // string(15) "original string"

// Or
$endata = ZbpEncrypt::aes256gcm_encrypt('original string', '12345');

$dedata = ZbpEncrypt::aes256gcm_decrypt($endata, '12345');

// aes256 encryption/decryption function (supports cbc, cfb, ctr, ecb, ofb modes)
$endata = ZbpEncrypt::aes256_encrypt('original string', '12345', '', 'ofb');

$dedata = ZbpEncrypt::aes256_decrypt($endata, '12345', '', 'ofb');

// sm4 encryption/decryption function usage example (supports cbc, cfb, ctr, ecb, ofb modes)
$endata = ZbpEncrypt::sm4_encrypt('original string', '12345', '', 'cbc');

$dedata = ZbpEncrypt::sm4_decrypt($endata, '12345', '', 'cbc');

// For interfacing with other systems, the original aes256gcm encryption/decryption
ZbpEncrypt::original_aes256gcm_encrypt($data, $password, $additional, $nonce)
ZbpEncrypt::original_aes256gcm_decrypt($data, $password, $additional, $nonce)
// Requires three parameters: $password, $additional, $nonce
# $password must be 32 bytes long, $nonce must be 12 bytes long

RSA Asymmetric Encryption Functions

// RSA asymmetric public key encryption function
ZbpEncrypt::rsa_public_encrypt($data, $public_key_pem, $key_length = 2048)
# $data original string
# $public_key_pem public key pem string
# $key_length key length, default 2048

// RSA asymmetric public key decryption function
ZbpEncrypt::rsa_public_decrypt($data, $public_key_pem, $key_length = 2048)
# $data string to be decrypted

// RSA asymmetric private key encryption function
ZbpEncrypt::rsa_private_encrypt($data, $private_key_pem, $key_length = 2048)
# $private_key_pem private key pem string

// RSA asymmetric private key decryption function
ZbpEncrypt::rsa_private_decrypt($data, $private_key_pem, $key_length = 2048)
// RSA function usage example
$rsa_config = array(
    'digest_alg' => 'sha512',
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
// Create public and private keys
$res = openssl_pkey_new($rsa_config);
// Get private key
openssl_pkey_export($res, $private_key);
// Get public key
$public_key = openssl_pkey_get_details($res)['key'];

// Encrypt with private key
$endata = ZbpEncrypt::rsa_private_encrypt('original string', $private_key);
// Decrypt with public key
$dedata = ZbpEncrypt::rsa_public_decrypt($endata, $public_key);
var_dump($dedata); // string(15) "original string"

// Encrypt with public key
$endata = ZbpEncrypt::rsa_public_encrypt('original string', $public_key);
// Decrypt with private key
$dedata = ZbpEncrypt::rsa_private_decrypt($endata, $private_key);
var_dump($dedata); // string(15) "original string"


Helpful?

Post comment

Support Live Chat
TOP