首页 > 代码库 > 通过分析WP的代码来学习PHP。1

通过分析WP的代码来学习PHP。1

下载了WP的代码,并且应用到了网站上面,现在也在正常的运行中,地址是:www.freealgorithm.tk 。具体的申请过程就不赘述了,学习WP的代码。

他的目录结构就不看了,可以下载同名文件我会通过相对目录来区分。

进入网站的第一个默认的页面:/index.php

<?php/** * Front to the WordPress application. This file doesn‘t do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress *//** * Tells WordPress to load the WordPress theme and output it. * * @var bool */define(‘WP_USE_THEMES‘, true);/** Loads the WordPress Environment and Template */ #定义WP_USE_THEMES为truerequire( dirname( __FILE__ ) . ‘/wp-blog-header.php‘ ); #返回路径中目录部分并且连接字符串得到此php文件的位置,用这个文件代替这个位置#引入同目录下的wp-blog-header.php文件

知识点:define函数,bool define    ( string $name   , mixed $value   [, bool $case_insensitive = false  ] ) 成功返回true否则false。
name:常量的名字。value:常量的值;仅允许标量和 null。标量的类型是 integerfloatstring 或者 boolean。 也能够定义常量值的类型为 resource ,但并不推荐这么做,可能会导致未知状况的发生。

require函数替换参数指向的文件,__FILE__取得当前文件的绝对路径,dirname返回路径中的目录部分。比如这个文件返回的就是根目录/。‘.‘这个符号是字符串连接运算符,将dirname(__FILE__)返回的字符串与‘/wp-blog-header.php‘相连接然后require进去。

而/wp-blog-header.php这个文件被包含了,如下:

 1 <?php 2  3 /** 4  * Loads the WordPress environment and template. 5  载入WordPress的环境和模板* 6  * @package WordPress 7  */ 8  9 10 if ( !isset($wp_did_header) ) #变量是否定义,定义返回true11 {12 13     $wp_did_header = true;14 15 16     require_once( dirname(__FILE__) . ‘/wp-load.php‘ );17 18     #用wp-load.php代替此语句19     /*如果定义了就不继续执行,否则执行下面的语句    */20 21     wp();22 23 24     require_once( ABSPATH . WPINC . ‘/template-loader.php‘ );25 26 #同样用27 }

