15 very useful PHP code snippets for PHP developers

1. Send Mail using mail function in PHP

$to = "viralpatel.net@gmail.com";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.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);
?>

2. Base64 Encode and Decode String in PHP

function base64url_encode($plainText) {
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}
 
function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

3. Get Remote IP Address in PHP

function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}

The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.

function getRealIPAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_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;
}

4. Seconds to String

This function will return the duration of the given time period in days, hours, minutes and seconds.
e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”

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;
}

5. Email validation snippet in PHP

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
    echo 'This is a valid email.';
} else{
    echo 'This is an invalid email.';
}

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML

//this is a sample xml string
$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 simplexml function
$xml = simplexml_load_string($xml_string);
 
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '<br>';
}

7. Database Connection in PHP

<!--?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name
 
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
 
# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
    header('HTTP/1.x 404 Not Found');
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"-->'."n".
    ''."n".
    '<title>404 Not Found</title>'."n".
    ''."n".
    '<h1>Not Found</h1>'."n".
    '<p>The requested URL '.
    str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.</p>'."n".
    ''."n";
    exit;
}
 
# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>

8. Creating and Parsing JSON data in PHP

Following is the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);

Following code will parse the JSON data into PHP arrays.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google

9. Process MySQL Timestamp in PHP

$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
    echo $row;
}

10. Generate An Authentication Code in PHP

This basic snippet will create a random authentication code, or just a random string.

<!--?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
    $pos = rand(0,36);
    $str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?-->

11. Date format validation in PHP

Validate a date in “YYYY-MM-DD” format.

function checkDateFormat($date)
{
    //match the format of the date
    if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
    {
        //check weather the date is valid of not
        if(checkdate($parts[2],$parts[3],$parts[1]))
            return true;
        else
        return false;
    }
    else
        return false;
}

12. HTTP Redirection in PHP

<!--?php
    header('Location: http://you_stuff/url.php'); // stick your url here
?-->

13. Directory Listing in PHP

<!--?php
  
function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
                {
                    echo '<a target="_blank" href="'.$dir.$file.'"-->'.$file.'<br>'."\n";
                }
            }
            closedir($handle);
        }
    }
}
 
/*
To use:
  
<!--?php
    list_files("images/");
?-->
*/
?>

14. Browser Detection script in PHP

<!--?php
    $useragent = $_SERVER ['HTTP_USER_AGENT'];
    echo "<b-->Your User Agent is: " . $useragent;
?>

15. Unzip a Zip File

<!--?php
    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;
        }
    }
?-->
//Use the code as following:
<!--?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?-->

How you like this small collection of PHP code snippets. You may want to paste your code snippet in the comment section below and share it with others. :)

 

[출처] http://viralpatel.net/blogs/15-very-useful-php-code-snippets-for-php-developers/

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
29 How to Call SWI-Prolog from PHP 5 졸리운_곰 2016.05.10 281
28 neural-network by php file 졸리운_곰 2016.03.16 152
27 Learning Library for PHP file 졸리운_곰 2016.03.16 371
26 php 전문가 시스템 php expert system file 졸리운_곰 2016.03.15 56
25 How to Insert JSON Data into MySQL using PHP file 졸리운_곰 2015.12.04 817
24 이클립스(Eclipse) PHP 개발환경 설정. file 졸리운_곰 2015.11.14 216
23 PHP로 만든 달력 file 졸리운_곰 2015.10.27 118
22 라이트 cms 다운로드 ritecms_2.2.1.zip file 졸리운_곰 2015.10.27 24
21 드루팔 다운로드 drupal-7.41.zip file 졸리운_곰 2015.10.27 11
20 도쿠위키 다운로드 dokuwiki-5422200921b.tgz file 졸리운_곰 2015.10.27 47
19 미디어위키 다운로드 mediawiki-1.25.3.tar.gz file 졸리운_곰 2015.10.27 34
18 워드프레스 다운로드 wordpress-4.3.1-ko_KR.zip file 졸리운_곰 2015.10.27 34
17 제로보드 다운로드 XE Core ver. 1.8.13 xe.zip file 졸리운_곰 2015.10.27 30
16 XE 스킨 제작 매뉴얼 v1.1 XE-Skin_Manual-ko(v1.1).pdf file 졸리운_곰 2015.10.26 21
15 제로보드 XE 개발자 가이드 file 졸리운_곰 2015.10.26 23
14 php로 웹 수집 : Basic PHP Web Scraping Script Tutorial 졸리운_곰 2015.09.20 64
13 PHP 와 MYSQL 연동 졸리운_곰 2015.08.11 585
12 PHP 기반의 Micro Frameworks 정리 졸리운_곰 2015.05.15 276
11 PHP의 composer 란 무엇인가?, PHP 의존성 관리도구 졸리운_곰 2015.05.15 372
10 슬림(Slim): 마이크로 프레임워크 [모바일 restful 서버] 졸리운_곰 2015.05.15 243
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED