Archive for June, 2009

PHP學習筆記 – 寄送Mail

Saturday, June 13th, 2009

MyMailer.php

其中用到Base64 Encode的方式,信件的寄件者和標題中文才不會變亂碼

<?php
class MyMailer {
  const headerFormat = '=?utf-8?b?%s?=';

  public static function mail($from, $to, $subject, $body) {
    // convert to base64 string
    $from = sprintf(self::headerFormat, base64_encode($from));
    $subject = sprintf(self::headerFormat, base64_encode($subject));

    // To send HTML mail, you can set the Content-type header.
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "From: ". $from . "\r\n"; // 寄件者
    //$headers .= "Cc: xxxgmail.com\r\n"; // 副本
    //$headers .= "Bcc: yyy@gmail.com\r\n"; // 密件副本

    return mail($to, $subject, $body, $headers);
  }
}
?>

Example

";
$to = "Z先生 ";
$subject = "中文標題測試! 許功蓋...測試一下~~~ !@#$%^&*()_+=-0987654321|\:\";'{}[]<>?,./-*/+   123";
$body = <<< HTML_BODY





許功蓋...測試!!
!@#$%^&*()_+=-0987654321|\:";'{}[]<>?,./-*/+ 123 abcdeffghijklmnopqrstuvwxyz HTML_BODY; $result = MyMailer::mail($from, $to, $subject, $body); if( $result ) echo "寄送成功!"; else echo "寄發失敗!"; ?>

Gmail收到信顯示的結果

PHP學習筆記 – Here Document(即席文件)

Saturday, June 13th, 2009

即席文件是用來寫大量文字時很好用的東西,例如產生一個HTML文件
以下code是將產生的即席文件字串傳給變數&body,然後將$body輸出

$body = <<< HTML_BODY
<html>
<head>
<title>Here Document測試!</title>
</head>
<body>
<div style="color:red;"><b><i>許功蓋...測試!!</i></b></div>
!@#$%^&amp;*()_+=-0987654321|\:";'{}[]<>?,./-*/+	 123
abcdeffghijklmnopqrstuvwxyz
</body>
</html>
HTML_BODY;

echo $body;

PHP學習筆記 – DB連線操作

Saturday, June 13th, 2009

由於我的PHP程式要放在虛擬主機,沒有裝PEAR。所以以下是用PHP內建的mysqli的方法連線DB。

// host, username, password, dbname
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_dbname');
if( !$conn ) {
  die("Can't connect: " . mysqli_connect_error());
}

$sql = "select id, status from t_account limit 5";
$q = $conn->query($sql);
while($r = mysqli_fetch_row($q)) { // 將query出來的資料以Array的方式傳回
  echo var_dump($r) . '<br>';
}
$conn->close(); // 關閉連線