顯示具有 php 標籤的文章。 顯示所有文章
顯示具有 php 標籤的文章。 顯示所有文章

2012年7月23日 星期一

PHP 使用 TCPDF 顯示中文的關鍵


$pdf = new TCPDF(PDF_PAFE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set font (PHP TCPDF 顯示中文字型)
$pdf->SetFont('cid0jp', '', 18); // 可以顯示中文(繁、簡)、日文、韓文。
//$pdf->SetFont('msungstdlight', '', 18, '', true); // 繁中, 但是效果不好,字會偏移
//$pdf->SetFont('stsongstdlight', '', 20); // 可以顯示中文, 但是效果不好,字會偏移
//$pdf->SetFont('dejavusans', '', 14, '', true); // 預設 utf8

2012年4月4日 星期三

Ajax Poll 投票範例

這是一個 AJAX Poll 投票的範例

1. HTML Code(ajax_poll.htm):

<html>
  <head>
    <meta charset="utf-8" />
    <title>AJAX Poll</title>
    <script src="ajax_poll.js"></script> 
  </head>
  <body>
    <h3><a href="http://www.w3schools.com/php/php_ajax_poll.asp">AJAX Poll</a></h3>
    <div id="poll">
      <h2>Do you like PHP and AJAX so far?</h2>
      <form>
        Yes: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br />
        No: <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
      </form>
    </div>
    <a href="index.htm">Home</a>
  </body>
</html>



2. Javascript Code(ajax_poll.js):

var xmlHttp;

function getVote(int) {
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null) {
    alert("Browser does not support HTTP Request");
    return;
  }
  var url="ajax_poll.php";
  url=url+"?vote="+int;
  url=url+"&sid="+Math.random();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function stateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
    document.getElementById("poll").innerHTML=xmlHttp.responseText;
  }
}

function GetXmlHttpObject() {
  var objXMLHttp=null;
  if (window.XMLHttpRequest) {
    objXMLHttp=new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
}



3. PHP Code(ajax_poll.php):

<?php

$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "ajax_poll.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) $yes = $yes + 1;
if ($vote == 1) $no = $no + 1;

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);

?>

<h2>Result:</h2>
<table>
  <tr>
    <td>Yes:</td>
    <td>
      <img src="images\\poll.gif" width='<?php echo(100*round($yes/($no+$yes),2)); ?>' height='20'>
      <?php echo(100*round($yes/($no+$yes),2)); ?>%
    </td>
  </tr>
  <tr>
    <td>No:</td>
    <td>
      <img src="images\\poll.gif" width='<?php echo(100*round($no/($no+$yes),2)); ?>' height='20'>
      <?php echo(100*round($no/($no+$yes),2)); ?>%
    </td>
  </tr>
</table>



4. TXT Code(ajax_poll.txt):

0||0



5. 下載 poll.gif 檔案, 放到 images 資料夾下.


6. 寫好後, 執行 ajax_poll.htm, 完成!

2012年4月3日 星期二

Ajax Login 登入範例

這是一個 AJAX Login 登入的範例

1. HTML Code(user_login.htm):

<html>
  <head>
    <meta charset="utf-8"/>
    <title>AJAX Login</title>
    <script src="user_login.js"></script>
  </head>
  <body>
    <h3><a href="http://www.aleixcortadellas.com/main/2009/03/01/ajax-post/">AJAX Login</a></h3>
    <form name="myform" id="myform">
      <div id="msg" style="color:red;display:none;"></div>
      Account: <input type="text" name="account"><br/>
      Password: <input type="password" name="pwd"><br/>
      <span id="btn"><input type="button" name="sb" id="sb" value="Login"></span><br/>
      <span style="color:blue;">(tip: guest / guest)</span><br/>
      <a href="index.htm">Home</a>
    </form>
  </body>
</html>



2. Javascript Code(user_login.js):

window.onload = initPage;
function initPage() {
  // 取得「送出」按鈕的參考
  var subBtn = document.getElementById("sb");
  // 為按鈕加入事件處理器
  subBtn.onclick = function () {
    MakeRequest(); // 建立請求的函式
  }
}

function createRequest() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  } else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
  }
}

var request = createRequest(); // 建立請求物件