isset函数用来判断这个变量是否已经被定义了,如果定义了就返回true否则返回false。如果没有定义的话就执行下面的语句,$wp_did_header=true;是定义变量,他是一个布尔变量。然后require_once这个文件 ,require_once函数与require的区别是以后再这个文件里不能再包含这个文件了,即仅仅包含这个文件一次。这些的动作是定义一个布尔变量且包含一个文件。下面的wp();函数指行,现在不知道这个函数的作用,一会就会看到。然后继续包含ABSPATH.WPINC.‘/template-loader.php‘。这个文件了。ABSPATH是绝对路径的意思,这个是WP自定义的常量,还有WPINC这两个,现在我们也不知道它的值是什么。此文件到此没有结束,我们继续跟踪进入wp-load.php.

 1 <?php 2  3 /** 4  5  * Bootstrap file for setting the ABSPATH constant 6  * and loading the wp-config.php file. The wp-config.php 7  * file will then load the wp-settings.php file, which 8  * will then set up the WordPress environment. 9  *10  * If the wp-config.php file is not found then an error11  * will be displayed asking the visitor to set up the12  * wp-config.php file.13  *14  * Will also search for wp-config.php in WordPress‘ parent15  * directory to allow the WordPress directory to remain16  * untouched.17  *18  * @internal This file must be parsable by PHP4.19  *20  * @package WordPress21  */22 23 24 /** Define ABSPATH as this file‘s directory 25 */26 27 define( ‘ABSPATH‘, dirname(__FILE__) . ‘/‘ );28 29 30 error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );31 32 /*error_reporting() 函数能够在运行时设置 error_reporting 指令。 PHP 有诸多错误级别,使用该函数可以设置在脚本运行时的级别。 如果没有设置可选参数 level, error_reporting() 仅会返回当前的错误报告级别。 */33 34 if ( file_exists( ABSPATH . ‘wp-config.php‘) ) #file_exists — 检查文件或目录是否存在,绝对路径+‘wp-config.php‘检测是否存在,这个文件是设置文件,后来在网站文件上传完成后进行安装时候来创建,所以在没有安装时候是不存在这个文件的。35 {36 37     /** The config file resides in ABSPATH */38     39     require_once( ABSPATH . ‘wp-config.php‘ );40 41 #如果文件存在,require_once把文件拿来42 #如果文件不存在,判断绝对路径取43 44 } elseif ( file_exists( dirname(ABSPATH) . ‘/wp-config.php‘ ) && ! file_exists( dirname(ABSPATH) . ‘/wp-settings.php‘ ) ) 45 {46 47     /** The config file resides one level above ABSPATH but is not part of another install */48 49     require_once( dirname(ABSPATH) . ‘/wp-config.php‘ );50 51 52 } else {53 54     // A config file doesn‘t exist55 56 57     define( ‘WPINC‘, ‘wp-includes‘ );58 59     define( ‘WP_CONTENT_DIR‘, ABSPATH . ‘wp-content‘ );60 61     require_once( ABSPATH . WPINC . ‘/load.php‘ );62 63     require_once( ABSPATH . WPINC . ‘/version.php‘ );64 65 66     wp_check_php_mysql_versions();67 68     wp_load_translations_early();69 70     // Standardize $_SERVER variables across setups.71     72     wp_fix_server_vars();73 74 75     require_once( ABSPATH . WPINC . ‘/functions.php‘ );76 77 78     $path = wp_guess_url() . ‘/wp-admin/setup-config.php‘;79 80     // Die with an error message81 82     $die  = __( "There doesn‘t seem to be a <code>wp-config.php</code> file. I need this before we can get started." ) . ‘</p>‘;83 84     $die .= ‘<p>‘ . __( "Need more help? <a href=http://www.mamicode.com/‘http://codex.wordpress.org/Editing_wp-config.php‘>We got it." ) . ‘</p>‘;85 86     $die .= ‘<p>‘ . __( "You can create a <code>wp-config.php</code> file through a web interface, but this doesn‘t work for all server setups. The safest way is to manually create the file." ) . ‘</p>‘;87     $die .= ‘<p><a href="http://www.mamicode.com/‘ . $path . ‘" class="button button-large">‘ . __( "Create a Configuration File" ) . ‘</a>‘;88 89 90     wp_die( $die, __( ‘WordPress &rsaquo; Error‘ ) );91 }

