當(dāng)前位置:工程項(xiàng)目OA系統(tǒng) > 泛普各地 > 江西OA系統(tǒng) > 鷹潭OA > 鷹潭網(wǎng)站建設(shè)公司
PHP函數(shù)代碼段
1. PHP可閱覽隨機(jī)字符串
此代碼將創(chuàng)立一個(gè)可閱覽的字符串,使其更挨近詞典中的單詞,有用且具有暗碼驗(yàn)證功用。
/**************
*@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;
}
2. PHP生成一個(gè)隨機(jī)字符串
若是不需求可閱覽的字符串,運(yùn)用此函數(shù)代替,即可創(chuàng)立一個(gè)隨機(jī)字符串,作為用戶的隨機(jī)暗碼等。
/*************
*@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;
}
3. PHP編碼電子郵件地址
運(yùn)用此代碼,可以將任何電子郵件地址編碼為 html 字符實(shí)體,以避免被垃圾郵件順序搜集。
function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, $attrs =’class=”emailencoder”‘ )
{
// remplazar aroba y puntos
$email = str_replace(‘@’, ‘@’, $email);
$email = str_replace(‘.’, ‘.’, $email);
$email = str_split($email, 5);
$linkText = str_replace(‘@’, ‘@’, $linkText);
$linkText = str_replace(‘.’, ‘.’, $linkText);
$linkText = str_split($linkText, 5);
$part1 = ‘$part2 = ‘ilto:’;
$part3 = ‘” ‘. $attrs .’ >’;
$part4 = ‘’;
$encoded = ‘’;
return $encoded;
}
4. PHP驗(yàn)證郵件地址
電子郵件驗(yàn)證也許是中最常用的網(wǎng)頁表單驗(yàn)證,此代碼除了驗(yàn)證電子郵件地址,也可以挑選查看郵件域所屬 DNS 中的 MX 記載,使郵件驗(yàn)證功用愈加強(qiáng)壯。
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;
}
5. PHP列出目錄內(nèi)容
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != “.” && $file != “..” && $file != “Thumbs.db”)
{
echo ‘’.$file.’
’.”n”;
}
}
closedir($handle);
}
}
}
6. PHP毀掉目錄
刪去一個(gè)目錄,包羅它的內(nèi)容。
/*****
*@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 == ‘.’ || $file == ‘..’)
{
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;
}
}
7. PHP解析 JSON 數(shù)據(jù)
與大多數(shù)盛行的 Web 效勞如 twitter 經(jīng)過敞開 API 來供給數(shù)據(jù)相同,它總是可以曉得如何解析 API 數(shù)據(jù)的各種傳送格局,包羅 JSON,XML 等等。
$json_string=’{“id”:1,”name”:”foo”,”email”:”foo@foobar.com”,”interest”:["wordpress","php"]} ‘;
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php
8. PHP解析 XML 數(shù)據(jù)
//xml string
$xml_string=”
Foo
foo@bar.com
Foobar
foobar@foo.com
”;
//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['id'], ‘ ‘;
//subnodes are accessed by -> operator
echo $user->name, ‘ ‘;
echo $user->email, ‘
’;
}
9. PHP創(chuàng)立日志縮略名
創(chuàng)立用戶友愛的日志縮略名。
function create_slug($string){
$slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);
return $slug;
}
10. PHP獲取客戶端實(shí)在 IP 地址
該函數(shù)將獲取用戶的實(shí)在 IP 地址,即使他運(yùn)用代理效勞器。
function getRealIpAddr()
{
if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
11. PHP強(qiáng)制性文件下載
為用戶供給強(qiáng)制性的文件下載功用。
/********************
*@file – path to file
*/
function force_download($file)
{
if ((isset($file))&&(file_exists($file))) {
header(“Content-length: “.filesize($file));
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=”‘ . $file . ‘”‘);
readfile(“$file”);
} else {
echo “No file selected”;
}
}
12. PHP創(chuàng)立標(biāo)簽云
function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
{
$minimumCount = min( array_values( $data ) );
$maximumCount = max( array_values( $data ) );
$spread = $maximumCount – $minimumCount;
$cloudHTML = ”;
$cloudTags = array();
$spread == 0 && $spread = 1;
foreach( $data as $tag => $count )
{
$size = $minFontSize + ( $count – $minimumCount )
* ( $maxFontSize – $minFontSize ) / $spread;
$cloudTags[] = ‘. ‘” href=”#” title=”” . $tag .
‘’ returned a count of ‘ . $count . ‘”>’
. htmlspecialchars( stripslashes( $tag ) ) . ‘’;
}
return join( “n”, $cloudTags ) . “n”;
}
/**************************
**** Sample usage ***/
$arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44, ‘Background’ => 43,
‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11, ‘Crop’ => 42,
‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12, ‘Encryption’ => 30,
‘Extract’ => 28, ‘Filters’ => 42);
echo getCloud($arr, 12, 36);
13. PHP尋覓兩個(gè)字符串的類似性
PHP 供給了一個(gè)很少運(yùn)用的 similar_text 函數(shù),但此函數(shù)非常有用,用于比擬兩個(gè)字符串并回來類似程度的百分比。
similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity
14. PHP在應(yīng)用順序中運(yùn)用 Gravatar 通用頭像
跟著 WordPress 越來越遍及,Gravatar 也隨之盛行。由于 Gravatar 供給了易于運(yùn)用的 API,將其歸入應(yīng)用順序也變得非常便利。
/******************
*@email – Email address to show gravatar for
*@size – size of gravatar
*@default – URL of default gravatar to use
*@rating – rating of Gravatar(G, PG, R, X)
*/
function show_gravatar($email, $size, $default, $rating)
{
echo ‘‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”
height=”‘.$size.’px” />’;
}
15. PHP在字符斷點(diǎn)處切斷文字
所謂斷字 (word break),即一個(gè)單詞可在轉(zhuǎn)行時(shí)斷開的當(dāng)?shù)?。這一函數(shù)將在斷字處切斷字符串。
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;
// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) – 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string, 100, ‘ ‘);
16. PHP文件 Zip 緊縮
/* creates a compressed zip file */
function create_zip($files = array(),$destination = ”,$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in…
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files…
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
//close the zip — done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);
create_zip($files, ‘myzipfile.zip’, true);
17. PHP解緊縮 Zip 文件
/**********************
*@file – path to zip file
*@destination – destination directory for unzipped files
*/
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
die (’Could not open archive’);
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
echo ‘Archive extracted to directory’;
}
18. PHP為 URL 地址預(yù)設(shè) http 字符串
有時(shí)需求承受一些表單中的網(wǎng)址輸入,但用戶很少增加 http:// 字段,此代碼將為網(wǎng)址增加該字段。
if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
$_POST['url'] = ‘http://’.$_POST['url'];
}
19. PHP將網(wǎng)址字符串轉(zhuǎn)換成超級(jí)鏈接
該函數(shù)將 URL 和 E-mail 地址字符串轉(zhuǎn)換為可點(diǎn)擊的超級(jí)鏈接。
function makeClickableLinks($text) {
$text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘1’, $text);
$text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘12’, $text);
$text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
‘1’, $text);
return $text;
}
20. PHP調(diào)整圖畫尺度
創(chuàng)立圖畫縮略圖需求許多工夫,此代碼將有助于明白縮略圖的邏輯。
/**********************
*@filename – path to the image
*@tmpname – temporary path to thumbnail
*@xmax – max width
*@ymax – max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
$ext = explode(“.”, $filename);
$ext = $ext[count($ext)-1];
if($ext == “jpg” || $ext == “jpeg”)
$im = imagecreatefromjpeg($tmpname);
elseif($ext == “png”)
$im = imagecreatefrompng($tmpname);
elseif($ext == “gif”)
$im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax)
return $im;
if($x >= $y) {
$newx = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
21. PHP檢測 ajax 懇求
大多數(shù)的 JavaScript 結(jié)構(gòu)如 jquery,Mootools 等,在宣布 Ajax 懇求時(shí),城市發(fā)送額定的 HTTP_X_REQUESTED_WITH 頭部信息,頭當(dāng)他們一個(gè)ajax懇求,因而你可以在效勞器端偵測到 Ajax 懇求。
if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){
//If AJAX Request Then
}else{
//something else
}
- 1PHP/MYSQL 查詢大數(shù)據(jù)
- 2代碼審查可以幫助提高代碼質(zhì)量
- 3Windows Azure 網(wǎng)站上運(yùn)行 CakePHP
- 4上海天煜商業(yè)聯(lián)盟成功上線
- 5玩具租賃商城系統(tǒng)需求1
- 6Zend2.0的MVC完整過程。
- 7企業(yè)為什么偏愛要求資深的網(wǎng)站維護(hù)單位做網(wǎng)站呢?
- 8玩具租賃系統(tǒng)功能列表
- 9PHP 安全措施
- 10PHPUnit
- 11萬網(wǎng)云服務(wù)器,優(yōu)惠啦!!!
- 12如何讓企業(yè)網(wǎng)站發(fā)揮到機(jī)極致
- 13JavaScript cookie詳解
- 14ecshop的數(shù)據(jù)字典
- 15網(wǎng)站改版注意的問題
- 16久途-網(wǎng)站制作流程
- 17企業(yè)為什么偏愛需要資深的網(wǎng)站設(shè)計(jì)企業(yè)做官方網(wǎng)站呢?
- 18網(wǎng)貸平臺(tái)主要運(yùn)營模式主要有兩類---傳統(tǒng)P2P模式
- 19網(wǎng)站制作絕對(duì)不可以犯的編程錯(cuò)誤2
- 20玩具租賃商城系統(tǒng)需求7
- 21企業(yè)網(wǎng)站的優(yōu)化現(xiàn)狀
- 22久途愿景
- 23301重定向?qū)?04錯(cuò)誤轉(zhuǎn)化為網(wǎng)站外鏈
- 24網(wǎng)站建設(shè)的效果圖設(shè)計(jì)不好導(dǎo)致的一些后果
- 25醫(yī)療設(shè)備一體化業(yè)務(wù)管理系統(tǒng)解決方案
- 26每個(gè)cookie都是一個(gè)名/值對(duì)
- 27404過錯(cuò)跳轉(zhuǎn)到一個(gè)頁面,咱們?nèi)∶校簃issing404.php
- 28再次提及貸款風(fēng)險(xiǎn)管理
- 29瀏覽器開發(fā)工具的秘密
- 30網(wǎng)站制作如何設(shè)計(jì)網(wǎng)站
成都公司:成都市成華區(qū)建設(shè)南路160號(hào)1層9號(hào)
重慶公司:重慶市江北區(qū)紅旗河溝華創(chuàng)商務(wù)大廈18樓