十个超级有用的PHP代码片段("10个实用PHP代码片段:提升编程效率的必备工具")
原创
一、生成随机字符串
在开发中,我们经常性需要生成随机字符串,以下是一个生成随机字符串的PHP代码片段。
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
二、检查邮箱格式是否正确
验证邮箱格式是常见的表单验证之一,以下是一个检查邮箱格式是否正确的PHP代码片段。
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
三、数组转XML
在PHP中,将数组转换成XML格式可以方便地与前端或其他服务进行数据交互。以下是一个数组转XML的代码片段。
function arrayToXml($array, $xml = null) {
if ($xml === null) {
$xml = new SimpleXMLElement('
'); }
foreach ($array as $key => $value) {
if (is_array($value)) {
if (is_numeric($key)) {
$key = 'item' . $key;
}
$subnode = $xml->addChild($key);
arrayToXml($value, $subnode);
} else {
$xml->addChild("$key", htmlspecialchars("$value"));
}
}
return $xml->asXML();
}
四、发送邮件
使用PHP发送邮件是常见的操作,以下是一个使用mail函数发送邮件的代码片段。
function sendEmail($to, $subject, $message) {
$headers = "From: your-email@example.com\r ";
$headers .= "Content-Type: text/html; charset=UTF-8\r ";
mail($to, $subject, $message, $headers);
}
五、获取客户端IP地址
获取客户端IP地址对于日志记录和统计很有帮助,以下是一个获取客户端IP地址的代码片段。
function getClientIP() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP')) {
$ipaddress = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_X_FORWARDED')) {
$ipaddress = getenv('HTTP_X_FORWARDED');
} elseif (getenv('HTTP_FORWARDED_FOR')) {
$ipaddress = getenv('HTTP_FORWARDED_FOR');
} elseif (getenv('HTTP_FORWARDED')) {
$ipaddress = getenv('HTTP_FORWARDED');
} elseif (getenv('REMOTE_ADDR')) {
$ipaddress = getenv('REMOTE_ADDR');
} else {
$ipaddress = '127.0.0.1';
}
return $ipaddress;
}
六、实现分页功能
分页功能是网站开发中常见的需求,以下是一个明了的分页功能实现。
function paginate($page, $perPage, $totalRows) {
$totalPages = ceil($totalRows / $perPage);
$offset = ($page - 1) * $perPage;
$html = '
$html .= '
- ';
- ' . $i . ' ';
- ' . $i . ' ';
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $page) {
$html .= '
} else {
$html .= '
}
}
$html .= '
$html .= '';
return [
'html' => $html,
'offset' => $offset,
'perPage' => $perPage
];
}
七、数组深度拷贝
在PHP中,复制数组时通常需要进行深度拷贝,以下是一个实现数组深度拷贝的代码片段。
function deepCopy($array) {
return array_map(function ($item) {
return is_array($item) ? deepCopy($item) : $item;
}, $array);
}
八、获取当前URL
获取当前页面的URL对于生成链接和日志记录很有帮助,以下是一个获取当前URL的代码片段。
function getCurrentUrl() {
$protocol = $_SERVER['HTTPS'] ? 'https' : 'http';
return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
九、实现明了的缓存机制
在PHP中实现明了的缓存机制可以提升程序性能,以下是一个基于文件的明了缓存实现。
function cache($key, $value = null, $duration = 3600) {
$filePath = __DIR__ . '/cache/' . md5($key) . '.txt';
if ($value !== null) {
file_put_contents($filePath, serialize($value));
return true;
}
if (file_exists($filePath) && (time() - filemtime($filePath)) < $duration) {
return unserialize(file_get_contents($filePath));
}
return false;
}
十、生成缩略图
生成缩略图是Web开发中的常见需求,以下是一个生成缩略图的PHP代码片段。
function createThumbnail($sourcePath, $destinationPath, $width, $height) {
list($sourceWidth, $sourceHeight) = getimagesize($sourcePath);
$sourceRatio = $sourceWidth / $sourceHeight;
$targetRatio = $width / $height;
if ($sourceRatio > $targetRatio) {
$newHeight = $height;
$newWidth = $height * $sourceRatio;
} else {
$newWidth = $width;
$newHeight = $width / $sourceRatio;
}
$image = imagecreatetruecolor($width, $height);
$sourceImage = imagecreatefromjpeg($sourcePath);
imagecopyresampled($image, $sourceImage, 0, 0, ($sourceWidth - $newWidth) / 2, ($sourceHeight - $newHeight) / 2, $width, $height, $newWidth, $newHeight);
imagejpeg($image, $destinationPath, 80);
}