search
HomeBackend DevelopmentPHP TutorialTen tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Ten tips for PHP developers to get twice the result with half the effort_PHP Tutorial

Jul 20, 2016 am 11:07 AM
indexphpGet twice the result with half the effortcreatetop tenhowEstablishDeveloperSkillhourcorrectofwebsitepage

1. How to correctly create an Index page of a website
When creating every website, establishing the index page of the website is one of the first things to do. If you are a PHP newbie, a typical approach when writing an index page is to program only the content required for the index page, and create another page for other links. However, if you want to learn a more efficient way to implement PHP programming, you can use the "index.php?page=home" mode, which is used by many websites.
2. Use Request Global Array to capture data
In fact, we have no reason to use $_GET and $_POST arrays to capture values. The global array $_REQUEST allows you to obtain a get or form request. Therefore, in most cases, the more efficient code for to parse data is roughly as follows:
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0; 3. Utilization var_dump for PHP code debugging
If you are looking for php debuggingtechniques, I must say that var_dump should be what you are looking for. This command can meet all your needs when it comes to displaying php information. Most cases of debugging code are related to getting values ​​in PHP.
4. PHP handles code logic, Smarty handles the presentation layer
Smarty is a templatePHP template engine written in PHP, which is currently the most famous PHP template in the industry One of the engines. It separates logical code and external content, providing an easy-to-manage and use method to logically separate PHP code that is originally mixed with HTML code. Simply put, the purpose is to separate PHP programmers from front-end personnel, so that programmers can change the logical content of the program without affecting the page design of the front-end personnel, and the front-end personnel can re-modify it. The page will not affect the program logic of the program, which is particularly important in multi-person collaboration projects.
5. When you really need to use global values, create a Config file
It is a bad practice to create global values ​​frequently, but sometimes the actual situation does require this. It is a good idea to use global values ​​for Database Tutorial table or database connection information, but do not use global values ​​frequently in your PHP code. Alternatively, a better approach is to store your global variables in a config.php file.
6. If it is not defined, access is prohibited!
If you create the page correctly, there is no reason for anyone else to access the index.php page outside of index.php or home.php. Once index.php is accessed, you can open the required page by obtaining the variables. Your index page should contain code similar to:
define('yourPage',1); Then, other pages should contain:
if (!defined('yourPage')) die('Access Denied') ; The purpose of this is to prevent direct access to your other php pages. This way, anyone trying to access other webpages without going through index.php will get an "Access Denied" message.
7. Create a database class
If you are doing database programming (a very common task in PHP), a good idea is to create a database class to handle any database management functionality . The sample code is as follows:
Public function dbexec ($ query) {$ result = $ this-& gt; db-& gt; exec ($ query); if ( PEA R :: ISERRT ($ Result)) ErrorRedirect ($ result-& gt ;getMessage(), true);             else                                                                               ’ ’ s ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ return $result;         } This function only receives a query statement and executes it. It also handles any errors that may occur. You can also include audit code here, but I prefer to use a similar audit function:
// checks if arguments given are integer values ​​not less than 0 - has multiple arguments function sanitizeInput() { $numargs = func_num_args( ); $arg_list = func_get_args(); for ($i = 0; $i require_once PROJECTROOT.'libs/messages.class.php'; $message = new Message(); switch ($action) { case 'display' :                   $message->display();                                                                                                 break; $message is just an object used by calling functions in the class.
9. Know your
SQL statements and always Sanitize them As I mentioned before, there is a 99% chance that the most important part of any php website is It's a database. Therefore, you need to be very familiar with how to use sql correctly. Learn association tables and more
advanced techniques. Below I will show an example of a function using MySQL and review it using function #7 of this article. private function getSentMessages($id) { $this->util->sanitizeInput($id); $pm_table = $GLOBALS['config']['privateMsg']; $users = $GLOBALS['config '] users']; $ SQL = "Select PM.*, USR.Username as name_sender from $ PM_Table PM, $ Usersr WHERE Id_SENDER = '$ ID' And Sender_purge = FALS E and usr.id = PM.ID_RECEIVER and is_read = True SQL command. Pay attention to the usage of SQL here. You need to understand how to use aliases and related tables.
10. Use the singleton pattern when you only need one object
In a very common situation in PHP, we only need to create an object once and then use it throughout our program. A good example of this is smart variables, which once initialized can be used anywhere. A good implementation solution for this situation is the singleton pattern. The sample code is as follows:
Function SmartyObject () {if ($ Globals ['Config'] ['Smartyobj'] == 0) {$ SMARTY = New Smartygame (); bj '] = $ Smarty;} Else $smarty = $GLOBALS['config']['SmartyObj'];                                           return $smarty; We will create a new smarty object. Otherwise, it means that the object has already been created and we just need to return it.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444959.htmlTechArticle1. How to correctly create the Index page of a website. When creating every website, establishing the index page of the website is the first priority. One of the things to do. If you are new to PHP and writing i...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software