夢想的天空
一 個 屬 於 我 們 的 世 界
 
 DS WebmailDS Webmail   搜尋搜尋   會員列表會員列表   會員群組會員群組   新進文章   星座物語   網誌   會員註冊會員註冊 
 個人資料個人資料  Calendar月曆   DS WebTV   登入檢查您的私人訊息登入檢查您的私人訊息   登入登入 
 IP 38.107.179.230
我的最愛我的最愛
RSSRSS

[轉貼]PHP 開發者常用的程式片段

 
發表新主題   回覆主題    夢想的天空 首頁 ->多媒體與程式設計 區->程式設計
上一篇主題 :: 下一篇主題  
發表人 內容
paul
DS - 技 術 社 群
DS - 技 術 社 群


註冊時間: 2002-08-15
文章: 33440
來自: 台北‧宜蘭

發表1 發表於: 星期五 十一月 07, 2008 2:13 am    文章主題: [轉貼]PHP 開發者常用的程式片段 引言回覆

From :
http://plog.longwin.com.tw/my-favorite-site/2008/11/06/favorite-php-code-snippet-2008





PHP 在撰寫時常會要判斷 Email、產生亂數密碼、抓取 IP(Proxy 背後的IP)、寄送信件、上傳檔案 及 秀出目錄檔案列表 等等.


這篇文章幫你將上述 等 10個程式片段整理起來, 並分別有寫出 Open Source 的網址, 只要將程式抓下來, 再照範例使用即可.

詳見: 10 code snippets for PHP developers



按右鍵觀看原圖 按右鍵觀看原圖 按右鍵觀看原圖

工作後,最近小弟貼文都沒什麼品質,請各位多多見諒。 >"<~~
回頂端
檢視會員個人資料 發送私人訊息 發送電子郵件 參觀發表人的個人網站
paul
DS - 技 術 社 群
DS - 技 術 社 群


註冊時間: 2002-08-15
文章: 33440
來自: 台北‧宜蘭

發表2 發表於: 星期五 十一月 07, 2008 2:14 am    文章主題: 引言回覆

http://htmlblog.net/10-code-snippets-for-php-developers/




Email address check
Checks for a valid email address using the php-email-address-validation class.
Source and docs: http://code.google.com/p/php-email-address-validation/

include('EmailAddressValidator.php');

$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) {
// Email address is technically valid
}
else {
// Email not valid
}


Random password generator
PHP password generator is a complete, working random passwordgeneration function for PHP. It allows the developer to customize thepassword: set its length and strength. Just include this functionanywhere in your code and then use it.
Source : http://www.webtoolkit.info/php-random-password-generator.html

function generatePassword($length=9, $strength=0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength & 1) {
  $consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength & 2) {
  $vowels .= "AEUY";
}
if ($strength & 4) {
  $consonants .= '23456789';
}
if ($strength & 8) {
  $consonants .= '@#$%';
}

$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
  if ($alt == 1) {
     $password .= $consonants[(rand() % strlen($consonants))];
     $alt = 0;
  } else {
     $password .= $vowels[(rand() % strlen($vowels))];
     $alt = 1;
  }
}
return $password;
}


Get IP address
Returns the real IP address of a visitor, even when connecting via a proxy.
Source : http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

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


XSL transformation
PHP5 version
Source : http://www.tonymarston.net/php-mysql/xsl.html

$xp = new XsltProcessor();

// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
$xsl->load('something.xsl');

// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);

// create a DOM document and load the XML datat
$xml_doc = new DomDocument;
$xml_doc->load('something.xml');

// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
   echo $html;
}
else {
   trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if

PHP4 version

function xml2html($xmldata, $xsl){
/* $xmldata -> your XML */
/* $xsl -> XSLT file */

$arguments = array('/_xml' => $xmldata);
$xsltproc = xslt_create();
xslt_set_encoding($xsltproc, 'ISO-8859-1');
$html = xslt_process($xsltproc, $xmldata, $xsl, NULL, $arguments);

if (empty($html)) {
  die('XSLT processing error: '. xslt_error($xsltproc));
}
xslt_free($xsltproc);
return $html;
}

echo xml2html('myxmml.xml', 'myxsl.xsl');


Force downloading of a file
Forces a user to download a file, for e.g you have an image but youwant the user to download it instead of displaying it in his browser.

header("Content-type: application/octet-stream");

// displays progress bar when downloading (credits to Felix Wink)
header("Content-Length: " . filesize('myImage.jpg'));

// file name of download file
header('Content-Disposition: attachment; filename="myImage.jpg"');

// reads the file on the server
readfile('myImage.jpg');


String encoding to prevent harmful code
Web applications face any number of threats; one of them is cross-site scripting and related injection attacks. The Reform libraryattempts to provide a solid set of functions for encoding output forthe most common context targets in web applications (e.g. HTML, XML,JavaScript, etc)
Source : http://phed.org/reform-encoding-library/

include('Reform.php');
Reform::HtmlEncode('a potentially harmful string');


Sending mail
Using PHPMailer
PHPMailera powerful email transport class with a big features and smallfootprint that is simple to use and integrate into your own software.
Source : http://phpmailer.codeworxtech.com/

include("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = 'noreply@htmlblog.net';
$mail->FromName = 'HTML Blog';
$mail->Host = 'smtp.site.com';
$mail->Mailer = 'smtp';
$mail->Subject = 'My Subject';
$mail->IsHTML(true);
$body = 'Hello<br/>How are you ?';
$textBody = 'Hello, how are you ?';
$mail->Body = $body;
$mail->AltBody = $textBody;
$mail->AddAddress('asvin [@] gmail.com');
if(!$mail->Send())
   echo 'There has been a mail error !';

Using Swift Mailer
Swift Mailer is an alternative to PHPMailer and is a fully OOP library for sending e-mails from PHP websites and applications.
Source : http://swiftmailer.org/

// include classes
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";

$swift =& new Swift(new Swift_Connection_SMTP("smtp.site.com", 25));
$message =& new Swift_Message("My Subject", "Hello<br/>How are you ?", "text/html");
if ($swift->send($message, "asvin [@] gmail.com", "noreply@htmlblog.net")){
echo "Message sent";
}
else{
echo 'There has been a mail error !';
}

//It's polite to do this when you're finished
$swift->disconnect();


Uploading of files
Using class.upload.php from Colin Verot
Source : http://www.verot.net/php_class_upload.htm

$uploadedImage = new Upload($_FILES['uploadImage']);

if ($uploadedImage->uploaded) {
   $uploadedImage->Process('myuploads');
   if ($uploadedImage->processed) {
         echo 'file has been uploaded';
   }
}


List files in directory
List all files in a directory and return an array.
Source : http://www.laughing-buddha.net/jon/php/dirlist/

function dirList ($directory) {
// create an array to hold directory list
$results = array();

// create a handler for the directory
$handler = opendir($directory);

// keep going until all files in directory have been read
while ($file = readdir($handler)) {

  // if $file isn't this directory or its parent,
  // add it to the results array
  if ($file != '.' && $file != '..')
     $results[] = $file;
}

// tidy up: close the handler
closedir($handler);

// done!
return $results;
}


Querying RDBMS with MDB2 (for e.g MySQL)
PEAR MDB2 provides a common API for all supported RDBMS.
Source : http://pear.php.net/package/MDB2

// include MDB2 class
include('MDB2.php');

// connection info
$db =& MDB2::factory('mysql://username:password@host/database');
// set fetch mode
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);

// querying data
$query = 'SELECT id,label FROM myTable';
$result = $db->queryAll($query);

// inserting data
// prepare statement
$statement = $db->prepare('INSERT INTO mytable(id,label) VALUES(?,?)');
// our data
$sqlData = array($id, $label);
// execute
$statement->execute($sqlData);
$statement->free();

// disconnect from db
$db->disconnect();



按右鍵觀看原圖 按右鍵觀看原圖 按右鍵觀看原圖

工作後,最近小弟貼文都沒什麼品質,請各位多多見諒。 >"<~~
回頂端
檢視會員個人資料 發送私人訊息 發送電子郵件 參觀發表人的個人網站
從之前的文章開始顯示:   
發表新主題   回覆主題    夢想的天空 首頁 -> 程式設計 所有的時間均為 台灣時間 (GMT + 8 小時)
1頁(共1頁)



前往:  
無法 在這個版面發表文章
無法 在這個版面回覆文章
無法 在這個版面編輯文章
無法 在這個版面刪除文章
無法 在這個版面進行投票
無法 在這個版面附加檔案
無法 在這個版面下載檔案


新進文章
建議使用瀏覽DS
Powered by phpBB2 © 2001, 2002 phpBB Group
維護管理 DS - 管 理 團 隊    繁體中文由 竹貓星球PBB2中文強化開發小組 製作

主機運作時間: 326 日 1 小時 02 分鐘 | 平均負載值: 0.64, 0.37, 0.19

DS 共花費了 0.1778 秒載入完成 , 有 (PHP: 53% - SQL: 47%) 項資料被查詢 - 讀取資料庫: 17 次 - 壓縮加速 關閉 - 除錯模式 關閉