Example method for using the header function to set HTTP headers in PHP
The code is as follows |
Copy Code |
Define Encoding 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 OK); Set a 404-head: Header (http/1.1 404 Not Found); Set addresses to be permanently redirected Header (http/1.1 moved Permanently); Go to a new address Header (location:http://www.example.org/); File delay turn: Header (refresh:10; url=http://www.example.org/); Print you are redirected in seconds; Of course, you can also use HTML syntax to implement <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); Document language Header (Content-language:en); Tell the browser when it was last modified $time = time ()-60; or Filemtime ($FN), etc Header (last-modified:. Gmdate (d, D M Y h:i:s, $time). GMT); Tells the browser that the contents of the document have not changed Header (http/1.1 304 not Modified); Set Content length Header (content-length:1234); Set to a download type 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); Disable caching for the current document Header (Cache-control:no-cache, No-store, max-age=0, must-revalidate); Header (Expires:mon, June June 1997 05:00:00 GMT); Date in the past Header (Pragma:no-cache); To set the content type: Header (content-type:text/html; charset=iso-8859-1); Header (content-type:text/html; charset=utf-8); Header (Content-type:text/plain); Plain Text Format Header (Content-type:image/jpeg); jpg*** Header (Content-type:application/zip); ZIP file Header (content-type:application/pdf); PDF file Header (Content-type:audio/mpeg); Audio files Header (Content-type:application/x-shockw**e-flash); Flash Animation Show Login dialog box Header (http/1.1 401 Unauthorized); Header (Www-authenticate:basic realm= "Top Secret"); Print Text that would be displayed if the user hits cancel or; Print enters wrong login data; |
A detailed explanation of the use of static statically variable in PHP
Another important feature of the scope of variables in PHP is static variables. A static variable exists only in the local function field and is initialized once, and the value does not disappear when the program executes away from the scope, using the result of the last execution.
Programming Examples:
The code is as follows |
Copy Code |
function test () { static $AA = 0; return $AA + +; } $AA = "1000"; Echo $aa; echo Test (); echo Test (); Echo $aa;
|
Every call to test () of this function outputs the $AA value and adds one.
The above code runs the output:
1000
0
1
1000
Static variables also provide a way to handle recursive functions. A recursive function is a method of calling itself. Be careful when writing recursive functions, as there may be infinite recursion, no exits. Be sure to have a way to abort recursion.
A one-dimensional array becomes a two-dimensional array, grouped by element or key value
Sometimes querying the database records will group the results of the database query, the one-dimensional array into a two-dimensional array, easy to invoke use (usually JSON)
The code is as follows |
Copy Code |
$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); After conversion Array ( [F1] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [F2] => Array ( [0] => 1 [1] => 2 ) ) |
PHP static binding and dynamic binding (Private/public)
the object of subclass Foo invokes the test () method, the test () method invokes the $this->testprivate (), and the $this should be a reference to a subclass at this point, and it is supposed to call the Testprivate () method of the subclass. Actually calls the Testprivate () method of the parent class
The code is as follows |
Copy Code |
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 (); Run results Bar->testprivate Foo->testpublic |
This is a situation in which PHP is dynamically bound and statically bound.
Public is dynamic binding and is not bound at compile time, so when the test () method of the parent class is invoked at run time, it resolves to the public method of the subclass.
Private is proprietary, does not inherit to subclasses, is bound at compile time, is a "static" binding (similar to 5.3 self).
Associated with this is the LSB, static delay binding, PHP5.3 because of this feature, the PHP oop is enhanced
Public: Can be inherited, or can be called externally.
Private: Can not be inherited, and can not be called outside.
Protected: Can be inherited, but cannot be called externally.
PHP three ways to run mod_php5/cgi/fast-cgi
A. Through the Httpserver built-in modules to achieve,
For example, Apache's MOD_PHP5, a similar Apache-built mod_perl can support Perl;
B. Using CGI to achieve
This is like the previous Perl CGI, which has the disadvantage of poor performance, because every time the server encounters these scripts, it needs to restart the script parser to execute the script and then return the results to the server, on the other hand it's less secure;
C. The latest appearance is called fastcgi.
The so-called fastcgi is the improvement of CGI. It generally uses C/s structure, the general script processor will start one or more daemon processes, each time the Httpserver encountered the script, delivered directly to the fastcgi process to execute, and then the resulting results (usually HTML) returned to the browser.
A small problem with this approach is that when encountering frequent requests for large traffic, the daemon process of the script processor can become overloaded and slow, and even memory leaks occur;
But the advantage of comparing Apache's built-in modules is that the server and the script parser are completely separate from the accountability, so the servers are no longer bloated, can focus on static file responses, or return the results of the dynamic script parser to the user client. So compare Apache's built-in modular approach, sometimes performance to improve a lot. Someone testing may reach apache+mod_php 5~10 times.
Three common patterns:
APACHE+MOD_PHP5;
lightppd+spawn-fcgi;
nginx+php-fpm
We can use in the production environment:
0 if not the server cluster:
You can use either of these, but there are a variety of tests that show NGINX+PHP-FPM performance is superior, but APACHE+MOD_PHP5 is very classic modules, such as the support for. htaccess.
If you build server cluster:
1) Nginx as a reverse proxy server, many apache+mod_php5 in the background.
Nginx processing static files, and PHP concurrent request to the background of multiple app server load balance;
2 Nginx as a reverse agent, many php-fpm in the background
Nginx processing static files and the PHP concurrent request sent to the background php-fpm to resolve;
Three variable naming rules (Hungarian law, Small hump method, Large Hump method)
1. Hungarian Name:
• Initials with variable type, the remainder using the English or English abbreviation of the variable, and asking for the first letter of the word to be capitalized.
for Example:long lsum = 0; " L "is the abbreviation of the type;
2. Small Hump type: (Little Camel-case)
• The first letter is lowercase, and the other words are capitalized.
for example:string firstName = string. Empty;
3. Large hump style: (Big camel-case)
• Capitalize the first letter of each word;
for example:string FirstName = string. Empty;
Solving the Json Chinese transcoding problem
The code is as follows |
Copy Code |
Code $data = Array ( ' Status ' => ' 1 ', ' Method ' => ' landing ', ' Message ' => ' success ', ); echo Json_encode ($data); Show {' Status ': ' 1 ', ' method ': ' u767bu9646 ', ' message ': ' u6210u529f '}
|
Json_encode can only accept data in utf-8 format, and the Chinese portion of the final JSON is replaced with Unicode encoding. All we have to do is convert the object to JSON and make sure that the Chinese inside the object still appears in normal Chinese in JSON.
The middle text segment in the class is URL-coded (UrlEncode), and then the object is JSON encoded (Jsonencode), and finally the URL decodes (urldecode) JSON, the final JSON, where Chinese is still the Chinese.
The code is as follows |
Copy Code |
Code foreach ($data as $key => $value) { $newData [$key] = UrlEncode ($value); } Echo UrlDecode (Json_encode ($newData)); Show {"Status": "1", "method": "Login", "message": "Success"}
|
Ajax Cross domain request cors error
When writing the JSON API for other site query calls, sometimes using Ajax to obtain, at this point, May Acao settings, then a Cros error occurs.
Error
XMLHttpRequest cannot load http://www.111cn.net. No ' Access-control-allow-origin ' header is present on the requested resource.
Solutions
The code is as follows |
Copy Code |
Header (' access-control-allow-origin: * '); Header (' access-control-allow-origin:ccdd.com '); CodeIgniter specify address to achieve HTTPS access management Start hooks app/config/config.php $config [' enable_hooks '] = TRUE; Hooks configuration app/config/hooks.php $hook [' post_controller_constructor '] = Array ( ' function ' => ' Check_ssl ', ' filename ' => ' ssl.php ', ' filepath ' => ' hooks ', ); Plugin Authoring 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 configuration requires the use of HTTPS's 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 ', ); Enforcing the use of SSL $config [' no_ssl_class_method '] = array (); |
Force not to use SSL