function MakeRequest() {
  form = document.getElementById("myform");
  if (request != null) {
    // 取得輸入的文字
    var sPost = "";
    for(i=0;i<form.elements.length;i++) {
      inp = form.elements[i];
      switch(inp.type) {
        case "text":
        case "textarea":
        case "select-one":
        case "radio":
        case "password":
          if (inp.name && inp.value) {
            sPost+="&"+escape(inp.name)+"="+escape(inp.value);
          }
          break;
        default:
          break;
      }
    }

    var url = "user_login.php?1=1";

    // 利用 POST 方法、請求目的地 url、true 為非同步
    request.open("POST", url, true);

    // 回應處理函式 displayResult
    request.onreadystatechange = displayResult;
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.send(sPost); // 送出請求
  }
}

function displayResult() {
  if (request.readyState == 4) { // 確認 readState
    if (request.status == 200) { // 確認 status
      var disp = document.getElementById("msg"); // 取得顯示位置
      disp.innerHTML = request.responseText;
      if (request.responseText=="Succcess") {
        var btnInput = document.getElementById("btn"); // 取得按鈕位置
        btnInput.style.display="none";
      }
      disp.style.display="block";
    }
  }
}



3. PHP Code(user_login.php):

<?php

$aRow =&$_POST;
$aStr = array();

if (!isset($aRow['account'])) $aRow['account']="";
if (!isset($aRow['pwd'])) $aRow['pwd']="";

if (!$aRow['account']) $aStr[] = "Enter account";
if (!$aRow['pwd']) $aStr[] = "Enter password";

if (!count($aStr)) {
  if ($aRow['account']=="guest" and $aRow['pwd']=="guest") {
    $aStr[] = "Succcess";
  } else {
    $aStr[] = "Account and password is not correct";
  }
}
echo implode("<br>",$aStr);

?>



4. 寫好後, 執行 user_login.htm , 完成!

Ajax Suggest 建議的範例

Ajax Suggest 建議的範例:

1. HTML Code(clienthint.htm):
<html>
  <head>
    <script src="clienthint.js"></script>
  </head>
  <body>
    <h3><a href="http://www.w3school.com.cn/php/php_ajax_suggest.asp">Ajax Suggest</a></h3>
    <form>
      First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
    </form>
    <p>Suggestions: <span id="txtHint" /></p>
    <a href="index.htm">Home</a>
  </body>
</html>


2. Javascript Code(clienthint.js):
var xmlHttp;
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  xmlHttp=GetXmlHttpObject()
  if (xmlHttp==null) {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url="clienthint.php";
  url=url+"?q="+str;
  url=url+"&sid="+Math.random();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function stateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
    document.getElementById("txtHint").innerHTML=xmlHttp.responseText
  }
}

function GetXmlHttpObject() {
  var xmlHttp=null;
  try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}


3. PHP Code(clienthint.php):
<?php

// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Eric";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0) {
  $hint="";
  for($i=0; $i<count($a); $i++) {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) {
      if ($hint=="") {
        $hint=$a[$i];
      } else {
        $hint=$hint." , ".$a[$i];
      }
    }
  }
}

//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>


4. 寫好後, 執行 clienthint.htm , 完成!

2011年5月12日 星期四

PHP印出陣列中被包在StdClass內的Value

 假設今天收到的資料的是
Array (
   [0] => stdClass Object (
   [name] => "AAA"
   [code] =>123
   )
[1] => stdClass Object (
   [name] => "BBB"
   [code] =>456
  )
[2] => stdClass Object (
   [name] => "CCC"
   [code] =>789
  )
)

要印出資料只要設定一個變數指到那個Array Object 就好了…
//先把資料存到某個變數 , 假設上面那筆資料是 $a
$b = $a;
//接著逐一印出的話
foreach ($b as $value) {
    $name = $value->name;
    $code = $value->code;
    echo "$name , $code \n";
}

出處: http://note.ajneok.org/programing_note/php/php-print-array-value-in-stdclass/comment-page-1/#comment-1231

2010年6月25日 星期五

Notepad++ Function List

目前撰寫PHP程式,都用 Notepad++ 來撰寫, 其中, 最常使用的 Plugin 為 function list,
這個 plugin 都是到 http://sourceforge.net/projects/npp-plugins/files/ 這個網站去下載,
要下載最新版本, 因為目前都是使用 UTF-8 的格式撰寫程式, 所以都是下載 unicode
版本的!

