2016-01-07

php imap_errors 解決方式

解封權限即可
https://www.google.com/settings/security/lesssecureapps

https://accounts.google.com/DisplayUnlockCaptcha

2014-11-11

MYSQL InnoDB 交易範例

PDF READ:http://download.dbworld.com.tw/mag_article/s030901903.pdf

mysql_query("BEGIN");

$sql="SELECT * FROM test_string2 WHERE id=3 FOR UPDATE ";

$rs= mysql_query($sql,$link);

$row=mysql_fetch_array($rs,MYSQL_ASSOC);

mysql_query("COMMIT");

2014-07-25

PHP中imagecopyresampled參數解說

bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
 
$dst_image:新建的图片
 
$src_image:需要载入的图片
 
$dst_x:设定需要载入的图片在新图中的x坐标
 
$dst_y:设定需要载入的图片在新图中的y坐标
 
$src_x:设定载入图片要载入的区域x坐标
 
$src_y:设定载入图片要载入的区域y坐标
 
$dst_w:设定载入的原图的宽度(在此设置缩放)
 
$dst_h:设定载入的原图的高度(在此设置缩放)
 
$src_w:原图要载入的宽度
 
$src_h:原图要载入的高度

2014-03-28

document.form1.submit(); 不能動作

http://www.neo.com.tw/archives/000312.html 

[Javascript] 請勿用保留字來取 HTML 的標籤名 

剛剛查一個 javascript 的 bug ,原因是 document.form1.submit(); 不能動作。出現的錯誤訊息是「物件不支援此屬性或方法」。 

這種 document.form1.submit(); 的 javascript 是再平常不過的指令,怎麼可能不支援呢? 

後來才發現,是美工把 submit 的按鈕取名叫 submit,也就是在 HTML 裡面有一行是: 

<input type="submit" name="submit" value="submit"> 

這樣 document.form1.submit(); 就無法執行了,因為 document.form1.submit 已經變成那個按鈕的物件了,自然 submit 的 method 也無法動作。 

因為自己不會犯這種用保留字來取 HTML Tag name 的錯誤,不過遇到對程式不熟的美工,還是會遇到這種狀況,只能自求多福了。

2014-03-26

PHP獲取路徑和目錄方法總結

<? php
/**
 * PHP獲取路徑或目錄實現
 * @link http://www.phpddt.com
 */

//魔術變量,獲取當前文件的絕對路徑
echo "__FILE__: ========> " . __FILE__ ;
echo '<br/>' ;

//魔術變量,獲取當前腳本的目錄
echo "__DIR__: ========> " . __DIR__ ;
echo '<br/>' ;

//dirname返迴路徑的目錄部分,dirname(__FILE__)相當於__DIR__
echo "dirname(__FILE__): ========> " . dirname ( __FILE__ );
echo '<br/>' ;

//$_SERVER['PHP_SELF']和$_SERVER['SCRIPT_NAME']的結果一般相同,他們都是獲取當前腳本的文件名
//只有當php以cgi方式運行時有區別,但是現在幾乎找不到以cgi方式運行php了
echo '$_SERVER["PHP_SELF"]: ========> ' . $_SERVER [ 'PHP_SELF' ];
echo '<br/>' ;

echo '$_SERVER["SCRIPT_NAME"]: ========> ' . $_SERVER [ 'SCRIPT_NAME' ];
echo '<br/>' ;

//當前執行腳本的絕對路徑。記住,在CLI方式運行php是獲取不到的
echo '$_SERVER["SCRIPT_FILENAME"]: ========> ' . $_SERVER [ 'SCRIPT_FILENAME' ];
echo '<br/>' ;

//當前運行腳本所在的文檔根目錄。在服務器配置文件中定義。
echo '$_SERVER["DOCUMENT_ROOT"]: ========> ' . $_SERVER [ 'DOCUMENT_ROOT' ];
echo '<br>' ;

//getcwd()返回當前工作目錄
echo "getcwd(): ========> " . getcwd ();
echo '<br>' ;

echo '<br>' ;
echo "PHP點點通(www.phpddt.com)整理" ;
轉載請註明地址: http://www.phpddt.com/php/get-path.html尊重他人勞動成果就是尊重自己!

