文章主要是一個站長在學習php過程中一些用到的函數與方法及對各種方法的理解與簡單的實例,下面全部放出來希望對你學習php有幫助.
PHP使用header函數設置HTTP頭的示例方法,代碼如下:
- //定義編碼
- header( Content-Type:text/html;charset=utf-8 );
- //Atom
- header(Content-type: application/atom+xml);
- //CSS
- header(Content-type: text/css);
- //Javascript
- header(Content-type: text/javascript);
- //JPEG Image
- header(Content-type: image/jpeg);
- //JSON
- header(Content-type: application/json);
- header(Content-type: application/pdf);
- //RSS
- header(Content-Type: application/rss+xml; charset=ISO-8859-1);
- //Text (Plain)
- header(Content-type: text/plain);
- //XML
- header(Content-type: text/xml);
- // ok
- header(HTTP/1.1 200 OK);
- //設置一個404頭:
- header(HTTP/1.1 404 Not Found);
- //設置地址被永久的重定向
- header(HTTP/1.1 301 Moved Permanently);
- //轉到一個新地址
- header(Location: http://www.example.org/);
- //文件延遲轉向:
- header(Refresh: 10; url=http://www.example.org/);
- print You will be redirected in 10 seconds;
- //當然,也可以使用html語法實現
- // <meta http-equiv="refresh" content="10;http://www.example.org/ />
- // override X-Powered-By: PHP:
- header(X-Powered-By: PHP/4.4.0);
- header(X-Powered-By: Brain/0.6b);
- //文檔語言
- header(Content-language: en);
- //告訴瀏覽器最后一次修改時間
- $time = time() - 60; // or filemtime($fn), etc
- header(Last-Modified: .gmdate(D, d M Y H:i:s, $time). GMT);
- //告訴瀏覽器文檔內容沒有發生改變
- header(HTTP/1.1 304 Not Modified);
- //設置內容長度
- header(Content-Length: 1234);
- //設置為一個下載類型
- header(Content-Type: application/octet-stream);
- header(Content-Disposition: attachment; filename="example.zip");
- header(Content-Transfer-Encoding: binary);
- // load the file to send:
- readfile(example.zip);
- // 對當前文檔禁用緩存
- header(Cache-Control: no-cache, no-store, max-age=0, must-revalidate);
- header(Expires: Mon, 26 Jul 1997 05:00:00 GMT); // Date in the past
- header(Pragma: no-cache);
- //設置內容類型:
- header(Content-Type: text/html; charset=iso-8859-1);
- header(Content-Type: text/html; charset=utf-8);
- header(Content-Type: text/plain); //純文本格式
- header(Content-Type: image/jpeg); //JPG***
- header(Content-Type: application/zip); // ZIP文件
- header(Content-Type: application/pdf); // PDF文件
- header(Content-Type: audio/mpeg); // 音頻文件
- header(Content-Type: application/x-shockw**e-flash); //Flash動畫
- //顯示登陸對話框
- header(HTTP/1.1 401 Unauthorized);
- header(WWW-Authenticate: Basic realm="Top Secret");
- print Text that will be displayed if the user hits cancel or ;
- print enters wrong login data;
php中static靜態變量的使用方法詳解
php中的變量作用范圍的另一個重要特性就是靜態變量(static 變量),靜態變量僅在局部函數域中存在且只被初始化一次,當程序執行離開此作用域時,其值不會消失,會使用上次執行的結果.
編程實例,代碼如下:
- function test()
- {
- static $aa = 0;
- return $aa++;
- }
- $aa = "1000";
- echo $aa;
- echo test();
- echo test();
- echo $aa;
- //本函數每調用test()都會輸出 $aa的值并加一。
- //上文代碼運行輸出:
- //1000
- //0
- //1
- //1000
靜態變量也提供了一種處理遞歸函數的方法,遞歸函數是一種自己調用自己的方法,寫遞歸函數時要小心,因為可能會無窮遞歸下去,沒有出口.務必確保,有方法來中止遞歸.
一維數組按照元素或者鍵值分組變為二維數組
有時候查詢數據庫記錄后會對數據庫查詢結果進行分組,即將一維數組變為二維數組,方便調用使用(通常是json),代碼如下:
- $arr = array(
- '0'=>array(
- 'firmware'=>'f1',
- 'version'=>'1',
- ),
- '1'=>array(
- 'firmware'=>'f1',
- 'version'=>'2',
- ),
- '2'=>array(
- 'firmware'=>'f1',
- 'version'=>'3',
- ),
- '3'=>array(
- 'firmware'=>'f2',
- 'version'=>'1',
- ),
- '4'=>array(
- 'firmware'=>'f2',
- 'version'=>'2',
- ),
- );
- $new_arr = array();
- foreach ($arr as $row ){
- $new_arr[$row['firmware']][] = $row['version'];
- }
- var_dump($new_arr);
- /*轉換后
- Array
- (
- [f1] => Array
- (
- [0] => 1
- [1] => 2
- [2] => 3
- )
- [f2] => Array
- (
- [0] => 1
- [1] => 2
- )
- )*/
PHP的靜態綁定和動態綁定(private/public)
子類Foo的對象調用了test()方法,test()方法調用了$this->testPrivate();這個$this此時應該是子類的引用,按理說應該調用子類的testPrivate()方法,實際上卻調用了父類的testPrivate()方法.代碼如下:
- class Bar
- {
- public function test() {
- $this->testPrivate();
- $this->testPublic();
- }
- public function testPublic() {
- echo "Bar::testPublicn";
- }
- private function testPrivate() {
- echo "Bar::testPrivaten";
- }
- }
- class Foo extends Bar
- {
- public function testPublic() {
- echo "Foo::testPublicn";
- }
- private function testPrivate() {
- echo "Foo::testPrivaten";
- }
- }
- $myFoo = new Foo();
- $myFoo->test();
- // 運行結果
- // Bar->testPrivate
- // Foo->testPublic
這是PHP的動態綁定和靜態綁定的一種情況.
public是動態綁定,在編譯期不綁定,所以在運行期調用父類的test()方法的時候,會解析為子類的public方法.
而private是私有的,不會繼承到子類,在編譯期就綁定了,是一種“靜態”的綁定(類似5.3后的self).
與這個相關的是LSB,靜態延遲綁定,PHP5.3因為有了這個特性之后,使PHP的OOP得到加強
public:可以被繼承,也可以被外部調用.
private:不可以被繼承,也不可以被外部調用.
protected:可以被繼承,但不能被外部調用.
PHP三種運行方式mod_php5/cgi/fast-cgi
a.通過HTTPServer內置的模塊來實現,例如Apache的mod_php5,類似的Apache內置的mod_perl可以對perl支持;
b.通過CGI來實現,這個就好比之前perl的CGI,該種方式的缺點是性能差,因為每次服務器遇到這些腳本都需要重新啟動腳本解析器來執行腳本然后將結果返回給服務器,另一方面就是不太安全,該方面幾乎很少使用了.
c.最新出現一種叫做FastCGI.所謂FastCGI就是對CGI的改進,它一般采用C/S結構,一般腳本處理器會啟動一個或者多個daemon進程,每次HTTPServer遇到腳本的時候,直接交付給FastCGI的進程來執行,然后將得到的結果(通常為html)返回給瀏覽器.
該種方法的問題存在一個小問題是當遇到大流量的頻繁請求的話,腳本處理器的daemon進程可能會超負荷從而變得很慢,甚至發生內存泄漏;
但是比較起Apache的內置模塊的方式的優點是由于Server和腳本解析器完全分開各負其責,因此服務器不再臃腫,可以專心地進行靜態文件響 應或者將動態腳本解析器的結果返回給用戶客戶端,所以比較起Apache的內置模塊方式,有時候性能要提高很多,有人測試可能會達到 Apache+mod_php的5~10倍.
三種常用模式:
Apache+mod_php5;lightppd+spawn-fcgi;nginx+PHP-FPM
我們可以使用到生產環境中的:
0) 如果不是server cluster的話:
可以使用以上任一種,不過有各種測試表明nginx+PHP-FPM性能優越,但是Apache+mod_php5很經典模塊多,比如對.htaccess等的支持.
如果構建server cluster的話:
1) nginx作為反向代理服務器,后臺多臺Apache+mod_php5.
nginx處理靜態文件,及對php并發請求對后臺多臺app server的負載均衡;
2) nginx作為反向代理器,后臺多臺PHP-FPM
nginx處理靜態文件及將php并發請求發送到后臺php-fpm來解析;
三種變量命名規則(匈牙利法,小駝峰法,大駝峰法)
1. 匈牙利命名:
•開頭字母用變量類型的縮寫,其余部分用變量的英文或英文的縮寫,要求單詞第一個字母大寫.
•For example: long lsum = 0;"l"是類型的縮寫;
2. 小駝峰式:(little camel-case)
•第一個單詞首字母小寫,后面其他單詞首字母大寫.
•For example: string firstName = string.Empty;
3. 大駝峰式:(big camel-case)
•每個單詞的第一個字母都大寫;
•For example:string FirstName = string.Empty;
解決 Json 中文轉碼問題,代碼如下:
- //代碼
- $data = array(
- 'status'=>'1',
- 'method'=>'登陸',
- 'message'=>'成功',
- );
- echo json_encode($data);
- //顯示
- {"status":"1","method":"u767bu9646","message":"u6210u529f"}
json_encode 只能接受utf-8格式的數據,最終的json中中文部分被替換為unicode編碼,我們要解決的就是將對象轉換為json并保證對象內部的中文在json中仍然是以正常的中文出現.
先將類中的中文字段進行url編碼(urlencode),然后再對對象進行json編碼(jsonencode),最后url解碼(urldecode)json,即最終的json,里面的中文依舊是那個中文,代碼如下:
- //代碼
- ( $data as $key => $value ) {
- $newData[$key] = urlencode ( $value );
- }
- echo urldecode(json_encode($newData));
- //顯示
- {"status":"1","method":"登陸","message":"成功"}
Ajax跨域請求CORS錯誤:
編寫Json api供其他站點查詢調用的時候有時候使用ajax方式獲取,此時,可能ACAO的設置,那么將發生CROS錯誤.
報錯:XMLHttpRequest cannot load http://www.49028c.com . No 'Access-Control-Allow-Origin' header is present on the requested resource.
解決辦法:
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Origin: ccdd.com');
- codeigniter指定地址實現HTTPS訪問管理
- //啟動hooks
- //app/config/config.php
- $config['enable_hooks'] = TRUE;
- //hooks配置
- ///app/config/hooks.php
- $hook['post_controller_constructor'][] = array(
- 'function' => 'check_ssl',
- 'filename' => 'ssl.php',
- 'filepath' => 'hooks',
- );
- //插件編寫
- //app/hooks/ssl.php
- function check_ssl(){
- $CI =& get_instance();
- $class = $CI->router->fetch_class();
- $method = $CI->router->fetch_method();
- $ssl = $CI->config->item('ssl_class_method');
- $partial = $CI->config->item('no_ssl_class_method');
- if(in_array($class.'/'.$method,$ssl)){
- //force_ssl();
- $CI =&get_instance();
- $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
- if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
- }
- else if(in_array($class.'/'.$method,$partial))
- {
- return;
- }
- else{
- //unforce_ssl
- $CI =&get_instance();
- $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
- if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
- }
- }
- //config 配置需要使用https的 class method
- //app/config/config.php
- $config['ssl_class_method'] = array(
- 'U_class/A_method',
- 'V_class/B_method',
- 'W_class/C_method',
- 'X_class/D_method',
- ); //強制使用ssl
- $config['no_ssl_class_method'] = array();
- //強制不使用ssl
新聞熱點
疑難解答