非常に有用なphpコードクリップ


1.SMS送信
Webやモバイルアプリケーションを開発する際、ユーザーにSMSを送信する必要がある場合や、ログインの理由や、情報を送信するために発生することがよくあります.以下のPHPコードはSMSを送信する機能を実現している.
任意の言語でSMSを送信するには、SMS gatewayが必要です.ほとんどのSMSは、MSG 91をSMS gatewayとして使用するAPIを提供します.
function send_sms($mobile,$msg)
	{
	$authKey = "XXXXXXXXXXX";
	date_default_timezone_set("Asia/Kolkata");
	$date = strftime("%Y-%m-%d %H:%M:%S");
	//Multiple mobiles numbers separated by comma
	$mobileNumber = $mobile;

	//Sender ID,While using route4 sender id should be 6 characters long.
	$senderId = "IKOONK";  

	//Your message to send, Add URL encoding here.
	$message = urlencode($msg);   

	//Define route
	$route = "template";

	//Prepare you post parameters
	$postData = array(
	    'authkey' => $authKey,
	    'mobiles' => $mobileNumber,
	    'message' => $message,
	    'sender' => $senderId,
	    'route' => $route
	);
	   
	//API URL
	$url="https://control.msg91.com/sendhttp.php";
	   
	// init the resource
	$ch = curl_init();
	curl_setopt_array($ch, array(
	    CURLOPT_URL => $url,
	    CURLOPT_RETURNTRANSFER => true,
	    CURLOPT_POST => true,
	    CURLOPT_POSTFIELDS => $postData
	    //,CURLOPT_FOLLOWLOCATION => true
	));
	   
	//Ignore SSL certificate verification
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	   
	//get response
	$output = curl_exec($ch);
	//Print error if any
	if(curl_errno($ch))
	{
	    echo 'error:' . curl_error($ch);
	}
		curl_close($ch);
	}

そのうち「$authKey="XXXXXXXXXXXXX";」パスワードを入力する必要があります"$senderId="IKOONK";SenderIDを入力する必要があります.移動番号を入力する場合は、国コードを指定する必要があります(例えば、米国は1、インドは91).
構文:
$message = "Hello World";
$mobile = "918112998787";
send_sms($mobile,$message);
?>
2.mandrillでメールを送る
Mandrillは強力なSMTPプロバイダです.開発者は、サードパーティ製SMTP providerを使用して、より良い成果物の提供を得る傾向があります.
次の関数では、「Mandrill.php」を同じフォルダにPHPファイルとして置く必要があります.これにより、TAを使用してメールを送信することができます.
function send_email($to_email,$subject,$message1)
{
	require_once 'Mandrill.php';
	$apikey = 'XXXXXXXXXX'; //specify your api key here
	$mandrill = new Mandrill($apikey);
	   
	$message = new stdClass();
	$message->html = $message1;
	$message->text = $message1;
	$message->subject = $subject;
	$message->from_email = "[email protected]";//Sender Email
	$message->from_name  = "KOONK";//Sender Name
	$message->to = array(array("email" => $to_email));
	$message->track_opens = true;
	   
	$response = $mandrill->messages->send($message);
}

「$apikey='XXXXXXXXXXXX';//specify your api key here」ここでは、あなたのAPIキー(Mandrillアカウントから取得)を指定する必要があります.
構文:
$to = "[email protected]";
$subject = "This is a test email";
$message = "Hello World!";
send_email($to,$subject,$message);
?>
最良の効果を達成するためには、Mandrillのチュートリアルに従ってDNSを構成することが望ましい.
3.ユーザ位置の検出
次の関数を使用して、ユーザーがどの都市であなたのサイトにアクセスしているかを検出できます.
function detect_city($ip) {
        $default = 'UNKNOWN';
        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );
        curl_setopt_array($ch, $curl_opt);
        $content = curl_exec($ch);
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
        curl_close($ch);
        if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {
            $state = $regs[1];
        }
        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default; 
        }
         
}