代码稍长,但是以后的代码会更长。这里看到了他的注释说定义ABSPATH为当前文件的目录,而且看到了这个define语句,知道了ABSPATH是dirname(__FILE__).‘/‘。其实还是这个根目录。error_reporting函数的说明在代码里面注释着意思是定义错误级别,我在书中也没有看到类似的说明这个函数,现在不予理会。
if当前绝对路径下的  /wp-config.php文件存在的话就require这个文件。不存在的话继续判断(/wp-config.php和/wp-settings.php)文件是否不存在,那么判断wp-config.php这个文件的判断是否多余?wp-setting.php这个文件是存在的,而wp-config.php是后来在安装时后生成的,第一次安装使用时候是没有的。否则就定义WPINC为‘wp-includes‘,define( ‘WP_CONTENT_DIR‘, ABSPATH . ‘wp-content‘ );require_once( ABSPATH . WPINC . ‘/load.php‘ );这句是将 /wp-includes/load.php包含进去,require_once( ABSPATH . WPINC . ‘/version.php‘ );这句将/wp-includes/version.php包含进去。先跟踪进去/wp-includes/load.php。

  1 <?php  2   3 /**  4  * These functions are needed to load WordPress.  5  *  6  * @internal This file must be parsable by PHP4.  7  *  8  * @package WordPress  9  */ 10  11  12 /** 13  * Turn register globals off. 14  * 15  * @access private 16  * @since 2.1.0 17  * @return null Will return null if register_globals PHP directive was disabled 18  */ 19  20 function wp_unregister_GLOBALS()  21 { 22  23     if ( !ini_get( ‘register_globals‘ ) ) 24  25         return; 26  27  28     if ( isset( $_REQUEST[‘GLOBALS‘] ) ) 29  30         die( ‘GLOBALS overwrite attempt detected‘ ); 31  32     // Variables that shouldn‘t be unset 33  34     $no_unset = array( ‘GLOBALS‘, ‘_GET‘, ‘_POST‘, ‘_COOKIE‘, ‘_REQUEST‘, ‘_SERVER‘, ‘_ENV‘, ‘_FILES‘, ‘table_prefix‘ ); 35  36  37     $input = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() ); 38     foreach ( $input as $k => $v ) 39  40         if ( !in_array( $k, $no_unset ) && isset( $GLOBALS[$k] ) )  41         { 42  43             unset( $GLOBALS[$k] ); 44  45         } 46  47 } 48  49  50 /** 51  * Fix $_SERVER variables for various setups. 52  * 53  * @access private 54  * @since 3.0.0 55  */ 56  57 function wp_fix_server_vars()  58 { 59  60     global $PHP_SELF; 61  62  63     $default_server_values = array( 64  65         ‘SERVER_SOFTWARE‘ => ‘‘, 66  67         ‘REQUEST_URI‘ => ‘‘, 68  69     ); 70  71  72     $_SERVER = array_merge( $default_server_values, $_SERVER ); 73  74     // Fix for IIS when running with PHP ISAPI 75  76     if ( empty( $_SERVER[‘REQUEST_URI‘] ) || ( php_sapi_name() != ‘cgi-fcgi‘ && preg_match( ‘/^Microsoft-IIS\//‘, $_SERVER[‘SERVER_SOFTWARE‘] ) ) ) 77     { 78  79         // IIS Mod-Rewrite 80  81         if ( isset( $_SERVER[‘HTTP_X_ORIGINAL_URL‘] ) ) 82         { 83  84             $_SERVER[‘REQUEST_URI‘] = $_SERVER[‘HTTP_X_ORIGINAL_URL‘]; 85  86         } 87         // IIS Isapi_Rewrite 88  89         else if ( isset( $_SERVER[‘HTTP_X_REWRITE_URL‘] ) ) { 90  91             $_SERVER[‘REQUEST_URI‘] = $_SERVER[‘HTTP_X_REWRITE_URL‘]; 92  93         } else { 94             // Use ORIG_PATH_INFO if there is no PATH_INFO 95  96             if ( !isset( $_SERVER[‘PATH_INFO‘] ) && isset( $_SERVER[‘ORIG_PATH_INFO‘] ) ) 97  98                 $_SERVER[‘PATH_INFO‘] = $_SERVER[‘ORIG_PATH_INFO‘]; 99 100 101             // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)102 103             if ( isset( $_SERVER[‘PATH_INFO‘] ) ) {104 105                 if ( $_SERVER[‘PATH_INFO‘] == $_SERVER[‘SCRIPT_NAME‘] )106 107                     $_SERVER[‘REQUEST_URI‘] = $_SERVER[‘PATH_INFO‘];108 109                 else110 111                     $_SERVER[‘REQUEST_URI‘] = $_SERVER[‘SCRIPT_NAME‘] . $_SERVER[‘PATH_INFO‘];112                         }    113     114 115             // Append the query string if it exists and isn‘t null116 117             if ( ! empty( $_SERVER[‘QUERY_STRING‘] ) ) {118 119                 $_SERVER[‘REQUEST_URI‘] .= ‘?‘ . $_SERVER[‘QUERY_STRING‘];120 121             }122 123         }124 125     }126 127 128     // Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests129     130     if ( isset( $_SERVER[‘SCRIPT_FILENAME‘] ) && ( strpos( $_SERVER[‘SCRIPT_FILENAME‘], ‘php.cgi‘ ) == strlen( $_SERVER[‘SCRIPT_FILENAME‘] ) - 7 ) )131 132         $_SERVER[‘SCRIPT_FILENAME‘] = $_SERVER[‘PATH_TRANSLATED‘];133 134     // Fix for Dreamhost and other PHP as CGI hosts135 136     if ( strpos( $_SERVER[‘SCRIPT_NAME‘], ‘php.cgi‘ ) !== false )137 138         unset( $_SERVER[‘PATH_INFO‘] );139 140     // Fix empty PHP_SELF141 142     $PHP_SELF = $_SERVER[‘PHP_SELF‘];143 144     if ( empty( $PHP_SELF ) )145 146         $_SERVER[‘PHP_SELF‘] = $PHP_SELF = preg_replace( ‘/(\?.*)?$/‘, ‘‘, $_SERVER["REQUEST_URI"] );147 148 }149 150 151 /**152  * Check for the required PHP version, and the MySQL extension or a database drop-in.153  *154  * Dies if requirements are not met.155  *156  * @access private157  * @since 3.0.0158  */159 160 161 function wp_check_php_mysql_versions() {162 163     global $required_php_version, $wp_version;164 165     $php_version = phpversion();166 167     if ( version_compare( $required_php_version, $php_version, ‘>‘ ) ) {168 169         wp_load_translations_early();170 171         header( ‘Content-Type: text/html; charset=utf-8‘ );172 173         die( sprintf( __( ‘Your server is running PHP version %1$s but WordPress %2$s requires at least %3$s.‘ ), $php_version, $wp_version, $required_php_version ) );174 175     }176 177 178     if ( ! extension_loaded( ‘mysql‘ ) && ! extension_loaded( ‘mysqli‘ ) && ! file_exists( WP_CONTENT_DIR . ‘/db.php‘ ) ) {179 180         wp_load_translations_early();181 182         header( ‘Content-Type: text/html; charset=utf-8‘ );183 184         die( __( ‘Your PHP installation appears to be missing the MySQL extension which is required by WordPress.‘ ) );185 186     }187 188 }189 190 191 192 /**193  * Don‘t load all of WordPress when handling a favicon.ico request.194  * Instead, send the headers for a zero-length favicon and bail.195  *196  * @since 3.0.0197  */198 199 200 function wp_favicon_request() {201 202     if ( ‘/favicon.ico‘ == $_SERVER[‘REQUEST_URI‘] ) {203 204         header(‘Content-Type: image/vnd.microsoft.icon‘);205 206         header(‘Content-Length: 0‘);207 208         exit;209 210     }211 212 }213 214 215 /**216  * Dies with a maintenance message when conditions are met.217  *218  * Checks for a file in the WordPress root directory named ".maintenance".219  * This file will contain the variable $upgrading, set to the time the file220  * was created. If the file was created less than 10 minutes ago, WordPress221  * enters maintenance mode and displays a message.222  *223  * The default message can be replaced by using a drop-in (maintenance.php in224  * the wp-content directory).225  *226  * @access private227  * @since 3.0.0228  */229 230 231 function wp_maintenance() {232 233     if ( !file_exists( ABSPATH . ‘.maintenance‘ ) || defined( ‘WP_INSTALLING‘ ) )234 235         return;236 237 238     global $upgrading;239 240 241     include( ABSPATH . ‘.maintenance‘ );242 243     // If the $upgrading timestamp is older than 10 minutes, don‘t die.244 245     if ( ( time() - $upgrading ) >= 600 )246 247         return;248 249 250     if ( file_exists( WP_CONTENT_DIR . ‘/maintenance.php‘ ) ) {251 252         require_once( WP_CONTENT_DIR . ‘/maintenance.php‘ );253 254         die();255 256     }257 258 259     wp_load_translations_early();260 261 262     $protocol = $_SERVER["SERVER_PROTOCOL"];263 264     if ( ‘HTTP/1.1‘ != $protocol && ‘HTTP/1.0‘ != $protocol )265 266         $protocol = ‘HTTP/1.0‘;267 268     header( "$protocol 503 Service Unavailable", true, 503 );269 270     header( ‘Content-Type: text/html; charset=utf-8‘ );271 272     header( ‘Retry-After: 600‘ );273 274 ?>

这是load.php的php部分,下面就基本是html代码了,html先不予分析。ini_get返回配制选项的值

通过分析WP的代码来学习PHP。1