2014-03-18

PHP TELNET PTT

class Telnet {
 var $sock = NULL;

 function telnet($host,$port) {
  $this->sock = fsockopen($host,$port);
  socket_set_timeout($this->sock,2,0);
 }

 function close() {
  if ($this->sock)  fclose($this->sock);
  $this->sock = NULL;
 }

 function write($buffer) {
  $buffer = str_replace(chr(255),chr(255).chr(255),$buffer);
  fwrite($this->sock,$buffer);
 }

 function getc() {
  return fgetc($this->sock); 
 }

 function read_till($what) {
  $buf = '';
  while (1) {
   $IAC = chr(255);

   $DONT = chr(254);
   $DO = chr(253);

   $WONT = chr(252);
   $WILL = chr(251);

   $theNULL = chr(0);

   $c = $this->getc();

   if ($c === false) return $buf;
   if ($c == $theNULL) {
    continue;
   }

   if ($c == "1") {
    continue;
   }

   if ($c != $IAC) {
    $buf .= $c;

    if ($what == (substr($buf,strlen($buf)-strlen($what)))) {
     return $buf;
    }
    else {
     continue;
    }
   }

   $c = $this->getc();

   if ($c == $IAC) {
   $buf .= $c;
   }
   else if (($c == $DO) || ($c == $DONT)) {
    $opt = $this->getc();
    // echo "we wont ".ord($opt)."\n";
    fwrite($this->sock,$IAC.$WONT.$opt);
   }
   elseif (($c == $WILL) || ($c == $WONT)) {
    $opt = $this->getc();
    //echo "we dont ".ord($opt)."\n";
    fwrite($this->sock,$IAC.$DONT.$opt);
   }
   else {
    //echo "where are we? c=".ord($c)."\n";
   }
  }
 }
}

2014-02-08

PHP發送POST請求的三種方式

class Request{

    public static function post($url, $post_data = '', $timeout = 5){

        $ch = curl_init();

        curl_setopt ($ch, CURLOPT_URL, $url);

        curl_setopt ($ch, CURLOPT_POST, 1);

        if($post_data != ''){

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        }

        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_HEADER, false);

        $file_contents = curl_exec($ch);

        curl_close($ch);

        return $file_contents;

    }


    public static function post2($url, $data){

     

        $postdata = http_build_query(

            $data

        );

     

        $opts = array('http' =>

                      array(

                          'method'  => 'POST',

                          'header'  => 'Content-type: application/x-www-form-urlencoded',

                          'content' => $postdata

                      )

        );

     

        $context = stream_context_create($opts);


        $result = file_get_contents($url, false, $context);

        return $result;


    }


    public static function post3($host,$path,$query,$others=''){


        $post="POST $path HTTP/1.1\r\nHost: $host\r\n";

        $post.="Content-type: application/x-www-form-";

        $post.="urlencoded\r\n${others}";

        $post.="User-Agent: Mozilla 4.0\r\nContent-length: ";

        $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";

        $h=fsockopen($host,80);

        fwrite($h,$post);

        for($a=0,$r='';!$a;){

                $b=fread($h,8192);

                $r.=$b;

                $a=(($b=='')?1:0);

            }

        fclose($h);

        return $r;

    }
}

2014-01-28

PHP DCOM 爬文網頁,自動登入

ref:http://www.blueshop.com.tw/board/FUM20041006152627A9N/BRD20130417225944UFH/2.html
<?php
$browser = new COM("InternetExplorer.Application") or die("can not start internet explorer");
$browser->Visible = true;
$browser->Navigate("http://php.a168a.com/andyto202/login.php");
while (($browser->Busy) || ($browser->readystate != 4) ) {
    com_message_pump(1000);
}
     $browser->Document->passForm->username->INNERTEXT = "abcdef";
     $browser->Document->passForm->password->INNERTEXT = "123456";
     com_message_pump(2000);
