Summary of PHP instance methods

Source: Internet
Author: User
Tags cos get ip
Many PHPExamples of commonly used methods, students can see, learn to learn these PHPmethod or you can study these PHPexample, to master such knowledge points.

Phpexcel reading Excel

Get the first picture address in the text

Save a picture to a local

Return JSON data

var_dump function rewrite

Image to base64 format

Implementing a GET request with curl

Using curl to implement a POST request

Simple XML-to-array approach

Utf-8 to Uniform Code

String to uniform encoding

Get IP Address

Create a random string

Get age based on birthday

Calculate distance based on latitude and longitude

Phpexcel reading Excel

function Readexcel ($filename, $encode = ' utf-8 ') {//import ("ORG.    Util.PHPExcel.IOFactory ");    Import ("Org/util/phpexcel");    if (Strpos ($filename, "xlsx")) {$objReader = Phpexcel_iofactory::createreader (' Excel2007 ');    } else {$objReader = Phpexcel_iofactory::createreader (' Excel5 ');    } $objReader->setreaddataonly (true);    $objPHPExcel = $objReader->load ($filename);    $objWorksheet = $objPHPExcel->getactivesheet ();    $highestRow = $objWorksheet->gethighestrow ();    $highestColumn = $objWorksheet->gethighestcolumn ();    $highestColumnIndex = phpexcel_cell::columnindexfromstring ($highestColumn);    $excelData = Array (); for ($row = 1; $row <= $highestRow; $row + +) {if (string) $objWorksheet->getcellbycolumnandrow (0, $row)->g        Etvalue () = = "") continue; for ($col = 0; $col < $highestColumnIndex; $col + +) {$value = (string) $objWorksheet->getcellbycolumnandro            W ($col, 1)->getvalue (); if ($value == "") {continue;        } $excelData [$row -1][] = (string) $objWorksheet->getcellbycolumnandrow ($col, $row)->getvalue (); }} return $excelData;}

Get the first picture address in the text

function Getfirstpic ($content) {    if (Preg_match_all ("/(SRC) = ([\" | ']?) ([^ \ "' >]+\. (gif|jpg|jpeg|bmp|png)) \\2/i ", $content, $matches)) {        $str = $matches [3][0];        if (Preg_match ('/\/ueditor\/php\/upload\/image/', $str)) {            return $str 1=substr ($STR, 6);}}    


Save a picture to a local

function GetImage ($url, $save _dir= ", $filename =", $type =1) {if (trim ($url) = = ") {return array (' file_name ' = ', '    Save_path ' = ', ' ERROR ' =>1);    } if (Trim ($save _dir) = = ") {$save _dir= './';        } if (Trim ($filename) = = ") {//save file name $ext = STRRCHR ($url, '. ');        if ($ext! = '. gif ' && $ext! = '. jpg ') {return array (' file_name ' = = ', ' save_path ' = = ', ' ERROR ' =>3);    } $filename =time (). $ext;    } if (0!==strrpos ($save _dir, '/')) {$save _dir.= '/'; }//Create save directory if (!file_exists ($save _dir) &&!mkdir ($save _dir,0777,true)) {return array (' file_name ' = = '),    ' Save_path ' = ', ' ERROR ' =>5);        }//Gets the remote file by the method if ($type) {$ch =curl_init ();        $timeout = 5;        curl_setopt ($ch, Curlopt_url, $url);        curl_setopt ($ch, curlopt_returntransfer,1);        curl_setopt ($ch, Curlopt_connecttimeout, $timeout);        $img =curl_exec ($ch);    Curl_close ($ch);        } else{Ob_start (); ReadfilE ($url);        $img =ob_get_contents ();    Ob_end_clean ();    } $size =strlen ($img);    Echo $size;    File size $fp 2=fopen ($save _dir. $filename, ' a ');    Fwrite ($fp 2, $img);    Fclose ($fp 2);    Unset ($img, $url); The return array (' file_name ' = $filename, ' save_path ' = = $save _dir. $filename, ' error ' =>0);}

Return JSON data

Function Show ($status, $msg, $closeCurrent =false, $data =array ()) {    $TMPARR = array (        ' statusCode ' + = $status,        ' message '    = $msg,        ' closecurrent ' and ' $closeCurrent, '    );    $TMPARR = Array_merge ($TMPARR, $data);    Exit (Json_encode ($TMPARR));}


var_dump function rewrite

function Lyl_dump ($content) {    header ("Content-type:text/html;charset=utf-8");    Echo ' <meta content= ' width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0 "name=" viewport "/ > ';    echo "<pre>";    Var_dump ($content);    echo "<pre/>";    Die;}


Image to base64 format

function Base64encodeimage ($image _file) {    if (!file_exists ($image _file)) {        return false;    }    $image _info = getimagesize ($image _file);    $image _data = fread (fopen ($image _file, ' R '), FileSize ($image _file));    $base 64_image = Chunk_split (Base64_encode ($image _data));    return $base 64_image;}


Implementing a GET request with curl

function HttpGet ($url) {    $curl = Curl_init ();    curl_setopt ($curl, Curlopt_returntransfer, true);    curl_setopt ($curl, Curlopt_timeout,);    curl_setopt ($curl, Curlopt_ssl_verifypeer, true); This is the SSL checksum that needs to be verified    curl_setopt ($curl, Curlopt_ssl_verifyhost, true);//    curl_setopt ($curl, Curlopt_url, $ URL);    $res = curl_exec ($curl);    Curl_close ($curl);    return $res;}


Using curl to implement a POST request

function HttpPost ($url, $post _data) {    $curl = Curl_init ();    $post _data = Json_encode ($post _data);    curl_setopt ($ch, Curlopt_url, $url);    curl_setopt ($ch, Curlopt_header, 0);    curl_setopt ($ch, Curlopt_post, 1);          Set to post mode    curl_setopt ($ch, Curlopt_returntransfer, 1);    curl_setopt ($ch, Curlopt_postfields, $post _data);    $rst = curl_exec ($ch);    Curl_close ($ch);    return $rst;}


Simple XML-to-array approach

function Simplexml_to_array ($simplexml _obj, $array _tags = Array (), $strip _white = 1) {    if ($simplexml _obj) {        if ( Count ($simplexml _obj) = = 0)            return $strip _white trim ((string) $simplexml _obj): (string) $simplexml _obj;        $attr = Array ();        foreach ($simplexml _obj as $k = + $val) {            if (!empty ($array _tags) && In_array ($k, $array _tags)) {                $attr [] = Simplexml_to_array ($val, $array _tags, $strip _white);            } else {                $attr [$k] = Simplexml_to_array ($val, $array _tags, $strip _white);            }        }        return $attr;    }    return FALSE;}


Utf-8 to Uniform Code

function Utf8_to_unicode ($char) {    switch (strlen ($char)) {case        1:            return ord ($char);        Case 2:            $n = (ord ($char [0]) & 0x3f) << 6;            $n + = Ord ($char [1]) & 0x3f;            return $n;        Case 3:            $n = (ord ($char [0]) & 0x1f) <<;            $n + = (ord ($char [1]) & 0x3f) << 6;            $n + = Ord ($char [2]) & 0x3f;            return $n;        Case 4:            $n = (ord ($char [0]) & 0x0f) <<;            $n + = (ord ($char [1]) & 0x3f) <<;            $n + = (ord ($char [2]) & 0x3f) << 6;            $n + = Ord ($char [3]) & 0x3f;            return $n;    }}


String to uniform encoding

function Str_to_unicode_word ($str, $depart = ") {    $arr = array ();    $str _len = Mb_strlen ($str, ' utf-8 ');    for ($i = 0; $i < $str _len; $i + +)    {        $s = mb_substr ($str, $i, 1, ' utf-8 ');        if ($s! = "&& $s! =")        {            $arr [] = ' ux '. Utf8_to_unicode ($s);        }    }    Return implode ($depart, $arr);}


Get IP Address

function GetIP () {    static $realip;    if (Isset ($_server)) {        if (isset ($_server["Http_x_forwarded_for")) {            $realip = $_server["Http_x_forwarded_ For "];        } else if (Isset ($_server["HTTP_CLIENT_IP"])) {            $realip = $_server["Http_client_ip"];        } else {            $realip = $_ server["REMOTE_ADDR"];        }    } else {        if (getenv ("Http_x_forwarded_for")) {            $realip = getenv ("http_x_forwarded_for");        } else if ( Getenv ("Http_client_ip")) {            $realip = getenv ("Http_client_ip");        } else {            $realip = getenv ("remote_addr ");        }    }    return $realip;}


Create a random string

function Createnoncestr ($length = +) {    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";    $str = "";    for ($i = 0; $i < $length; $i + +) {        $str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);    }    return $STR;}


Get age based on birthday

function Get_age ($birthday) {    if ($birthday) {        list ($y 1, $m 1, $d 1) = Explode ("-", Date ("y-m-d", $birthday));        List ($y 2, $m 2, $d 2) = Explode ("-", Date ("Y-m-d", Time ()));        $age = $y 2-$y 1;        if (Intval ($m 2. $d 2) < Intval ($m 1. $d 1)) {$age-= 1;}        return $age;    } else{        return "Unknown";    }}


Calculate distance based on latitude and longitude

function getdistance ($lat 1, $lng 1, $lat 2, $lng 2) {$earthRadius = 6367000;    $lat 1 = ($lat 1 * PI ())/180;    $LNG 1 = ($lng 1 * PI ())/180;    $lat 2 = ($lat 2 * PI ())/180;    $LNG 2 = ($lng 2 * PI ())/180;    $calcLongitude = $lng 2-$LNG 1;    $calcLatitude = $lat 2-$lat 1;    $stepOne = Pow (sin ($calcLatitude/2), 2) + cos ($lat 1) * cos ($lat 2) * POW (sin ($calcLongitude/2), 2);    $STEPTWO = 2 * ASIN (MIN (1, sqrt ($stepOne)));    $calculatedDistance = $earthRadius * $STEPTWO; Return round ($calculatedDistance);} 
Related Article

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.