そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。<\/p>
最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。<\/p>
function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;}<\/pre> そしてスクリプト內(nèi):<\/p> 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂Status is :
そしてスクリプト內(nèi):<\/p>
国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂Status is :
function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 );<\/pre> 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう:<\/p> 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) );<\/pre> これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。<\/p> 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 <\/p>すごいこれで多くの問題が回避されます。例を見てみましょう:<\/p> クラスファイル super_class.php<\/p> 今度は、index.php<\/p> \/\/super extra character after the closing tag<\/pre> そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。<\/p> したがって、終了タグを省略する習慣をつけましょう:<\/p> require_once('super_class.php');\/\/echo an image or pdf , or set the cookies or session data<\/pre> その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p> そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう:<\/p>
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) );<\/pre> これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。<\/p> 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 <\/p>すごいこれで多くの問題が回避されます。例を見てみましょう:<\/p> クラスファイル super_class.php<\/p> 今度は、index.php<\/p> \/\/super extra character after the closing tag<\/pre> そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。<\/p> したがって、終了タグを省略する習慣をつけましょう:<\/p> require_once('super_class.php');\/\/echo an image or pdf , or set the cookies or session data<\/pre> その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p> そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。<\/p> 6. php の終了タグがスクリプトの最後にある場合は省略します。
なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 <\/p>すごい
これで多くの問題が回避されます。例を見てみましょう:<\/p>
クラスファイル super_class.php<\/p>
今度は、index.php<\/p> \/\/super extra character after the closing tag<\/pre> そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。<\/p> したがって、終了タグを省略する習慣をつけましょう:<\/p> require_once('super_class.php');\/\/echo an image or pdf , or set the cookies or session data<\/pre> その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p> そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
今度は、index.php<\/p>
\/\/super extra character after the closing tag<\/pre> そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。<\/p> したがって、終了タグを省略する習慣をつけましょう:<\/p> require_once('super_class.php');\/\/echo an image or pdf , or set the cookies or session data<\/pre> その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p> そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。<\/p>
したがって、終了タグを省略する習慣をつけましょう:<\/p>
require_once('super_class.php');\/\/echo an image or pdf , or set the cookies or session data<\/pre> その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p> そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
その方が良いです。<\/p> 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ
これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。<\/p>
そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p> function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります<\/p>
function print_header(){ echo \"Site Log and Login links<\/div>\";}function print_footer(){ echo \"Site was made by me<\/div>\";}print_header();for($i = 0 ; $i < 100; $i++){ echo \"I is : $i ';}print_footer();<\/pre> それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
それでは、なぜ出力バッファリングを行う必要があるのですか:<\/p> You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler\/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content
Lets echo some xml.<\/p>
$xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
0<\/code><\/response>\";\/\/Send xml dataecho $xml;<\/pre> Works fine. But it needs some improvement.<\/p> $xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Works fine. But it needs some improvement.<\/p>
$xml = '';$xml = \" 0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
0<\/code><\/response>\";\/\/Send xml dataheader(\"content-type: text\/xml\");echo $xml;<\/pre> Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p> Similarly for javascript , css , jpg image , png image :<\/p> Javascript<\/p> header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.<\/p>
Similarly for javascript , css , jpg image , png image :<\/p>
Javascript<\/p>
header(\"content-type: application\/x-javascript\");echo \"var a = 10\";<\/pre> CSS<\/p> header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
CSS<\/p>
header(\"content-type: text\/css\");echo \"#div id { background:#000; }\";<\/pre> 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p> $host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Ever faced a problem that unicode\/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.<\/p>
$host = 'localhost';$username = 'root';$password = 'super_secret';\/\/Attempt to connect to database$c = mysqli_connect($host , $username, $password);\t\t\/\/Check connection validityif (!$c) {\tdie (\"Could not connect to the database host: \". mysqli_connect_error());}\t\t\/\/Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){\tdie('mysqli_set_charset() failed');}<\/pre> Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p> Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p> $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.<\/p>
Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.<\/p> 10. Use htmlentities with the correct characterset option
Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.<\/p>
$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');<\/pre> Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p> Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php.<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.<\/p> 11. Do not gzip output in your application , make apache do that
Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.<\/p>
Use apache mod_gzip\/mod_deflate to compress content via the .htaccess file.<\/p> 12. Use json_encode when echoing javascript code from php
There are times when some javascript code is generated dynamically from php.<\/p>
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= \"'$image' ,\";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;\/\/Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];<\/pre> Be smart. use json_encode :<\/p> $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Be smart. use json_encode :<\/p>
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;\/\/Output is : var images = [\"myself.png\",\"friends.png\",\"colleagues.png\"]<\/pre> Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p> Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p> $contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Isn't that neat ?<\/p> 13. Check if directory is writable before writing any files
Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of \"debugging\" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.<\/p>
Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.<\/p>
$contents = \"All the content\";$file_path = \"\/var\/www\/project\/content.txt\";file_put_contents($file_path , $contents);<\/pre> That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file.<\/p> $contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :<\/p> Parent directory does not exist Directory exists , but is not writable File locked for writing ?
So its better to make everything clear before writing out to a file.<\/p>
$contents = \"All the content\";$dir = '\/var\/www\/project';$file_path = $dir . \"\/content.txt\";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die(\"Directory $dir is not writable, or does not exist. Please check\");}<\/pre> By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p> \/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
By doing this you get the accurate information that where is a file write failing and why<\/p> 14. Change permission of files that your application creates
When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are \"accessible\" outside. Otherwise for example the files may be created by \"php\" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.<\/p>
\/\/ Read and write for owner, read for everybody elsechmod(\"\/somedir\/somefile\", 0644);\/\/ Everything for owner, read and execute for otherschmod(\"\/somedir\/somefile\", 0755);<\/pre> 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
if($_POST['submit'] == 'Save'){ \/\/Save the things}<\/pre> The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p> if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :<\/p>
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ \/\/Save the things}<\/pre> Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value \/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Now you are free from the value the submit button<\/p> 16. Use static variables in function where they always have same value
\/\/Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); \t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> Instead use static variables as :<\/p> \/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Instead use static variables as :<\/p>
\/\/Delay for some timefunction delay(){ static $sync_delay = null;\t if($sync_delay == null) {\t$sync_delay = get_option('sync_delay'); }\t echo \"Delaying for $sync_delay seconds...\"; sleep($sync_delay); echo \"Done \";}<\/pre> 17. Don't use the $_SESSION variable directly Some simple examples are :<\/p> $_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Some simple examples are :<\/p>
$_SESSION['username'] = $username;$username = $_SESSION['username'];<\/pre> But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p> Hence use application specific keys with wrapper functions :<\/p> define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.<\/p>
Hence use application specific keys with wrapper functions :<\/p>
define('APP_ID' , 'abc_corp_ecommerce');\/\/Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}\/\/Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}<\/pre> 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like :<\/p> function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
So you have a lot of utility functions in a file like :<\/p>
function utility_a(){ \/\/This function does a utility thing like string processing}function utility_b(){ \/\/This function does nother utility thing like database processing}function utility_c(){ \/\/This function is ...}<\/pre> And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p> class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
And you use the function throughout your application freely. You may want to wrap them into a class as static functions :<\/p>
class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}\/\/and call them as $a = Utility::utility_a();$b = Utility::utility_b();<\/pre> One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.<\/p> 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this :
if($a == true) $a_count++;<\/pre> Its absolutely a WASTE.<\/p> Write<\/p> if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Its absolutely a WASTE.<\/p>
Write<\/p>
if($a == true){ $a_count++;}<\/pre> Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this :<\/p> foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.<\/p> Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map
Lets say you want to trim all elements of an array. Newbies do it like this :<\/p>
foreach($arr as $c => $v){\t$arr[$c] = trim($v);}<\/pre> But it can more cleaner with array_map :<\/p> $arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
But it can more cleaner with array_map :<\/p>
$arr = array_map('trim' , $arr);<\/pre> This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p> The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.<\/p> 21. Validate data with php filters
Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.<\/p>
The php filter extension provides simple way to validate or check values as being a valid 'something'.<\/p> 22. Force type checking
$amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];<\/pre> Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p> $db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Its a good habit.<\/p> 23. Write Php errors to file using set_error_handler()
set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose<\/p> 24. Handle large arrays carefully
Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :<\/p>
$db_records_in_array_format; \/\/This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; \/\/2MB moresome_function($cc); \/\/Another 2MB ?<\/pre> The above thing is common when importing a csv file or exporting table to a csv file<\/p> Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p> Consider passing them by reference , or storing them in a class variable :<\/p> $a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The above thing is common when importing a csv file or exporting table to a csv file<\/p>
Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.<\/p>
Consider passing them by reference , or storing them in a class variable :<\/p>
$a = get_large_array();pass_to_function(&$a);<\/pre> by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p> class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
by doing this the same variable (and not its copy) will be available to the function. Check documentation<\/p>
class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { \/\/process $this->a }}<\/pre> unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p> Here is a simple demonstration of how assign by reference can save memory in some cases<\/p> ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
unset them as soon as possible , so that memory is freed and rest of the script can relax.<\/p>
Here is a simple demonstration of how assign by reference can save memory in some cases<\/p>
';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() \/ 1000000 . '';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() \/ 1000000 . '';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() \/ 1000000 . '';<\/pre> The output on a typical php 5.4 machine is :<\/p> Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p> So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p> function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The output on a typical php 5.4 machine is :<\/p>
Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 <\/p>
So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.<\/p> 25. Use a single database connection, throughout the script
Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :<\/p>
function add_to_cart(){ $db = new Database(); $db->query(\"INSERT INTO cart .....\");}function empty_cart(){ $db = new Database(); $db->query(\"DELETE FROM cart .....\");}<\/pre> Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p> Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it $query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.<\/p>
Use the singleton pattern for special cases like database connection.<\/p> 26. Avoid direct SQL query , abstract it
$query = \"INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')\";$db->query($query); \/\/call to mysqli_query()<\/pre> The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord<\/p> It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p> A very simple example of an activerecord insert function can be like this :<\/p> function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:<\/p> All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that
Solution: ActiveRecord<\/p>
It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.<\/p>
A very simple example of an activerecord insert function can be like this :<\/p>
function insert_record($table_name , $data){ foreach($data as $key => $value) {\t\/\/mysqli_real_escape_string $data[$key] = $db->mres($value); }\t\t $fields = implode(',' , array_keys($data)); $values = \"'\" . implode(\"','\" , array_values($data)) . \"'\"; \/\/Final query\t $query = \"INSERT INTO {$table}($fields) VALUES($values)\";\t\t return $db->query($query);}\/\/data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);\/\/perform the INSERT queryinsert_record('users' , $data);<\/pre> The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p> This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p> Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p> Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example :<\/p> <\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).<\/p>
This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.<\/p> 27. Cache database generated content to static files
Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.<\/p>
Benefits :<\/p> Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database
File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.<\/p>
Storing session in database makes many other things easier like:<\/p> Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines\/constants Get value using a function Use Class and access via $this 30. Use base url in head tag
Quick example :<\/p>
<\/head> <\/body><\/html><\/pre> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p> Lets take an example<\/p> www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p> In home.php the following can be written :<\/p> Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.<\/p>
Lets take an example<\/p>
www.domain.com\/store\/home.php www.domain.com\/store\/products\/ipad.php<\/p>
In home.php the following can be written :<\/p>
Home<\/a>Ipad<\/a><\/pre> But in ipad.php the links have to be like this :<\/p> Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
But in ipad.php the links have to be like this :<\/p>
Home<\/a>Ipad<\/a><\/pre> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p> <\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.<\/p>
<\/head>Home<\/a>Ipad<\/a><\/body><\/html><\/pre> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p> ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products\/ipad.php<\/p> 31. Manage error reporting
error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.<\/p>
ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);<\/pre> On production , the display should be disabled.<\/p> ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
On production , the display should be disabled.<\/p>
ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p> After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p> ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.<\/p>
After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.<\/p>
ini_set('log_errors' , '1');ini_set('error_log' , '\/path\/to\/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);<\/pre> Note :<\/p> 1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p> 2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p> 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p> 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p> 5. Dont set error_reporting to 0. It will not log anything then.<\/p> Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p> Set 'display_errors=On' in php.ini on development machine<\/p> On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p> Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p> Set 'display_errors=Off' in php.ini on production machine<\/p> Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p> On a 64 bit machine you can see such output.<\/p> $ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
Note :<\/p>
1. The path '\/path\/to\/errors.txt' should be writable by the web server for errors to be logged there.<\/p>
2. A separate error file is specified , otherwise all logs would go inside the apache\/web server error log and get mixed up with other apache errors.<\/p>
3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).<\/p>
4. The path can be somewhere inside the directory of the current application as well , so that the system directories like \/var\/log dont have to searched.<\/p>
5. Dont set error_reporting to 0. It will not log anything then.<\/p>
Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.<\/p>
Set 'display_errors=On' in php.ini on development machine<\/p>
On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.<\/p>
Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.<\/p>
Set 'display_errors=Off' in php.ini on production machine<\/p>
Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.<\/p> 32. Be aware of platform architecture
The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.<\/p>
On a 64 bit machine you can see such output.<\/p>
$ php -aInteractive shellphp > echo strtotime(\"0000-00-00 00:00:00\");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600<\/pre> But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p> What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this :<\/p> set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
But on a 32 bit machine all of them would give bool(false). Check here for more.<\/p>
What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.<\/p> 33. Dont rely on set_time_limit too much
If you are limiting the maximum run-time of a script , by doing this :<\/p>
set_time_limit(30);\/\/Rest of the code<\/pre> It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p> So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p> A better solution :<\/p> \/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
It may not always work. Any execution that happens outside the script via system calls\/os functions like socket operations, database operations etc. will not be under control of set_time_limit.<\/p>
So if a database operation takes lot of time or \"hangs\" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.<\/p> 34. Make a portable function for executing shell commands
system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.<\/p>
A better solution :<\/p>
\/**\tMethod to execute a command in the terminal\tUses :\t1. system\t2. passthru\t3. exec\t4. shell_exec*\/function terminal($command){\t\/\/system\tif(function_exists('system'))\t{\t\tob_start();\t\tsystem($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/passthru\telse if(function_exists('passthru'))\t{\t\tob_start();\t\tpassthru($command , $return_var);\t\t$output = ob_get_contents();\t\tob_end_clean();\t}\t\/\/exec\telse if(function_exists('exec'))\t{\t\texec($command , $output , $return_var);\t\t$output = implode(\"\\n\" , $output);\t}\t\/\/shell_exec\telse if(function_exists('shell_exec'))\t{\t\t$output = shell_exec($command) ;\t}\telse\t{\t\t$output = 'Command execution not possible on this system';\t\t$return_var = 1;\t}\treturn array('output' => $output , 'status' => $return_var);}terminal('ls');<\/pre> The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p> Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p> Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p> They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p> The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p> 1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p> Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p> ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "} コミュニティ 記事 トピックス に質(zhì)問 學ぶ コース プログラミング辭典 ツールライブラリ 開発ツール 公式サイト PHP ライブラリ JS特殊効果 サイト素材 拡張プラグイン AIツール レジャー ゲームのダウンロード ゲームのチュートリアル 日本語 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup ホームページ バックエンド開発 PHPチュートリアル 初心者向けの 40 以上の PHP の役立つヒント ?パート1 初心者向けの 40 以上の PHP の役立つヒント ?パート1 WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB Jun 23, 2016 pm 02:37 PM PHP 學習指南 http://www.binarytides.com/category/php-2/tutorial/ このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。 テクニック 1. 相対パスを使用せず、代わりに ROOT パスを定義します。 このような行を見るのはよくあることです : require_once('http://www.cnblogs.com/lib/some_class.php'); このアプローチ多くの欠點があります: 最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。 スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。 もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。 そのため、絶対パスを使用することをお勧めします: define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう: //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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。 2. require 、 include 、 require_once 、または include_once は使用しないでください。 スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます: require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php'); これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう: 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'); 何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます : function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }} これでできることはたくさんあります : 同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。 3. アプリケーションでデバッグ環(huán)境を維持します。 開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです 開発マシンではこれを?qū)g行できます: define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } サーバーではこれを?qū)g行できます: define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } 4. セッション経由でステータス メッセージを伝播します ステータス メッセージタスクの実行後に生成されるメッセージです。 <?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html> そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。 最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。 function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;} そしてスクリプト內(nèi): <?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html> 5. 関數(shù)を柔軟にする function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 ); 単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう: 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) ); これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。 6. php の終了タグがスクリプトの最後にある場合は省略します。 なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。 すごいこれで多くの問題が回避されます。例を見てみましょう: クラスファイル super_class.php <?phpecho "Hello";//Now dont close this tag 今度は、index.php <?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。 したがって、終了タグを省略する習慣をつけましょう: require_once('super_class.php');//echo an image or pdf , or set the cookies or session data その方が良いです。 7. すべての出力を 1 か所に集め、一気に出力します。ブラウザ これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。 <?phpclass super_class{ function super_function() { //super code }}//No closing tag そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer(); それでは、なぜ出力バッファリングを行う必要があるのですか: You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed. 8. Send correct mime types via header when outputting non-html content Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript");echo "var a = 10"; CSS header("content-type: text/css");echo "#div id { background:#000; }"; 9. Set the correct character encoding for a mysql connection Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text. 10. Use htmlentities with the correct characterset option Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual. 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ? 13. Check if directory is writable before writing any files Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : Parent directory does not exist Directory exists , but is not writable File locked for writing ? So its better to make everything clear before writing out to a file. $contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");} By doing this you get the accurate information that where is a file write failing and why 14. Change permission of files that your application creates When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755); 15. Don't check submit button value to check form submission if($_POST['submit'] == 'Save'){ //Save the things} The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things} Now you are free from the value the submit button 16. Use static variables in function where they always have same value //Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} Instead use static variables as : //Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";} 17. Don't use the $_SESSION variable directly Some simple examples are : $_SESSION['username'] = $username;$username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;} 18. Wrap utility helper functions into a class So you have a lot of utility functions in a file like : function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...} And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else. 19. Bunch of silly tips Use echo instead of print Use str_replace instead of preg_replace , unless you need it absolutely Do not use short tags Use single quotes instead of double quotes for simple strings Always remember to do an exit after a header redirect Never put a function call in a for loop control line. isset is faster than strlen Format your code correctly and consistently Do not drop the brackets of loops or if-else blocks. Do not code like this : if($a == true) $a_count++; Its absolutely a WASTE. Write if($a == true){ $a_count++;} Dont try to make your code shorter by eating up syntax. Rather make your logic shorter. Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors. 20. Process arrays quickly with array_map Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v){ $arr[$c] = trim($v);} But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more. 21. Validate data with php filters Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'. 22. Force type checking $amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate']; Its a good habit. 23. Write Php errors to file using set_error_handler() set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose 24. Handle large arrays carefully Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array();pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }} unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more. 25. Use a single database connection, throughout the script Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");} Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection. 26. Avoid direct SQL query , abstract it $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: All values have to be escaped everytime manually Manually verify the sql syntax everytime. Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise. 27. Cache database generated content to static files Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits : Save php processing to generate the page , hence faster execution Lesser database queries means lesser load on mysql database 28. Store sessions in database File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like: Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time Check online status of users more accurately 29. Avoid using globals Use defines/constants Get value using a function Use Class and access via $this 30. Use base url in head tag Quick example : <head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html> The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> But in ipad.php the links have to be like this : <a href="../home.php">Home</a><a href="ipad.php">Ipad</a> This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. <a href="home.php">Home</a><a href="products/ipad.php">Ipad</a> Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php 31. Manage error reporting error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away. 32. Be aware of platform architecture The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines. 33. Dont rely on set_time_limit too much If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30);//Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time. 34. Make a portable function for executing shell commands system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : /** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent. 35. Localize your application Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user. 36. Use a profiler like xdebug if you need to Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind. 37. Use plenty of external libraries An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are : mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference. 39. Use an MVC framework Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code. Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out. 41. Go to the IRC channel to ask The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!! 42. Read open source code Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more 1. Codeigniter 2. WordPress 3. Joomla CMS43. Linux で開発する すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。 Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。 ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。 このウェブサイトの聲明 この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。 ホットAIツール Undress AI Tool 脫衣畫像を無料で Undresser.AI Undress リアルなヌード寫真を作成する AI 搭載アプリ AI Clothes Remover 寫真から衣服を削除するオンライン AI ツール。 Clothoff.io AI衣類リムーバー Video Face Swap 完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。 もっと見る 人気の記事 ガイド:Stellar Blade Save Fileの場所/ファイルを保存する/保存しない 4週間前 By DDD Agnes Tachyonビルドガイド|かなりのダービーズメソム 2週間前 By Jack chen Oguri Cap Build Guide |かなりのダービーズメソム 2週間前 By Jack chen 砂丘:目覚め - 高度な惑星科醫(yī)クエストウォークスルー 4週間前 By Jack chen すべての日付:ダークとハーパーの関係ガイド 4週間前 By Jack chen もっと見る ホットツール メモ帳++7.3.1 使いやすく無料のコードエディター SublimeText3 中國語版 中國語版、とても使いやすい ゼンドスタジオ 13.0.1 強力な PHP 統(tǒng)合開発環(huán)境 ドリームウィーバー CS6 ビジュアル Web 開発ツール SublimeText3 Mac版 神レベルのコード編集ソフト(SublimeText3) もっと見る ホットトピック Gmailメールのログイン入り口はどこですか? 8638 17 Java チュートリアル 1783 16 CakePHP チュートリアル 1728 56 Laravel チュートリアル 1579 28 PHP チュートリアル 1444 31 もっと見る Related knowledge PHPに認証と承認を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。 PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。 PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。 PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests. PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset. See all articles
The above function will execute the shell command using whichever function is available , keeping your code consistent.<\/p> 35. Localize your application
Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.<\/p> 36. Use a profiler like xdebug if you need to
Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.<\/p>
Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.<\/p> 37. Use plenty of external libraries
An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.<\/p>
Few popular libraries are :<\/p> mPDF - Generate pdf documents, by converting html to pdf beautifully. PHPExcel - Read and write Excel files PhpMailer - Send html emails with attachments easily pChart - Generate graphs in php 38. Have a look at phpbench for some micro-optimisation stats
If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.<\/p> 39. Use an MVC framework
Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.<\/p> Clean separation of php and html code. Good for team work, when designers and coders are working together. Functions and functionalities are organised in classes making maintenance easy. Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc. Is a must when writing big applications Lots of tips, techniques, hacks are already implemented in the framework 40. Read the comments on the php documentation website
The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.<\/p>
They contain user feedback, expert advice and useful code snippets. So check them out.<\/p> 41. Go to the IRC channel to ask
The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!<\/p> 42. Read open source code
Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.<\/p>
The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more<\/p>
1. Codeigniter 2. WordPress 3. Joomla CMS<\/p>43. Linux で開発する
すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。<\/p>
Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。<\/p>
ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。<\/p> "}
PHP 學習指南
http://www.binarytides.com/category/php-2/tutorial/
このシリーズでは、改善と最適化に使用できるいくつかの役立つヒントとテクニックを検討します。あなたのphpコード。これらの PHP のヒントは初心者向けであり、すでに mvc フレームワークなどを使用している人向けではないことに注意してください。
このような行を見るのはよくあることです :
require_once('http://www.cnblogs.com/lib/some_class.php');
このアプローチ多くの欠點があります:
最初に php のインクルード パスで指定されたディレクトリを検索し、次に現(xiàn)在のディレクトリから検索します。 非常に多くのディレクトリがチェックされます。
スクリプトが別のディレクトリにある別のスクリプトによってインクルードされる場合、そのベースディレクトリは、インクルード スクリプトのディレクトリに変更されます。
もう 1 つの問題は、スクリプトが cron から実行されている場合、その親ディレクトリが作業(yè)ディレクトリとしてない可能性があることです。
そのため、絶対パスを使用することをお勧めします:
define('ROOT' , '/var/www/project/');require_once(ROOT . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code
これは絶対パスであり、常に一定になります。しかし、これをさらに改善することができます。 /var/www/project ディレクトリは変更される可能性があるので、毎回変更するのでしょうか?いいえ、代わりに __FILE__ のようなマジック定數(shù)を使用して移植性を高めます。詳しく見てみましょう:
//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 . 'http://www.cnblogs.com/lib/some_class.php');//rest of the code
したがって、プロジェクトをオンラインサーバーに移動するなど、別のディレクトリに移動した場合でも、同じコードは変更せずに実行されます。
スクリプトには、次のように、クラス ライブラリ、ユーティリティやヘルパー関數(shù)のファイルなど、さまざまなファイルを上部に含めることができます:
require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php');
これはかなり原始的です。コードはもっと柔軟にする必要があります。ヘルパー関數(shù)を作成して、より簡単に組み込みます。例を見てみましょう:
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');
何か違いはありますか?絶対です。これ以上の説明は必要ありません。 これを気に入ったら、これをさらに改善できます :
function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); }}
これでできることはたくさんあります :
同じクラス ファイルを複數(shù)のディレクトリで検索します。 変更コードをどこにも壊すことなく、クラスファイルを含むディレクトリを簡単に取得できます。 ヘルパー関數(shù)、HTML コンテンツなどを含むファイルをロードするには、同様の関數(shù)を使用します。
開発中、データベース クエリをエコーし??、変數(shù)をダンプします。問題を作成し、問題が解決したら、コメントするか削除します。しかし、すべてをそのままにして、長期的には役立つようにするのは良い考えです
開発マシンではこれを?qū)g行できます:
define('ENVIRONMENT' , 'development');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
サーバーではこれを?qū)g行できます:
define('ENVIRONMENT' , 'production');if(! $db->query( $query ){ if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
ステータス メッセージタスクの実行後に生成されるメッセージです。
<?phpif($wrong_username || $wrong_password){ $msg = 'Invalid username or password';}?><html><body><?php echo $msg; ?><form>...</form></body></html>
そのようなコードは一般的です。変數(shù)を使用してステータス メッセージを表示するには制限があります。これらをリダイレクト経由で送信することはできません (GET 変數(shù)として次のスクリプトに伝播しない限り、これは非常に愚かです)。大規(guī)模なスクリプトでは、複數(shù)のメッセージなどが存在する可能性があります。
最良の方法は、(同じページ上にある場合でも) セッションを使用してメッセージを伝達することです。このためには、すべてのページに session_start が必要です。
function set_flash($msg){ $_SESSION['message'] = $msg;}function get_flash(){ $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg;}
そしてスクリプト內(nèi):
<?phpif($wrong_username || $wrong_password){ set_flash('Invalid username or password');}?><html><body>Status is : <?php echo get_flash(); ?><form>...</form></body></html>
function add_to_cart($item_id , $qty){ $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 );
単一の項目を追加する場合は、上記の関數(shù)を使用します。複數(shù)のアイテムを追加する場合、別の関數(shù)を作成しますか?いいえ。さまざまな種類のパラメータを受け取れるように関數(shù)を柔軟にするだけです。詳しく見てみましょう:
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) );
これで、同じ関數(shù)が異なる種類の出力を受け入れることができるようになりました。上記の內(nèi)容を多くの場所に適用すると、コードの機敏性が高まります。
なぜこのヒントが、php のヒントに関する非常に多くのブログ投稿から省略されているのか不思議です。
これで多くの問題が回避されます。例を見てみましょう:
クラスファイル super_class.php
<?phpecho "Hello";//Now dont close this tag
今度は、index.php
<?phpclass super_class{ function super_function() { //super code }}?>//super extra character after the closing tag
そして、Headers selected are selected エラーが表示されます。なぜ ?なぜなら、「スーパー余分な文字」がエコーされ、すべてのヘッダーがそれに伴って行われたからです。デバッグを開始します。非常に余分なスペースを見つけるのに何時間も無駄にする必要があるかもしれません。
したがって、終了タグを省略する習慣をつけましょう:
require_once('super_class.php');//echo an image or pdf , or set the cookies or session data
その方が良いです。
これは出力バッファリングと呼ばれます。次のようにさまざまな関數(shù)からコンテンツをエコーし??てきたとします。
<?phpclass super_class{ function super_function() { //super code }}//No closing tag
そのようにする代わりに、まずすべての出力を 1 か所に集めます。関數(shù)の変數(shù)內(nèi)に保存することも、ob_start と ob_end_clean を使用することもできます。これで、次のようになります
function print_header(){ echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){ echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){ echo "I is : $i <br />';}print_footer();
それでは、なぜ出力バッファリングを行う必要があるのですか:
Lets echo some xml.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataecho $xml;
Works fine. But it needs some improvement.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml;
Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.
Similarly for javascript , css , jpg image , png image :
Javascript
header("content-type: application/x-javascript");echo "var a = 10";
CSS
header("content-type: text/css");echo "#div id { background:#000; }";
Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.
$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: <br />". 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 , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.
Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.
Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.
$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');
Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.
Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.
Use apache mod_gzip/mod_deflate to compress content via the .htaccess file.
There are times when some javascript code is generated dynamically from php.
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = '';foreach($images as $image){$js_code .= "'$image' ,";}$js_code = 'var images = [' . $js_code . ']; ';echo $js_code;//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];
Be smart. use json_encode :
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png');$js_code = 'var images = ' . json_encode($images);echo $js_code;//Output is : var images = ["myself.png","friends.png","colleagues.png"]
Isn't that neat ?
Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.
Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.
$contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents);
That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :
So its better to make everything clear before writing out to a file.
$contents = "All the content";$dir = '/var/www/project';$file_path = $dir . "/content.txt";if(is_writable($dir)){ file_put_contents($file_path , $contents);}else{ die("Directory $dir is not writable, or does not exist. Please check");}
By doing this you get the accurate information that where is a file write failing and why
When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.
// Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755);
if($_POST['submit'] == 'Save'){ //Save the things}
The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){ //Save the things}
Now you are free from the value the submit button
//Delay for some timefunction delay(){ $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";}
Instead use static variables as :
//Delay for some timefunction delay(){ static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />";}
Some simple examples are :
$_SESSION['username'] = $username;$username = $_SESSION['username'];
But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.
Hence use application specific keys with wrapper functions :
define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){ $k = APP_ID . '.' . $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false;}//Function set the session variablefunction session_set($key , $value){ $k = APP_ID . '.' . $key; $_SESSION[$k] = $value; return true;}
So you have a lot of utility functions in a file like :
function utility_a(){ //This function does a utility thing like string processing}function utility_b(){ //This function does nother utility thing like database processing}function utility_c(){ //This function is ...}
And you use the function throughout your application freely. You may want to wrap them into a class as static functions :
class Utility{ public static function utility_a() { } public static function utility_b() { } public static function utility_c() { }}//and call them as $a = Utility::utility_a();$b = Utility::utility_b();
One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.
if($a == true) $a_count++;
Its absolutely a WASTE.
Write
if($a == true){ $a_count++;}
Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.
Lets say you want to trim all elements of an array. Newbies do it like this :
foreach($arr as $c => $v){ $arr[$c] = trim($v);}
But it can more cleaner with array_map :
$arr = array_map('trim' , $arr);
This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.
Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters.
The php filter extension provides simple way to validate or check values as being a valid 'something'.
$amount = intval( $_GET['amount'] );$rate = (int) $_GET['rate'];
Its a good habit.
set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose
Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :
$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ?
The above thing is common when importing a csv file or exporting table to a csv file
Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.
Consider passing them by reference , or storing them in a class variable :
$a = get_large_array();pass_to_function(&$a);
by doing this the same variable (and not its copy) will be available to the function. Check documentation
class A{ function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a }}
unset them as soon as possible , so that memory is freed and rest of the script can relax.
Here is a simple demonstration of how assign by reference can save memory in some cases
<?phpini_set('display_errors' , true);error_reporting(E_ALL);$a = array();for($i = 0; $i < 100000 ; $i++){ $a[$i] = 'A'.$i;}echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />';
The output on a typical php 5.4 machine is :
Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864
So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.
Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :
function add_to_cart(){ $db = new Database(); $db->query("INSERT INTO cart .....");}function empty_cart(){ $db = new Database(); $db->query("DELETE FROM cart .....");}
Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.
Use the singleton pattern for special cases like database connection.
$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";$db->query($query); //call to mysqli_query()
The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:
Solution: ActiveRecord
It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.
A very simple example of an activerecord insert function can be like this :
function insert_record($table_name , $data){ foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query);}//data to be inserted in database$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);//perform the INSERT queryinsert_record('users' , $data);
The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).
This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.
Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.
Benefits :
File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.
Storing session in database makes many other things easier like:
Quick example :
<head> <base href="http://www.domain.com/store/"></head><body> <img src="happy.jpg" /></body></html>
The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.
Lets take an example
www.domain.com/store/home.php www.domain.com/store/products/ipad.php
In home.php the following can be written :
<a href="home.php">Home</a><a href="products/ipad.php">Ipad</a>
But in ipad.php the links have to be like this :
<a href="../home.php">Home</a><a href="ipad.php">Ipad</a>
This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.
Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php
error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing.
ini_set('display_errors', 1);error_reporting(~E_NOTICE & ~E_STRICT);
On production , the display should be disabled.
ini_set('display_errors', 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.
After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.
ini_set('log_errors' , '1');ini_set('error_log' , '/path/to/errors.txt');ini_set('display_errors' , 0);error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
Note :
1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there.
2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors.
3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).
4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched.
5. Dont set error_reporting to 0. It will not log anything then.
Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.
Set 'display_errors=On' in php.ini on development machine
On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page.
Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.
Set 'display_errors=Off' in php.ini on production machine
Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.
The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.
On a 64 bit machine you can see such output.
$ php -aInteractive shellphp > echo strtotime("0000-00-00 00:00:00");-62170005200php > echo strtotime('1000-01-30');-30607739600php > echo strtotime('2100-01-30');4104930600
But on a 32 bit machine all of them would give bool(false). Check here for more.
What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.
If you are limiting the maximum run-time of a script , by doing this :
set_time_limit(30);//Rest of the code
It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit.
So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.
system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.
A better solution :
/** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec*/function terminal($command){ //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var);}terminal('ls');
The above function will execute the shell command using whichever function is available , keeping your code consistent.
Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.
Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.
Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.
An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.
Few popular libraries are :
If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.
Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.
The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.
They contain user feedback, expert advice and useful code snippets. So check them out.
The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!
Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.
The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more
1. Codeigniter 2. WordPress 3. Joomla CMS
すでに Windows で開発している場合は、Linux を試してみるとよいでしょう。私のお気に入りはubuntuです。これは単なる意見ではありますが、それでも開発には Linux の方がはるかに優(yōu)れた環(huán)境であると強く感じています。
Php アプリケーションは主に Linux (LAMP) 環(huán)境にデプロイされます。したがって、同様の環(huán)境で開発することは、堅牢なアプリケーションをより速く作成するのに役立ちます。
ほとんどの開発ツールは、Ubuntu の synaptic パッケージ マネージャーから非常に簡単にインストールできます。さらに、セットアップと実行に必要な設(shè)定はほとんどありません。そして最も素晴らしいのは、それらはすべて無料であるということです。
脫衣畫像を無料で
リアルなヌード寫真を作成する AI 搭載アプリ
寫真から衣服を削除するオンライン AI ツール。
AI衣類リムーバー
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。
使いやすく無料のコードエディター
中國語版、とても使いやすい
強力な PHP 統(tǒng)合開発環(huán)境
ビジュアル Web 開発ツール
神レベルのコード編集ソフト(SublimeText3)
tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole
PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認します。
PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場合にのみ使用されます。
PHPで基本的な數(shù)學操作を使用する方法は次のとおりです。1。追加標識は、整數(shù)と浮動小數(shù)點數(shù)をサポートし、変數(shù)にも使用できます。文字列番號は自動的に変換されますが、依存関係には推奨されません。 2。減算標識の使用 - 標識、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標識を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標識を使用し、結(jié)果は浮動小數(shù)點數(shù)である可能性があることに注意してください。 5.モジュラス標識を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負の數(shù)を処理する場合、殘りの兆候は配當と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。
はい、PHPは、特定の拡張機能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。
postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests.
PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions
tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset.