PHP編程學習筆記

來源:互聯網
上載者:User

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);
//PDF
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作為反向 Proxy伺服器,後台多台Apache+mod_php5。
nginx處理靜態檔案,及對php並發請求對後台多台app server的負載平衡;

2) nginx作為反向 Proxy器,後台多台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,裡面的中文依舊是那個中文。

 代碼如下 複製代碼
//代碼
foreach ( $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.111cn.net . 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.