46 very useful snippets of PHP code (II)

Source: Internet
Author: User
Tags date1

16. Unzip the file [code]php code:

function unzip ($location, $newLocation) {        if (EXEC ("Unzip $location", $arr)) {            mkdir ($newLocation);            for ($i = 1; $i < count ($arr), $i + +) {                $file = Trim (Preg_replace ("~inflating: ~", "", $arr [$i]));                Copy ($location. ' /'. $file, $newLocation. ' /'. $file);                Unlink ($location. ' /'. $file);            }            return TRUE;        } else{            return FALSE;        }}

Grammar:

<?php

Unzip (' Test.zip ', ' unziped/test '); File would is unzipped in Unziped/test folder

?>

17. Zoom Image

[Code]php Code:

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;      } $im 2 = Imagecreatetruecolor ($newx, $newy);      Imagecopyresized ($im 2, $im, 0, 0, 0, 0, Floor ($newx), Floor ($newy), $x, $y);   return $im 2; }

18. Send mail using mail ()

We've previously provided snippets of PHP code to send mail using Mandrill, but if you don't want to use a third-party service, you can use the following PHP snippet.

[Code]php Code:

function Send_mail ($to, $subject, $body) {$headers = "from:koonk\r\n"; $headers. = "reply-to:blog@koonk.com\r\n"; $ Headers. = "return-path:blog@koonk.com\r\n"; $headers. = "x-mailer:php5\n"; $headers. = ' mime-version:1.0 '. "\ n"; $headers. = ' content-type:text/html; Charset=iso-8859-1 '. "\ r \ n"; Mail ($to, $subject, $body, $headers);}

Grammar:

<?php

$to = "admin@koonk.com";

$subject = "This is a test mail";

$body = "Hello world!";

Send_mail ($to, $subject, $body);

?>

19. Convert seconds to days, hours and minutes

[Code]php Code:

