ホームページ  >  記事  >  php教程  >  PHP编程学习笔记

PHP编程学习笔记

WBOY
WBOYオリジナル
2016-06-06 20:11:491422ブラウズ

PHP使用header函数设置HTTP头的示例方法 //定义编码header( Content-Type:text/html;charset=utf-8 );//Atomheader( Content-type: application/atom+xml );//CSSheader( Content-type: text/css );//Javascriptheader( Content-type: text/javascript );//J

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语法实现
// 
// 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::testPublic\n";
    }
    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}
class Foo extends Bar 
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }
    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}
$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":"\u767b\u9646","message":"\u6210\u529f"}

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://aabb.com/api/user. 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

PHP二维数组排序函数

PHP一维数组的排序可以用sort(),asort(),arsort()等函数,但是PHP二维数组的排序需要自定义。
以下函数是对一个给定的二维数组按照指定的键值进行排序,先看函数定义:

function array_sort($arr,$keys,$type='asc'){ 
    $keysvalue = $new_array = array();
    foreach ($arr as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $arr[$k];
    }
    return $new_array; 
} 

它可以对二维数组按照指定的键值进行排序,也可以指定升序或降序排序法(默认为升序),用法示例:

$array = array(
    array('name'=>'手机','brand'=>'诺基亚','price'=>1050),
    array('name'=>'笔记本电脑','brand'=>'lenovo','price'=>4300),
    array('name'=>'剃须刀','brand'=>'飞利浦','price'=>3100),
    array('name'=>'跑步机','brand'=>'三和松石','price'=>4900),
    array('name'=>'手表','brand'=>'卡西欧','price'=>960),
    array('name'=>'液晶电视','brand'=>'索尼','price'=>6299),
    array('name'=>'激光打印机','brand'=>'惠普','price'=>1200)
);
$ShoppingList = array_sort($array,'price');
print_r($ShoppingList);

上面是对$array这个二维数组按照'price'从低到高的排序。

PHP函数名参数

array array_filter ( array $input [, callable $callback = "" ] )

一些函数如 call_user_func() 或 usort() 可以接受用户自定义的回调函数作为参数。回调函数不止可以是 简单函数 ,还可以是对象的方法,包括 静态类方法
一个已实例化的对象的方法被作为数组传递,下标 0 包含该对象,下标 1 包含方法名。

静态类方法也可不经实例化该类的对象而传递,只要在下标 0 中包含类名而不是对象。自 PHP 5.2.3 起,也可以传递 'ClassName::methodName'。

除了普通的用户自定义函数外,create_function() 可以用来创建一个匿名回调函数。自 PHP 5.3.0 起也可传递 closure 给回调参数。

<?php // An example callback function
function my_callback_function() {
    echo 'hello world!';
}
// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}
// Type 1: Simple callback
call_user_func('my_callback_function'); 
// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod')); 
// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');
// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}
class B extends A {
    public static function who() {
        echo "B\n";
    }
}
call_user_func(array('B', 'parent::who')); // A
?>

closure

<?php $input = array_flip( range( 'a', 'z' ) );
$consonants = array_filter_key( $arr, function( $elem ) {
    $vowels = "aeiou";
    return strpos( $vowels, strtolower( $elem ) ) === false;
} );
?>
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。