構文:
$ip = $_SERVER['REMOTE_ADDR'];
$city = detect_city($ip);
echo $city;
?>
4.Webページのソースコードを取得する
次の関数を使用して、任意のWebページのHTMLコードを取得できます.
function display_sourcecode($url)
{
$lines = file($url);
$output = "";
foreach ($lines as $line_num => $line) { 
    // loop thru each line and prepend line numbers
    $output.= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>
"; } }

構文:
$url = "http://blog.koonk.com";
$source = display_sourcecode($url);
echo $source;
?>
5.任意のピクチャの主導色を決定する
function dominant_color($image)
{
$i = imagecreatefromjpeg($image);
for ($x=0;$x<imagesx($i);$x++) {="" for="" ($y="0;$y<imagesy($i);$y++)" $rgb="imagecolorat($i,$x,$y);" $r="($rgb">> 16) & 0xFF;
        $g   = ($rgb >>  & 0xFF;
        $b   = $rgb & 0xFF;
        $rTotal += $r;
        $gTotal += $g;
        $bTotal += $b;
        $total++;
    }
}
$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
}</imagesx($i);$x++)>

6.メールアドレスの検証
Webサイトにフォームを記入すると、ユーザーが誤ったメールアドレスを入力する可能性があります.この関数は、メールアドレスが有効かどうかを検証します.
function is_validemail($email)
{
$check = 0;
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
$check = 1;
}
return $check;
}

構文:
$email = "[email protected]";
$check = is_validemail($email);
echo $check;
//If the output is 1, then email is valid.
?>
7.ユーザの実際のIPを取得する
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;  
}

構文:
$ip = getRealIpAddr();
echo $ip;
?>
8.変換URL:文字列からハイパーリンクへ
フォーラム、ブログ、または通常のフォームの提出を開発している場合は、ユーザーがWebサイトにアクセスすることが多いです.この関数を使用すると、URL文字列が自動的にハイパーリンクに変換されます.
function makeClickableLinks($text) 
{  
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',  
 '<a href="\1">\1</a>', $text);  
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',  
 '\1<a href="http://\2">\2</a>', $text);  
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',  
 '<a href="mailto:\1">\1</a>', $text);  
   
return $text;  

構文:
$text = "This is my first post on http://blog.koonk.com";
$text = makeClickableLinks($text);
echo $text;
?>
9.複数のIPがあなたのサイトにアクセスすることを阻止する
このコードの断片は、特定のIPアドレスがあなたのサイトにアクセスすることを禁止するのに便利です.
if ( !file_exists('blocked_ips.txt') ) {
 $deny_ips = array(
  '127.0.0.1',
  '192.168.1.1',
  '83.76.27.9',
  '192.168.1.163'
 );
} else {
 $deny_ips = file('blocked_ips.txt');
}
// read user ip adress:
$ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : '';
  
// search current IP in $deny_ips array
if ( (array_search($ip, $deny_ips))!== FALSE ) {
 // address is blocked:
 echo 'Your IP adress ('.$ip.') was blocked!';
 exit;
}

10.強制ファイルのダウンロード
新しいウィンドウを開かずに特定のファイルをダウンロードする必要がある場合は、次のコードクリップが役立ちます.
function force_download($file) 
{ 
    $dir      = "../log/exports/"; 
    if ((isset($file))&&(file_exists($dir.$file))) { 
       header("Content-type: application/force-download"); 
       header('Content-Disposition: inline; filename="' . $dir.$file . '"'); 
       header("Content-Transfer-Encoding: Binary"); 
       header("Content-length: ".filesize($dir.$file)); 
       header('Content-Type: application/octet-stream'); 
       header('Content-Disposition: attachment; filename="' . $file . '"'); 
       readfile("$dir$file"); 
    } else { 
       echo "No file selected"; 
    } 
}

構文:
force_download("image.jpg");
?>
11.zipファイルの圧縮
次のPHPクリップを使用してzipファイルを即時圧縮できます.
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;  
    }  
}

構文:
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
create_zip($files, 'myzipfile.zip', true); 
?>
12.ファイルを解凍する
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;
        }
}

構文:
unzip('test.zip','unziped/test');//File would be unzipped in unziped/test folder
?>
13.拡大・縮小
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;   
}