//隔兩秒才送出才看得到結果
$browser->Document->passForm->Submit->Click;
//在這裡判斷$iecontent;正確進入才存入cookie;
while (($browser->Busy) || ($browser->readystate != 4) ) {
    com_message_pump(2000);
}
$string = "錯誤";
$iecontent = $browser->Document->body->INNERTEXT;
$iecontent  = iconv("big5","UTF-8",$iecontent);
if (strpos($iecontent,"錯誤")) {
//還有很多判斷例如無此帳號....,每個網頁不一樣請自行增加
echo $iecontent;
}
else {
echo "write cookie ok";
$iecookie = $browser->Document->cookie;
echo $iecookie;
}
$browser->Quit();
?>

2014-01-27

PHP CURL不使用文件存取COOKIE

/*-----保存COOKIE-----*/
$url = 'domain'; //url地址
$post = "id=user&pwd=123456"; //POST数据
$ch = curl_init($url); //初始化
curl_setopt($ch,CURLOPT_HEADER,1); //将头文件的信息作为数据流输出
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //返回获取的输出文本流
curl_setopt($ch,CURLOPT_POSTFIELDS,$post); //发送POST数据
$content = curl_exec($ch); //执行curl并赋值给$content
preg_match('/Set-Cookie:(.*);/iU',$content,$str); //正则匹配
$cookie = $str[1]; //获得COOKIE(SESSIONID)
curl_close($ch); //关闭curl

/*-----使用COOKIE-----*/
curl_setopt($ch,CURLOPT_COOKIE,$cookie);

2013-08-31

PHP保留小数位的三种方法

  1. /**
  2. * PHP保留两位小数的几种方法
  3. * @link http://www.phpddt.com
  4. */
  5. $num = 10.4567;
  6.  
  7. //第一种:利用round()对浮点数进行四舍五入
  8. echo round($num,2); //10.46
  9.  
  10. //第二种:利用sprintf格式化字符串
  11. $format_num = sprintf("%.2f",$num);
  12. echo $format_num; //10.46
  13.  
  14. //第三种:利用千位分组来格式化数字的函数number_format()
  15. echo number_format($num, 2); //10.46
  16. //或者如下
  17. echo number_format($num, 2, '.', ''); //10/46

 关于number_format()函数扩展阅读:http://www.w3school.com.cn/php/func_string_number_format.asp

2013-04-23

PHP 時區 timezone 設定


date_default_timezone_set("Asia/Taipei")


////////////////////////////
if (function_exists ( 'date_default_timezone_set' )){
date_default_timezone_set('Asia/Taipei'); //PHP5設定時區, 在PHP4無法使用
} else {
putenv("TZ=Asia/Taipei"); //PHP4設定時區的用法
}

2012-08-09

php中++i 与 i++ 的區別

1、++i的用法(以a=++i ,i=2為例)先將i值加1 (也就是i=i+1 ),然後賦給變量a ​​(也就是a=i ),則最終a值等於3 , i值等於3 。所以a=++i相當於i=i+1 ,a=i 
2、i++的用法(以a=i++ ,i=2為例)先將i值賦給變量a ​​(也就是a=i ),然後i值加1 (也就是i=i+1 ),則最終a值等於2 ,i值等於3 。所以a=i++相當於a=i , i=i+1 
3、++i與i++ a=++i相當於i++ , a=i a=i++相當於a=i , i++
 4、++i與i++單獨使用時,相當於i=i+1如果賦給一個新變量,則++i先將i值加1 ,而i++先將i賦給新變量。 

2012-01-05

超級實用的7個PHP代碼

1、超級簡單的頁面緩存如果你的工程項目不是基於CMS系統或框架,打造一個簡單的緩存系統將會非常實在。下面的代碼很簡單,但是對小網站而言能切切實實解決問題。
複製代碼代碼如下:

<?php 
// define the path and name of cached file 
$cachefile = 'cached-files/'.date('Md-Y').'.php'; 
// define how long we want to keep the file in seconds . I set mine to 5 hours. 
$cachetime = 18000; 
// Check if the cached file is still fresh. If it is, serve it up and exit. 
if (file_exists($cachefile) && time() - $cachetime < filemtime ($cachefile)) { 
include($cachefile); 
exit; 
} 
// if there is either no file OR the file to too old, render the page and capture the HTML. 
ob_start(); 
?> 
<html> 
output all your html here. 
</html> 
<?php 
// We're done! Save the cached content to a file 
$fp = fopen($cachefile, 'w'); 
fwrite($fp, ob_get_contents()); 
fclose($ fp); 
// finally send browser output 
ob_end_flush(); 
?>

