Favorite PHP common function recommendations

Source: Internet
Author: User
Tags add time date1 ereg flock php excel gtar
Favorite common PHP functions are recommended. Save the following content:

The code is as follows:


Function GetIP () {// obtain the IP address
If ($ _ SERVER ["HTTP_X_FORWARDED_FOR"])
$ Ip = $ _ SERVER ["HTTP_X_FORWARDED_FOR"];
Else if ($ _ SERVER ["HTTP_CLIENT_IP"])
$ Ip = $ _ SERVER ["HTTP_CLIENT_IP"];
Else if ($ _ SERVER ["REMOTE_ADDR"])
$ Ip = $ _ SERVER ["REMOTE_ADDR"];
Else if (getenv ("HTTP_X_FORWARDED_FOR "))
$ Ip = getenv ("HTTP_X_FORWARDED_FOR ");
Else if (getenv ("HTTP_CLIENT_IP "))
$ Ip = getenv ("HTTP_CLIENT_IP ");
Else if (getenv ("REMOTE_ADDR "))
$ Ip = getenv ("REMOTE_ADDR ");
Else
$ Ip = "Unknown ";
Return $ ip;
}
?>


The code is as follows:


Function DateAdd ($ date, $ int, $ unit = "d") {// increase of time (you can also improve it to increase by hour, minute, and second, and then add time)
$ DateArr = explode ("-", $ date );
$ Value [$ unit] = $ int;
Return date ("Y-m-d", mktime (0, 0, 0, $ dateArr [1] + $ value ['M'], $ dateArr [2] + $ value ['D'], $ dateArr [0] + $ value ['Y']);
}
Function GetWeekDay ($ date) {// calculate the day of the week
$ DateArr = explode ("-", $ date );
Return date ("w", mktime (0, 0, 0, $ dateArr [1], $ dateArr [2], $ dateArr [0]);
}
?>


The code is as follows:


Function check_date ($ date) {// check whether the date is valid
$ DateArr = explode ("-", $ date );
If (is_numeric ($ dateArr [0]) & is_numeric ($ dateArr [1]) & is_numeric ($ dateArr [2]) {
Return checkdate ($ dateArr [1], $ dateArr [2], $ dateArr [0]);
}
Return false;
}
Function check_time ($ time) {// check whether the time is valid
$ TimeArr = explode (":", $ time );
If (is_numeric ($ timeArr [0]) & is_numeric ($ timeArr [1]) & is_numeric ($ timeArr [2]) {
If ($ timeArr [0]> = 0 & $ timeArr [0] <= 23) & ($ timeArr [1]> = 0 & $ timeArr [1] <= 59) & ($ timeArr [2]> = 0 & $ timeArr [2] <= 59 ))
Return true;
Else
Return false;
}
Return false;
}


The code is as follows:


Function DateDiff ($ date1, $ date2, $ unit = "") {// Time comparison function, returns the seconds, minutes, hours, or days of difference between two dates
Switch ($ unit ){
Case's ':
$ Pidend = 1;
Break;
Case 'I ':
$ Pidend = 60;
Break;
Case 'H ':
$ Pidend = 3600;
Break;
Case 'D ':
$ Pidend = 86400;
Break;
Default:
$ Pidend = 86400;
}
$ Time1 = strtotime ($ date1 );
$ Time2 = strtotime ($ date2 );
If ($ time1 & $ time2)
Return (float) ($ time1-$ time2)/$ pidend;
Return false;
}
?>


PHP redirection

The code is as follows:


Method 1: header ("Location: index. php ");
Method 2: echo" Window. location = "$ PHP_SELF "; ";
Method 3: echo" ";
?>


Obtain the visitor's browser

The code is as follows:


Function browse_infor ()
{
$ Browser = ""; $ browserver = "";
$ Browsers = array ("Lynx", "MOSAIC", "AOL", "Opera", "JAVA", "MacWeb", "WebExplorer", "OmniWeb ");
$ Agent = $ GLOBALS ["HTTP_USER_AGENT"];
For ($ I = 0; $ I <= 7; $ I ++)
{
If (strpos ($ Agent, $ Browsers [$ I])
{
$ Browser = $ Browsers [$ I];
$ Browserver = "";
}
}
If (ereg ("Mozilla", $ Agent )&&! Ereg ("MSIE", $ Agent ))
{
$ Temp = explode ("(", $ Agent); $ Part = $ temp [0];
$ Temp = explode ("/", $ Part); $ browserver = $ temp [1];
$ Temp = explode ("", $ browserver); $ browserver = $ temp [0];
$ Browserver = preg_replace ("/([d.] +)/", "1", $ browserver );
$ Browserver = "$ browserver ";
$ Browser = "Netscape Navigator ";
}
If (ereg ("Mozilla", $ Agent) & ereg ("Opera", $ Agent ))
{
$ Temp = explode ("(", $ Agent); $ Part = $ temp [1];
$ Temp = explode (")", $ Part); $ browserver = $ temp [1];
$ Temp = explode ("", $ browserver); $ browserver = $ temp [2];
$ Browserver = preg_replace ("/([d.] +)/", "1", $ browserver );
$ Browserver = "$ browserver ";
$ Browser = "Opera ";
}
If (ereg ("Mozilla", $ Agent) & ereg ("MSIE", $ Agent ))
{
$ Temp = explode ("(", $ Agent); $ Part = $ temp [1];
$ Temp = explode (";", $ Part); $ Part = $ temp [1];
$ Temp = explode ("", $ Part); $ browserver = $ temp [2];
$ Browserver = preg_replace ("/([d.] +)/", "1", $ browserver );
$ Browserver = "$ browserver ";
$ Browser = "Internet Explorer ";
}
If ($ browser! = "")
{
$ Browseinfo = "$ browser $ browserver ";
}
Else
{
$ Browseinfo = "Unknown ";
}
Return $ browseinfo;
}
// Call method $ browser = browseinfo (); directly return the result
?>


Obtain the visitor's operating system

The code is as follows:


Function osinfo (){
$ OS = "";
$ Agent = $ GLOBALS ["HTTP_USER_AGENT"];
If (eregi ('win', $ Agent) & strpos ($ Agent, '95 ')){
$ OS = "Windows 95 ";
}
Elseif (eregi ('win 9x', $ Agent) & strpos ($ Agent, '4. 90 ')){
$ OS = "Windows ME ";
}
Elseif (eregi ('win', $ Agent) & ereg ('98 ', $ Agent )){
$ OS = "Windows 98 ";
}
Elseif (eregi ('win', $ Agent) & eregi ('nt 5.0 ', $ Agent )){
$ OS = "Windows 2000 ";
}
Elseif (eregi ('win', $ Agent) & eregi ('nt ', $ Agent )){
$ OS = "Windows NT ";
}
Elseif (eregi ('win', $ Agent) & eregi ('nt 5.1 ', $ Agent )){
$ OS = "Windows XP ";
}
Elseif (eregi ('win', $ Agent) & ereg ('32', $ Agent )){
$ OS = "Windows 32 ";
}
Elseif (eregi ('Linux ', $ Agent )){
$ OS = "Linux ";
}
Elseif (eregi ('unix ', $ Agent )){
$ OS = "Unix ";
}
Elseif (eregi ('sun', $ Agent) & eregi ('OS', $ Agent )){
$ OS = "SunOS ";
}
Elseif (eregi ('IBM ', $ Agent) & eregi (' OS ', $ Agent )){
$ OS = "ibm OS/2 ";
}
Elseif (eregi ('Mac', $ Agent) & eregi ('PC', $ Agent )){
$ OS = "Macintosh ";
}
Elseif (eregi ('powerpc', $ Agent )){
$ OS = "PowerPC ";
}
Elseif (eregi ('aix ', $ Agent )){
$ OS = "AIX ";
}
Elseif (eregi ('hpux ', $ Agent )){
$ OS = "HPUX ";
}
Elseif (eregi ('netsd', $ Agent )){
$ OS = "NetBSD ";
}
Elseif (eregi ('bsd', $ Agent )){
$ OS = "BSD ";
}
Elseif (ereg ('oss1', $ Agent )){
$ OS = "OSF1 ";
}
Elseif (ereg ('irix ', $ Agent )){
$ OS = "IRIX ";
}
Elseif (eregi ('freebsd ', $ Agent )){
$ OS = "FreeBSD ";
}
If ($ OS = '') $ OS =" Unknown ";
Return $ OS;
}
// Call method $ OS = OS _infor ();
?>


File format

The code is as follows:


$ Mime_types = array (
'Gif' => 'image/GIF ',
'Jpg '=> 'image/jpeg ',
'Jpeg '=> 'image/jpeg ',
'Jpe' => 'image/jpeg ',
'Bmp '=> 'image/bmp ',
'PNG '=> 'image/png ',
'Tif '=> 'image/tiff ',
'Tiff '=> 'image/tiff ',
'Pict' => 'image/x-pict ',
'Pic '=> 'image/x-pict ',
'Pct '=> 'image/x-pict ',
'Tif '=> 'image/tiff ',
'Tiff '=> 'image/tiff ',
'Psd '=> 'image/x-photoshop ',
'Swf '=> 'application/x-shockwave-Flash ',
'Js' => 'application/x-Forwarded Cr limit pt ',
'PDF '=> 'application/pdf ',
'Ps' => 'application/postscr reject pt ',
'Eps '=> 'application/postscr reject pt ',
'AI' => 'application/postscr reject pt ',
'WMF '=> 'application/x-msmetafile ',
'Css '=> 'text/css ',
'Htm '=> 'text/html ',
'Html' => 'text/html ',
'Txt '=> 'text/plain ',
'Xml' => 'text/XML ',
'Wml' => 'text/wml ',
'Wbmp '=> 'image/vnd. wap. wbmp ',
'Mid '=> 'audio/midi ',
'Wav '=> 'audio/wav ',
'Mp3' => 'audio/mpeg ',
'Mp2' => 'audio/mpeg ',
'Av' => 'video/x-msvideo ',
'MPEG '=> 'video/mpeg ',
'Mpg' => 'video/mpeg ',
'Qt '=> 'video/quicktime ',
'Mov' => 'video/quicktime ',
'Lha' => 'application/x-lha ',
'Lzh '=> 'application/x-lha ',
'Z' => 'application/x-compress ',
'Gtar '=> 'application/x-gtar ',
'Gz '=> 'application/x-gzip ',
'Gzip '=> 'application/x-gzip ',
'Tgz' => 'application/x-gzip ',
'Tar '=> 'application/x-tar ',
'Bz2' => 'application/bzip2 ',
'Zip' => 'application/zip ',
'Arj' => 'application/x-arj ',
'Rar '=> 'application/x-rar-compressed ',
'Hqx' => 'application/mac-binhex40 ',
'Sit '=> 'application/x-stuffit ',
'Bin' => 'application/x-macbinary ',
'Uu '=> 'text/x-uencode ',
'Uuue' => 'text/x-uencode ',
'Latex '=> 'application/x-latex ',
'Ltx '=> 'application/x-latex ',
'Tcl '=> 'application/x-tcl ',
'Pgp '=> 'application/pgp ',
'Asc' => 'application/pgp ',
'Exe '=> 'application/x-msdownload ',
'Doc' => 'application/msword ',
'Rtf '=> 'application/rtf ',
'XLS '=> 'application/vnd. ms-excel ',
'Ppt '=> 'application/vnd. ms-powerpoint ',
'Mdb '=> 'application/x-msaccess ',
'Wri' => 'application/x-mswrite ',
);
?>


Php excel file generation

The code is as follows:


Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: filename=test.xls ");
Echo "test1t ";
Echo "test2tn ";
Echo "test1t ";
Echo "test2tn ";
Echo "test1t ";
Echo "test2tn ";
Echo "test1t ";
Echo "test2tn ";
Echo "test1t ";
Echo "test2tn ";
Echo "test1t ";
Echo "test2tn ";
// You can change the corresponding file header to export file formats such as .doc. xls.
?>


Time comparison problems
For example, a forum marks a post posted on the day with a new image.
Method 1:

The code is as follows:


// $ Db-> rows [$ I] [date] indicates the datetime field value in the database.
$ Today = time ();
$ TheDay = date ("Y-m-d H: I: s", $ today-24*3600 );
$ NewTag = $ db-> rows [$ I] [date]> = $ theDay? "":"";
// Method 2:
$ NewTag = $ db-> rows [$ I] [date]> = date ("Y-m-d 00:00:00 ")? "":"";
?>


The code is as follows:


// Extract the variables submitted by the page and browser, which is equivalent to enabling PHP. INI to enable global variables.
@ Extract ($ _ SERVER, EXTR_SKIP );
@ Extract ($ _ SESSION, EXTR_SKIP );
@ Extract ($ _ POST, EXTR_SKIP );
@ Extract ($ _ FILES, EXTR_SKIP );
@ Extract ($ _ GET, EXTR_SKIP );
@ Extract ($ _ ENV, EXTR_SKIP );
?>


The code is as follows:


// Read the file function
Function readfromfile ($ file_name ){
If (file_exists ($ file_name )){
$ Filenum = fopen ($ file_name, "r ");
Flock ($ filenum, LOCK_EX );
$ File_data = fread ($ filenum, filesize ($ file_name ));
Rewind ($ filenum );
Fclose ($ filenum );
Return $ file_data;
}
}
?>


The code is as follows:


// File writing function
Function writetofile ($ file_name, $ data, $ method = "w "){
$ Filenum = fopen ($ file_name, $ method );
Flock ($ filenum, LOCK_EX );
$ File_data = fwrite ($ filenum, $ data );
Fclose ($ filenum );
Return $ file_data;
}
?>


The code is as follows:


// Quick page redirection
Function turntopage ($ url = "index. php", $ info = "page redirection...", $ second = 2 ){
Print"NNPage turning ....N ";
Print" N ";
Print"N ";
Print"NN ";
Print"











N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print"
N ";
Print"










N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print" N ";Print"N ";Print"
Page redirection prompt information
$ Info
N ";
Print "if your browser does not support automatic jump, click here
N ";
Print"N";
Exit;
?>


Generate random string functions

The code is as follows:


Function random ($ length ){
$ Hash = @#@#;
$ Chars =@# ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz @#;
$ Max = strlen ($ chars)-1;
Mt_srand (double) microtime () * 1000000 );
For ($ I = 0; $ I <$ length; $ I ++ ){
$ Hash. = $ chars [mt_rand (0, $ max)];
}
Return $ hash;
}
?>


Truncate a string of a certain length (this function is valid for GB2312)

The code is as follows:


Function Wordscut ($ string, $ length, $ sss = 0 ){
If (strlen ($ string)> $ length ){
If ($ sss ){
$ Length = $ length-3;
$ Addstr = @#...@#;
}
For ($ I = 0; $ I <$ length; $ I ++ ){
If (ord ($ string [$ I])> 127 ){
$ Wordscut. = $ string [$ I]. $ string [$ I + 1];
$ I ++;
} Else {
$ Wordscut. = $ string [$ I];
}
}
Return $ wordscut. $ addstr;
}
Return $ string;
}
?>


Obtain the client IP address

The code is as follows:


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 [@ # REMOTE_ADDR @ #]) & $ _ SERVER [@ # REMOTE_ADDR @ #] & strcasecmp ($ _ SERVER [@ # REMOTE_ADDR @ #], "unknown "))
$ Ip = $ _ SERVER [@ # REMOTE_ADDR @ #];
Else
$ Ip = "unknown ";
Return ($ ip );
}
?>


Determine email address

The code is as follows:


Function checkEmail ($ inAddress)
{
Return (ereg ("^ ([a-zA-Z0-9 _-]) + @ ([a-zA-Z0-9 _-]) + (. [a-zA-Z0-9 _-]) +", $ inAddress ));
}
?>


Paging (use with two functions)

The code is as follows:


Function getpage ($ SQL, $ page_size = 20)
{
Global $ page, $ totalpage, $ sums; // out param
$ Page = $ _ GET ["page"];
// $ Eachpage = $ page_size;
$ Pagesql = strstr ($ SQL, "from ");
$ Pagesql = "select count (*) as ids". $ pagesql;
$ Result = mysql_query ($ pagesql );
If ($ rs = mysql_fetch_array ($ result) $ sums = $ rs [0];
$ Totalpage = ceil ($ sums/$ page_size );
If ((! $ Page) ($ page <1) $ page = 1;
$ Startpos = ($ page-1) * $ page_size;
$ SQL. = "limit $ startpos, $ page_size ";
Return $ SQL;
}
Function showbar ($ string = "")
{
Global $ page, $ totalpage;
$ Out = "total". $ Totalpage ."Page ";
$ LinkNum = 4;
$ Start = ($ page-round ($ linkNum/2)> 0? ($ Page-round ($ linkNum/2): "1 ";
$ End = ($ page + round ($ linkNum/2) <$ totalpage? ($ Page + round ($ linkNum/2): $ totalpage;
$ Prestart = $ start-1;
$ Nextend = $ end + 1;
If ($ page <> 1)
$ Out. = "first page ";
If ($ start> 1)
$ Out. = "... <";
For ($ t = $ start; $ t <= $ end; $ t ++)
{
$ Out. = ($ page = $ t )? "[". $ T."]":" $ T ";
}
If ($ end <$ totalpage)
$ Out. = "> ..";
If ($ page <> $ totalpage)
$ Out. = "Last page ";
Return $ out;
}
?>


Obtain the ID of the newly inserted data

The code is as follows:


Mysql_insert_id ();
?>


The code is as follows:


// Obtain the current script URL
Function get_php_url (){
If (! Empty ($ _ server ["REQUEST_URI"]) {
$ ScriptName = $ _ SERVER ["REQUEST_URI"];
$ Nowurl = $ scriptName;
} Else {
$ ScriptName = $ _ SERVER ["PHP_SELF"];
If (empty ($ _ SERVER ["QUERY_STRING"]) $ nowurl = $ scriptName;
Else $ nowurl = $ scriptName ."? ". $ _ SERVER [" QUERY_STRING "];
}
Return $ nowurl;
}
?>


The code is as follows:


// Convert the fullwidth number into a halfwidth number
Function GetAlabNum ($ fnum ){
$ Nums = array ("0", "1", "2", "3", "4", "5", "6", "7 ", "8", "9 ");
$ Fnums = "0123456789 ";
For ($ I = 0; $ I <= 9; $ I ++) $ fnum = str_replace ($ nums [$ I], $ fnums [$ I], $ fnum );
$ Fnum = ereg_replace ("[^ 0-9.] | ^ 0 {1,}", "", $ fnum );
If ($ fnum = "") $ fnum = 0;
Return $ fnum;
}
?>


The code is as follows:


// Remove HTML tags
Function Text2Html ($ txt ){
$ Txt = str_replace ("", "", $ txt );
$ Txt = str_replace ("<", "<", $ txt );
$ Txt = str_replace (">", ">", $ txt );
$ Txt = preg_replace ("/[rn] {1,}/isU ","
Rn ", $ txt );
Return $ txt;
}
?>


The code is as follows:


// Convert relative paths to absolute paths
Function relative_to_absolute ($ content, $ feed_url ){
Preg_match ('/(http | https | ftp): //', $ feed_url, $ protocol );
$ Server_url = preg_replace ("/(http | https | ftp | news): //", "", $ feed_url );
$ Server_url = preg_replace ("//. */", "", $ server_url );
If ($ server_url = ''){
Return $ content;
}
If (isset ($ protocol [0]) {
$ New_content = preg_replace ('/href = "//', 'href =" '. $ protocol [0]. $ server_url.'/', $ content );
$ New_content = preg_replace ('/src = "//', 'src =" '. $ protocol [0]. $ server_url.'/', $ new_content );
} Else {
$ New_content = $ content;
}
Return $ new_content;
}
?>


The code is as follows:


// Get all links
Function get_all_url ($ code ){
Preg_match_all ('/"'] +) [" | ']? S * [^>] *> ([^>] +)/I ', $ code, $ arr );
Return array ('name' => $ arr [2], 'URL' => $ arr [1]);
}
?>


The code is as follows:


// Convert each line of the HTML table into an array in CSV format
Function get_tr_array ($ table ){
$ Table = preg_replace ("' ] *?> 'Si ", '"', $ table );
$ Table = str_replace ("", '",', $ Table );
$ Table = str_replace (""," {Tr} ", $ table );
// Remove the HTML tag
$ Table = preg_replace ("'<[/!] *? [^ <>] *?> 'Si "," ", $ table );
// Remove the white space characters
$ Table = preg_replace ("'([rn]) [s] +'", "", $ table );
$ Table = str_replace ("", "", $ table );
$ Table = str_replace ("", "", $ table );
$ Table = explode (", {tr}", $ table );
Array_pop ($ table );
Return $ table;
}
?>


The code is as follows:


// Convert each row and column of an HTML table into an array to collect table data
Function get_td_array ($ table ){
$ Table = preg_replace ("' ] *?> 'Si "," ", $ table );
$ Table = preg_replace ("' ] *?> 'Si "," ", $ table );
$ Table = preg_replace ("' ] *?> 'Si "," ", $ table );
$ Table = str_replace (""," {Tr} ", $ table );
$ Table = str_replace (""," {Td} ", $ table );
// Remove the HTML tag
$ Table = preg_replace ("'<[/!] *? [^ <>] *?> 'Si "," ", $ table );
// Remove the white space characters
$ Table = preg_replace ("'([rn]) [s] +'", "", $ table );
$ Table = str_replace ("", "", $ table );
$ Table = str_replace ("", "", $ table );
$ Table = explode ('{tr}', $ table );
Array_pop ($ table );
Foreach ($ table as $ key => $ tr ){
$ Td = explode ('{td}', $ tr );
Array_pop ($ td );
$ Td_array [] = $ td;
}
Return $ td_array;
}
?>


The code is as follows:


// Return all words in the string $ distinct = true to remove duplicates
Function split_en_str ($ str, $ distinct = true ){
Preg_match_all ('/([a-zA-Z] +)/', $ str, $ match );
If ($ distinct = true ){
$ Match [1] = array_unique ($ match [1]);
}
Sort ($ match [1]);
Return $ match [1];
}
?>


The code is as follows:


// Print out a list of people contributing to this PHP project
String phpcredits (void)
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.