2010年1月8日 星期五

php 中的訊息顯示

這個我覺得不錯,可以試試看

function popmsg($str='') {
echo "<script>window.alert(\"".$str."\");</script>";
}
$message=13242143;
popmsg($message);

PHP实现文件安全下载

PHP实现文件安全下载
你一定会笑我"下载文件"如此简单都值得说?当然并不是想象那么简单。例如你希望客户要填完一份表格,才可以下载某一文件,你第一个想法一定是用 "Redirect"的方法,先检查表格是否已经填写完毕和完整,然后就将网址指到该文件,这样客户才能下载,但如果你想做一个关于"网上购物"的电子商务网站,考虑安全问题,你不想用户直接复制网址下载该文件,笔者建议你使用PHP直接读取该实际文件然后下载的方法去做。程序如下:

$file_name = "info_check.exe";
$file_dir = "/public/www/download/";
if (!file_exists($file_dir . $file_name)) { //检查文件是否存在
echo "文件找不到";
exit;
} else {
$file = fopen($file_dir . $file_name,"r"); // 打开文件
// 输入文件标签
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . $file_name);
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;}

而如果文件路径是"http" 或者 "ftp" 网址的话,则源代码会有少许改变,程序如下:

$file_name = "info_check.exe";
$file_dir = "http://www.easycn.net/";
$file = @ fopen($file_dir . $file_name,"r");
if (!$file) {
echo "文件找不到";
} else {
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=" . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}

PHP 匯出 Excel 的方法

How to generate Excel files ??

http://pear.php.net/package/Spreadsheet_Excel_Writer/download/All

http://pear.php.net/package/OLE/download

http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro.php

http://twpug.net/modules/newbb/viewtopic.php?post_id=6230

http://www.wretch.cc/blog/godisverygoo

PHP 在 FreeBSD 上的安裝步驟

PHP 在 FreeBSD 上安裝的步驟: (使用 Configure 方式安裝) :

1. Download php-5.2.6.tar.gz

2. tar xzvf php-5.2.6.tar.gz

3. cd php-5.2.6

4. /bin/sh ../php.configure.sh (php.configure.sh 要先將configure的參數先設定好)

5. make install

6. cp php.ini-dist /usr/local/php/lib/php.ini

7. 設定 /usr/local/php/lib/php.ini

(1) include_path=".:/usr/local/php"

(2) register_globals=off

(3) short_open_tag = On

8. 設定 httpd.conf

(1) LoadModule php5_module libexec/libphp5.so

(2) AddType application/x-httpd-php .php

(3) DirectoryIndex 後面加上 index.php

9. 重新啟動 Apache Server

/usr/local/apache2/bin/apachectl restart

(PS: DSO版(*.so)檔案, 放在 /usr/local/apache2/modules

10. 測試 php

/usr/local/php/bin/php -i

如果有出現php的參數設定,就表示成功了~~



以下列出為參考其他人使用的PHP configure 的參數設定: (php.configure.sh)

#!/bin/bash
./configure --prefix=/usr/local/php --mandir=/usr/local/php/man --infodir=/usr/local/php/info --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql --with-curl=/usr/lib --with-zlib-dir=/usr/lib --with-freetype-dir=/usr/lib --enable-zend-multibyte --enable-ftp --enable-mbstring --with-iconv --enable-gd-native-ttf --with-openssl --with-mysql --with-zlib --with-gd --enable-mbstring --enable-libxml --with-regex=php



(PS:apxs 為 Apache configure 時要有下 --enable-module=so 的參數)

其他參數如:

--enable-fastcgi

--enable-mssql

--enable-pgsql

--enable-sqlite-utf8

PHP: Curl POST a file

I'm trying to post a
word doc file to a remote server using cURL. I've tried posting ot to a local folder (code attached) but I don't get the file at the recieved page. All the FILES data is there but what use is a local path to a remote server?

Array
(
[file] => Array
(
[name] => php1431.tmp
[type] => application/octet-stream
[tmp_name] => C:\WINDOWS\TEMP\php1432.tmp
[error] => 0
[size] => 26112
)

)

"@$fullfilepath"
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);

//echo $response;
}

?>


<form enctype="multipart/form-data" action="<?=$_SERVER['SCRIPT_NAME']?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="userfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>