點擊這裡查看詳細情況:http://wesbos.com/simple-php-page-caching-technique/ 2、在PHP中計算距離這是 ​​一個非常有用的距離計算函數,利用緯度和經度計算從A地點到B地點的距離。該函數可以返回英里,公里,海里三種單位類型的距離。



複製代碼代碼如下:

function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos (deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } }
















使用方法: 
複製代碼代碼如下:

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers"; 

點擊這裡查看詳細情況:http://www.phpsnippets.info/calculate-distances-in-php 3、將秒數轉換為時間(年、月、日、小時…)這個有用的函數能將秒數表示的事件轉換為年、月、日、小時等時間格式。



複製代碼代碼如下:

function Sec2Time($time){ 
if(is_numeric($time)){ 
$value = array( 
"years" => 0, "days" => 0, "hours" => 0, 
"minutes" => 0, " seconds" => 0, 
); 
if($time >= 31556926){ 
$value["years"] = floor($time/31556926); 
$time = ($time%31556926); 
} 
if($time >= 86400){ 
$value["days"] = floor($time/86400); 
$time = ($time%86400); 
} 
if($time >= 3600){ 
$value["hours"] = floor($ time/3600); 
$time = ($time%3600); 
} 
if($time >= 60){ 
$value["minutes"] = floor($time/60); 
$time = ($time%60) ; 
} 
$value["seconds"] = floor($time); 
return (array) $value; 
}else{ 
return (bool) FALSE; 
} 
}

點擊這裡查看詳細情況:http://ckorp.net/sec2time.php 4、強制下載文件一些諸如mp3類型的文件,通常會在客戶端瀏覽器中直接被播放或使用。如果你希望它們強制被下載,也沒問題。可以使用以下代碼:


複製代碼代碼如下:

function downloadFile($file){ 
$file_name = $file; 
$mime = 'application/force-download'; 
header('Pragma: public'); // required 
header('Expires: 0'); // no cache 
header ('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Cache-Control: private',false); 
header('Content-Type: '.$mime); 
header('Content-Disposition: attachment; filename="'.basename($file_name).'"'); 
header('Content-Transfer-Encoding: binary'); 
header('Connection: close'); 
readfile($ file_name); // push it out 
exit(); 
}

點擊這裡查看詳細情況:Credit: Alessio Delmonti 5、使用Google API獲取當前天氣信息想知道今天的天氣?這段代碼會告訴你,只需3行代碼。你只需要把其中的ADDRESS換成你期望的城市。



複製代碼代碼如下:

$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS'); 
$information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition"); 
echo $information [0]->attributes();

點擊這裡查看詳細情況:http://ortanotes.tumblr.com/post/200469319/current-weather-in-3-lines-of-php 6、獲得某個地址的經緯度隨著Google Maps API的普及,開發人員常常需要獲得某一特定地點的經度和緯度。這個非常有用的函數以某一地址作為參數,返回一個數組,包含經度和緯度數據。


複製代碼代碼如下:

function getLatLong($address){ 
if (!is_string($address))die("All Addresses must be passed as a string"); 
$_url = sprintf('http://maps.google.com/maps?output= js&q=%s',rawurlencode($address)); 
$_result = false; 
if($_result = file_get_contents($_url)) { 
if(strpos($_result,'errortips') > 1 || strpos($_result, 'Did you mean:') !== false) return false; 
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\ d+\.\d+)}!U', $_result, $_match); 
$_coords['lat'] = $_match[1]; 
$_coords['long'] = $_match[2]; 
} 
return $_coords ; 
}

點擊這裡查看詳細情況:http://snipplr.com/view.php?codeview&id=47806 7、使用PHP和Google獲取域名的favicon圖標有些網站或Web應用程序需要使用來自其他網站的favicon圖標。利用Google和PHP很容易就能搞定,不過前提是Google不會連接被重置哦!



複製代碼代碼如下:

function get_favicon($url){ 
$url = str_replace("http://",'',$url); 
return "http://www.google.com/s2/favicons?domain=".$url; 
}