10 PHP skills that are very useful for beginners and for beginners. 10 Useful PHP skills for beginners. This article describes some tips and skills for improving and optimizing php code for your reference. the specific content is as follows: 1. do not use 10 PHP skills that are useful to beginners.
This article introduces some tips and tips for improving and optimizing PHP code for your reference. the specific content is as follows:
1. do not use relative paths. define a root path
Such code lines are common:
require_once('../../lib/some_class.php');
This method has many disadvantages:
1) it first searches for the specified directory in the php including path and then displays the current directory. Therefore, many directories are checked.
2) when a script is included in different directories of another script, its basic directory becomes the directory containing the script.
3) Another problem is that when a script runs from cron, it may not use its parent directory as the working directory.
Therefore, using absolute paths becomes a good method:
define('ROOT' , '/var/www/project/');require_once(ROOT . '../../lib/some_class.php');//rest of the code
This is an absolute path and will remain unchanged. However, we can further improve it. The directory/var/www/project can be changed. Do we need to change it every time?
No. use a magic constant such as _ FILE _ to make it portable. Take a closer look:
//suppose your script is /var/www/project/index.php//Then __FILE__ will always have that full path.define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));require_once(ROOT . '../../lib/some_class.php');//rest of the code
So now, even if you move a project to a different Directory, such as moving it to an online server, the code can run without any changes.
2. do not use require, including require_once or include_once
Your script may contain various files, such as class libraries, utility files, and auxiliary functions, like these:
require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php');
This is rather rough. Code needs to be more flexible. Writing a helper function makes it easier to include things. For example:
function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); require_once( $path ); }load_class('Database');load_class('Mail');
Do you see the difference? Obviously. No more explanation is required.
You can further improve:
function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }}
This can accomplish many things:
Search multiple directories for the same class file.
Easily change the directory containing class files without damaging code anywhere.
Use similar functions to load files that contain helper functions and HTML content.
3. maintain the debugging environment in the application
During the development process, we echo database queries, dump the variables that create the problem, and once the problem is solved, we comment them or delete them. However, keeping everything in place can provide long-term help.
On the Development computer, you can do this:
define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
And on the server, you can do this:
define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
4. Send Status messages through sessions
Status messages are those generated after the task is executed.
<?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><?php echo $msg; ?>
Such code is very common. Using Variables to display status information has certain limitations. Because they cannot be sent through redirection (unless you spread them as GET variables to the next script, but this is silly ). In addition, there may be multiple messages in large scripts.
The best way is to use sessions for propagation (even on the same page ). To do this, you must have a session_start on each page.
function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;}
In your script:
<?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?>Status is : <?php echo get_flash(); ?>
5. flexible functions
function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 );
Use the above function when adding a single entry. So when multiple entries are added, do I have to create another function? NO. You only need to make the function flexible so that it can accept different parameters. See:
function add_to_cart($item_id , $qty){ if(!is_array($item_id)) { $_SESSION['cart'][$item_id] = $qty; } else { foreach($item_id as $i_id => $qty) { $_SESSION['cart'][$i_id] = $qty; } }}add_to_cart( 'IPHONE3' , 2 );add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );
Now, the same function can accept different types of output. The above code can be applied to many places to make your code more flexible.
6. omit the end php tag. if it is the last line in the script
I don't know why many blog posts will omit this technique when talking about php tips.
<?phpecho "Hello";//Now dont close this tag
This helps you omit a large number of problems. For example:
Class file super_class.php
<?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag
Now let's look at index. php.
require_once('super_class.php');//echo an image or pdf , or set the cookies or session data
You will get the sending error Header. Why? Because "super redundant characters", all titles are processed. So you have to start debugging. You may need to waste a lot of time looking for extra space.
Therefore, we need to develop the habit of omitting the end tag:
<?phpclass super_class{ function super_function() { //super code }}//No closing tag
This is better.
7. collect all outputs in one place and then output them to the browser at a time.
This is the so-called output buffer. For example, you get something like this from different functions:
function print_header(){ echo "Site Log and Login links
";}function print_footer(){ echo "Site was made by me
";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i
';}print_footer();
In fact, you should first collect all the output in one place. You can either store the variable in the function or use ob_start and ob_end_clean. So now it should look like this
function print_header(){ $o = "Site Log and Login links
"; return $o;}function print_footer(){ $o = "Site was made by me
"; return $o;}echo print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i
';}echo print_footer();
So why should you buffer the output:
You can change the output before sending it to the browser, if needed. For example, do some str_replaces, or preg_replaces, or add some additional html at the end, such as profiler/debugger output.
It is not a good idea to send the output to the browser and perform php processing at the same time. Have you ever seen a website with a Fatal error in the sidebar or in the box in the middle of the screen? Do you know why? Because the processing process and output are mixed together.
8. when non-HTML content is output, the correct mime type is sent through the header.
See some XML.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "
0
";//Send xml dataecho $xml;
Working properly. But it requires some improvements.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "
0
";//Send xml dataheader("content-type: text/xml");echo $xml;
Note the header line. This line of code tells the browser that the content is XML. Therefore, the browser can handle it correctly. Many JavaScript libraries also rely on header information.
JavaScript, css, JPG, and png images are the same:
JavaScript
header("content-type: application/x-javascript");echo "var a = 10";CSSheader("content-type: text/css");echo "#p id { background:#000; }"
9. set correct character encoding for MySQL connections
I have encountered the problem that unicode/UTF-8 characters are correctly stored in mysql tables. phpmyadmin also shows that they are correct, but when you use them, your webpage cannot be correctly displayed. The secret lies in MySQL connection verification.
$host = 'localhost';$username = 'root';$password = 'super_secret';//Attempt to connect to database$c = mysqli_connect($host , $username, $password);//Check connection validityif (!$c) { die ("Could not connect to the database host:
". mysqli_connect_error());}//Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){ die('mysqli_set_charset() failed');}
Once you connect to the database, you may wish to set the connection character set. This is absolutely necessary when you use multiple languages in your application.
Otherwise, what will happen? You will see a lot of boxes and ????????.
10. use htmlentities with the correct character set options
Before PHP 5.4, the default character encoding used is a ISO-8859-1, which cannot display characters such as â.
$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');
From PHP 5.4, the default code is UTF-8, which solves most of the problem, but you 'd better know it if your application uses multiple languages.
We will introduce these 10 tips first. The remaining PHP skills will be shared with you in the following articles. thank you for reading them.
Articles you may be interested in:
- PHP delimiter usage tips
- PHP shortde_path setting tips
- PHP Array Operations Summary php array usage tips
- Tips for PHP recursive call
- Php watermarking techniques for uploading multiple images
- Php error handling methods and techniques
- PHP timestamp strtotime () usage and tips
- Application skills of JSON and JSON in PHP
- PHP tips: how to use JS and CSS optimization tool Minify
- PHP namespace dynamic access and usage skills
This article introduces some tips and tips for improving and optimizing PHP code for your reference. the specific content is as follows: 1. do not use it...