14.mail()を使用してメールを送信
以前はMandrillを使用してメールを送信する方法のPHPコードクリップを提供していましたが、サードパーティのサービスを使用したくない場合は、次のPHPコードクリップを使用することができます.
function send_mail($to,$subject,$body)
{
$headers = "From: KOONK\r
"; $headers .= "Reply-To: [email protected]\r
"; $headers .= "Return-Path: [email protected]\r
"; $headers .= "X-Mailer: PHP5
"; $headers .= 'MIME-Version: 1.0' . "
"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r
"; mail($to,$subject,$body,$headers); }

構文:
$to = "[email protected]";
$subject = "This is a test mail";
$body = "Hello World!";
send_mail($to,$subject,$body);
?>
15.目次リスト
次のPHPコードクリップを使用して、すべてのファイルとフォルダを1つのディレクトリにリストできます.
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.'</a><br>'."
"; } } closedir($handle); } } }

構文:
    list_files("images/");//This will list all files of images folder
?>
16.ユーザ言語の検出
次のPHPコードフラグメントを使用して、ユーザーブラウザで使用されている言語を検出します.
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;
}

17.CSVファイルの表示
function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}

構文:
$csvFile = "test.csv";
$csv = readCSV($csvFile);
$a = csv[0][0];//This will get value of Column 1 & Row 1
?>
18.PHPデータからCSVファイルを作成する
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;
}

19.現在のページURLを取得する
このPHPクリップは、ユーザーがログインした後、前に閲覧したページに直接ジャンプするのに役立ちます.
function current_url()
{
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return validURL;
}

20.フォルダの内容を削除する
function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file)
        {
            Delete(realpath($path) . '/' . $file);
        }
        return rmdir($path);
    }
    else if (is_file($path) === true)
    {
        return unlink($path);
    }
    return false;
}

構文:
$path = "images/";
Delete($path);//This will delete images folder along with its contents.
?>
21.検索およびハイライト文字列のキーワード
function highlighter_text($text, $words)
{
    $split_words = explode( " " , $words );
    foreach($split_words as $word)
    {
        $color = "#4285F4";
        $text = preg_replace("|($word)|Ui" ,
            "<b>$1</b>" , $text );
    }
    return $text;
}

構文:
$string = "I like chocolates and I like apples";
$words = "apple";
echo highlighter_text($string ,$words);
?>
22.URLから画像をダウンロードする
function imagefromURL($image,$rename)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("$rename",'w');
fwrite($fp, $rawdata); 
fclose($fp);
}

構文:
$url = "http://koonk.com/images/logo.png";
$rename = "koonk.png";
imagefromURL($url,$rename);
?>
23.URLが有効かどうかを検出する
function isvalidURL($url)
{
$check = 0;
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
  $check = 1;
}
return $check;
}

構文:
$url = "http://koonk.com";
$check = checkvalidURL($url);
echo $check;//if returns 1 then URL is valid.
?>
24.QRコードの生成
function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0')  
{
     $types = array("URL" =--> "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:");
    if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL")))
    {
        $type = "TXT";
    }
    if (!preg_match('/^'.$types[$type].'/', $data))
    {
        $data = str_replace("\\", "", $types[$type]).$data;
    }
    $ch = curl_init();
    $data = urlencode($data);
    curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

構文:
header("Content-type: image/png");
echo qr_code("http://koonk.com", "URL");
?>
26.2つの地図座標間の距離を計算する
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles','feet','yards','kilometers','meters'); 
}

構文:
$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
    echo $unit.': '.number_format($value,4).'
';
}
?>
27.ファイルのダウンロード速度を制限する
<!--?php
// local file that should be send to the client
$local_file = 'test-file.zip';
// filename that the user gets as default
$download_file = 'your-download-name.zip';
  
// set the download rate limit (=--> 20,5 kb/s)
$download_rate = 20.5; 
if(file_exists($local_file) && is_file($local_file)) {
    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream'); 
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);
  
    // flush content
    flush();    
    // open file stream
    $file = fopen($local_file, "r");    
    while(!feof($file)) {
  
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));    
  
        // flush the content to the browser
        flush();
  
        // sleep one second
        sleep(1);    
    }    
  
    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}
?>

28.テキストを画像に変換する
<?php
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng("images/button.png");
$color = imagecolorallocate($im, 255, 255, 255);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
$py = 9;
$fontSize = 1;
imagestring($im, fontSize, $px, $py, $string, $color);
imagepng($im);
imagedestroy($im);
?>

29.リモート・ファイルのサイズを取得する
function remote_filesize($url, $user = "", $pw = "")
{
    ob_start();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    if(!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  <a href="http://www.php-z.com/" target="_blank" class="relatedlink">Base</a>64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $ok = curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);
    return isset($matches[1]) ? $matches[1] : "unknown";
}

構文:
$file = "http://koonk.com/images/logo.png";
$size = remote_filesize($url);
echo $size;
?>