function Secstostr ($secs) {    if ($secs >=86400) {$days =floor ($secs/86400); $secs = $secs%86400; $r = $days. ' Day '; if ($days <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}    if ($secs >=3600) {$hours =floor ($secs/3600), $secs = $secs%3600; $r. = $hours. ' Hour '; if ($hours <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}    if ($secs >=60) {$minutes =floor ($secs/60), $secs = $secs%60; $r. = $minutes. ' Minute '; if ($minutes <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}    $r. = $secs. ' Second '; if ($secs <>1) {$r. = ' s ';}    return $r;}

Grammar:

<?php

$seconds = "56789";

$output = Secstostr ($seconds);

Echo $output;

?>

20. Database connection

<?php$dbname = ' Koonk '; $HOST = ' localhost '; $DBUSER = ' root '; $DBPASS = ' Koonk '; $CONNECT = mysql_connect ($HOST, $DBUSER, $DBPASS); if (! $CONNECT) {    echo ' MySQL Error: '. mysql_error ();} $SELECT = mysql_select_db ($DBNAME), if (! $SELECT) {    echo ' mysql Error: '. mysql_error ();}? >

21. Catalogue List

Use the following PHP code snippet to list all files and folders in a directory

[Code]php Code:

function List_files ($dir) {    if (Is_dir ($dir))    {        if ($handle = Opendir ($dir))        {while            ($file = Readdir ($handle))!== false)            {                if ($file! = "." && $file! = ":" && $file! = "Thumbs.db"/*pesky win dows, images. */)                {                    echo ' <a target= "_blank" href= "'. $dir. $file. '" > '. $file. ' </a><br> '. ' \ n ";                }            }            Closedir ($handle);}}    

Grammar:

<?php

List_files ("images/"); This would list all files of images folder

?>

22. Detecting User Language

Use the following PHP code snippet to detect the language used by the user's browser

[Code]php Code:

function Get_client_language ($availableLanguages, $default = ' en ') {    if (isset ($_server[' http_accept_language ')) {        $langs =explode (', ', $_server[' http_accept_language '));        foreach ($langs as $value) {            $choice =substr ($value, 0,2);            if (In_array ($choice, $availableLanguages)) {                return $choice;            }        }    }     return $default;}

23. View the CSV file

[Code]php Code:

function Readcsv ($csvFile) {    $file _handle = fopen ($csvFile, ' R ');    while (!feof ($file _handle)) {        $line _of_text[] = fgetcsv ($file _handle, 1024x768);    }    Fclose ($file _handle);    return $line _of_text;}

Grammar:

<?php

$csvFile = "Test.csv";

$csv = Readcsv ($csvFile);

$a = csv[0][0]; This'll get value of Column 1 & Row 1

?>

24. Create a CSV file from PHP data

[Code]php Code:

function Generatecsv ($data, $delimiter = ', ', $enclosure = ' "') {   $handle = fopen (' php://temp ', ' r+ ');   foreach ($data as $line) {           fputcsv ($handle, $line, $delimiter, $enclosure);   }   Rewind ($handle);   while (!feof ($handle)) {           $contents. = Fread ($handle, 8192);   }   Fclose ($handle);   return $contents;}

Grammar:

<?php

$data [0] = "apple";

$data [1] = "oranges";

Generatecsv ($data, $delimiter = ', ', $enclosure = ' "');

?>

25. Parsing XML Data

[Code]php Code:

$xml _string= "<!--? XML version= ' 1.0 '?--><moleculedb>    <molecule name=" Benzine ">        < symbol>ben</symbol>        <code>A</code>    </molecule>    <molecule name= "Water" >        <symbol>h2o</symbol>        <code>K</code>    </molecule></moleculedb > ";  Load the XML string using <a href= "http://www.php-z.com/" target= "_blank" class= "Relatedlink" >Simple</a> XML function$xml = simplexml_load_string ($xml _string);  Loop through the each node of Moleculeforeach ($xml->molecule as $record) {   //attribute is accessted by   Ech o $record [' name '], '  ;   Node   is accessted by-and operator Echo $record->symbol, "  ;   echo $record->code, ' <br> ';}

26. Parsing JSON Data

[Code]php Code:

$json _string= ' {"id": 1, "name": "Rolf", "Country": "Russia", "office": ["Google", "Oracle"]} '; $obj =json_decode ($json _ string);//print the parsed Dataecho $obj->name; Displays Rolfecho $obj->office[0]; Displays Google

27. Get the current page URL

This PHP snippet can help you get the user to log in and jump directly to the previously viewed page

[Code]php Code:

function Current_url () {$url = "http://". $_server[' Http_host '). $_server[' Request_uri ']; $validURL = Str_replace (" & "," & ", $url); return validurl;}

Grammar:

<?php

echo "Currently you is on:". Current_url ();

?>

28. Get the latest tweets from any Twitter account

[Code]php Code:

function My_twitter ($username) {     $no _of_tweets = 1;     $feed = "Http://search.twitter.com/search.atom?q=from:". $username. "&rpp=". $no _of_tweets;     $xml = Simplexml_load_file ($feed);    foreach ($xml->children () as $child) {        foreach ($child as $value) {            if ($value->getname () = = "link") $link = $ value[' href '];            if ($value->getname () = = "Content") {                $content = $value. "";        Echo ' <p class= ' twit > ' $content. ' <a class= ' TWT ' href= '. $link. ' title= ' >  </a></p> ';            }            }    }    }

Grammar:

<?php

$handle = "Koonktech";

My_twitter ($handle);

?>

29. Number of forwards

Use this PHP fragment to detect how many forwards you have in your page URL

[Code]php Code:

function Tweetcount ($url) {    $content = file_get_contents ("http://api.tweetmeme.com/url_info?url=". $url);    $element = new SimpleXMLElement ($content);    $retweets = $element->story->url_count;    if ($retweets) {        return $retweets;    } else {        return 0;}    }

Grammar:

<?php

$url = "http://blog.koonk.com";

$count = Tweetcount ($url);

return $count;

?>

30. Calculate the difference of two dates

[Code]php Code:

<!--? php$date1 = date (' y-m-d '); $date 2 = "2015-12-04"; $diff = ABS (Strtotime ($date 2)-Strtotime ($date 1)); $years = Floo  R ($diff/(365*60*60*24)), $months = Floor (($diff-$years * 365*60*60*24)/(30*60*60*24)), $days = Floor (($diff-$years * 365*60*60*24-$months *30*60*60*24)/(60*60*24));p rintf ("%d years,%d months,%d days\n", $years, $months, $days);------- -------------------------------------------------or$date1 = new DateTime ("2007-03-24"), $date 2 = new DateTime (" 2009-06-26 ") $interval = $date 1--->diff ($date 2); echo" Difference ". $interval->y. "Years,". $interval->m. "Months,". $interval->d. "Days"; Shows the total amount's (not divided to years, months and days like above) echo "difference". $interval->days. "Days";--------------------------------------------------------or/** * Calculate differences between the date s with precise semantics. <a href= "http://www.php-z.com/" target= "_blank" class= "Relatedlink" >base</a>dOn PHPs DateTime::d iff () * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved. * * See here for original code: * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision= 302890&view=markup * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973        &view=markup */function _date_range_limit ($start, $end, $adj, $a, $b, $result) {if ($result [$a] < $start) {        $result [$b]-= Intval (($start-$result [$a]-1)/$adj) + 1;    $result [$a] + = $adj * Intval (($start-$result [$a]-1)/$adj + 1);        if ($result [$a] >= $end) {$result [$b] + = intval ($result [$a]/$ADJ);    $result [$a]-= $adj * Intval ($result [$a]/$ADJ); } return $result;} function _date_range_limit_days ($base, $result) {$days _in_month_leap = array (31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31    , 30, 31);    $days _in_month = Array (31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); _date_range_Limit (1, x, N, "M", "Y", & $base);    $year = $base ["Y"];    $month = $base ["M"];            if (! $result ["invert"]) {while ($result ["D"] < 0) {$month--;                if ($month < 1) {$month + = 12;            $year--; } $leapyear = $year% 400 = = 0 | |            ($year%! = 0 && $year% 4 = = 0); $days = $leapyear?            $days _in_month_leap[$month]: $days _in_month[$month];            $result ["D"] + = $days;        $result ["M"]--; }} else {while ($result ["D"] < 0) {$leapyear = $year% 400 = = 0 | |            ($year%! = 0 && $year% 4 = = 0); $days = $leapyear?            $days _in_month_leap[$month]: $days _in_month[$month];            $result ["D"] + = $days;            $result ["M"]--;            $month + +;                if ($month >) {$month-= 12;            $year + +; }}} return $result;} function _date_normalize ($base, $result) {$rEsult = _date_range_limit (0, a, "s", "I", $result);    $result = _date_range_limit (0, Max, "I", "H", $result);    $result = _date_range_limit (0, a, "H", "D", $result);    $result = _date_range_limit (0, N, a, "M", "Y", $result);    $result = _date_range_limit_days (& $base, & $result);    $result = _date_range_limit (0, N, a, "M", "Y", $result); return $result;} /** * accepts, UNIX timestamps.    */function _date_diff ($one, $two) {$invert = false;        if ($one > $two) {list ($one, $two) = Array ($two, $one);    $invert = true;    } $key = Array ("Y", "M", "D", "H", "I", "s");    $a = Array_combine ($key, Array_map ("Intval", Explode ("", Date ("Y m D H i S", $one))));    $b = Array_combine ($key, Array_map ("Intval", Explode ("", Date ("Y m D H i S", $two))));    $result = Array ();    $result ["y"] = $b ["y"]-$a ["Y"];    $result ["M"] = $b ["M"]-$a ["M"];    $result ["d"] = $b ["D"]-$a ["D"];    $result ["h"] = $b ["h"]-$a ["H"]; $result ["i"] = $b ["I"]-$a ["I"];    $result ["s"] = $b ["s"]-$a ["s"]; $result ["invert"] = $invert?    1:0;    $result ["days"] = Intval (ABS (($one-$two)/86400);    if ($invert) {_date_normalize (& $a, & $result);    } else {_date_normalize (& $b, & $result); } return $result;} $date = "2014-12-04 19:37:22"; Echo ' <pre> ';p rint_r (_date_diff (Strtotime ($date), Time ()); Echo ' </pre> ';? >

The above is 46 very useful PHP code fragment (ii) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.