PHP Wisdome

PHP Pearls below … enjoy. Security/safety first

Make PHP.INI Recursive

Php.ini files are not recursive, and can override the global php directives in the same folder only, not the sub-folders. However, htaccess files are recursive. To make php.ini recursive, you can set the path to php.ini in one master htaccess by suPHP_ConfigPath, often in same folder as the php.ini:

In .htaccess file

suPHP_ConfigPath /home/user/public_html

In php.ini file in the folder stated in the suPHP of htaccess write the needed directives you need to be recursive, for example setting timezone or limits for upload file size, memory, and execution times. See

date.timezone = "America/Los_Angeles"
upload_max_filesize = "15M"
post_max_size = "15M"
memory_limit = "128M"
max_execution_time = "30"

To keep things compatible between Linux and Windows OS, NEVER use capital letters in file or folder names.

Test your server for $GLOBALS array following before/during coding. The $GLOBALS array includes almost everything, including variables you made in your script, and automatically generated variables, arrays, and objects, which include $_REQUESTS (i.e. $_POST and $_GET arrays), arrays, objects, $_SERVER variables, and more. Each server may be a bit different based on default settings in php.ini and operating system.

 echo '<p><hr>==== START DEBUG -- $GLOBALS ARRAY ====<pre>';
 echo '</pre>==== END DEBUG ====</p><hr>';

Re-assign SERVER and REQUEST/POST/GET Predefined Variables

The automatically generated or “predefined” variables include those in the arrays $_REQUEST, are made on the fly by the PHP engine. Don't use them in this form! Say what? Yes, don't use things like echo $_POST['form_input_name'], instead set your own variable and set it to the predefined variable you need, at the beginning of your code. But why? Because if any predefined variables change, either in the html/client code or server environment, you can quickly adapt your script. Otherwise you have to go through your script pages one by one and change each manually.

//Hard to maintain/adapt code, specially for big complicated scripts
  echo $_POST['form_input_clientname'];  
//Easy to maintain/adapt code on different servers and client templates
  $my_application['client_name'] = $_POST['form_input_clientname'];  
  echo $my_application['client_name'];

Same idea can apply to databases, table and column names, etc. Re-assign names that occur outside your volition in one place, and re-use as you see fit. Good luck :-)

This can be a ball of wax if you don't understand it well. See PHP include or require.

Another ball of wax. See php_variable and function scope.


Comment by Will Blackamoor

To anyone watching this video, here's a few short words to the wise:

1. NEVER EMBED PHP CODE DIRECTLY INTO HTML! that is the work of an amateur. It's useful to learn it this way, i get it. we all learned like this, but it would be better in my opinion to teach the concepts of templating first, and the separation of logic from the view and the data. Do not fall into the traditional pitfall of MVC either. Instead, look at MVC and think what would make it better. How can you make MVC faster, and more decoupled? Should you serve static html and fetch data from ajax(YES YOU SHOULD AS MUCH AS POSSIBLE)

2. Never use double quotes in php unless it is inside of a single quoted string. single quoted strings are also processed faster by the php interpreter. Don't ask why, just don't do it, ever

3. Never use the heredoc syntax.

4. Don't use PHP to render html. Use php to build a data model then inject it into an html template.

5. Don't use multiple echoes. build your html content in a single string with concatenation, then echo it once you've reached the end of your html document.

6. (int) is a shorter way of typecasting a variable to an integer.

7. Never use mysql_* functions to connect to a mysql database. google will tell you why.

8. Never concatenate database queries with user supplied variables.

9. don't use & to create copies (references) to your variables. I'm sure there was a time when this made sense but that time has come and gone. in my opinion, referencing variables in this way is a form of cargo cult programming. The only real useful application for it is modifying a global variable from within the scope of a function. this is a lazy way to program, use return to return values instead.

10. remember the reference manual and keep it holy. if you plan on being a php programmer, you need to bookmark the php reference manual. the more you learn, the more you will understand, until you are doing things even you didn't know you could do.

11. when checking if a string equals a certain value, with multiple outcomes, don't use conditional if's. use a switch instead, like he teaches in this video.

12. i have been programming for years, and have never used a while loop. use a for loop. its superior. use foreach for arrays.

13. the guy in the video should have used the modulus to detect the last iteration of the for loop instead of what he did.

if($i %20 == 0){ }

14. don't use outdated array syntax. instead of using old outdated php array syntax array('foo','bar') use ['foo','bar'] short array syntax.

15. never roll your own password hashing algorithm. use php's built in password_hash() and password_verify() functions.

16. never, ever , EVER use Wordpress to build your website. Just don't do it.

17. sanitize all user data

18. learn a framework. i recommend slim. its so easy a caveman can do it.

A database is a fundamental component for most web applications. If you’re using PHP, you’re probably using MySQL–an integral part of the LAMP stack.

PHP is relatively easy and most new developers can write functional code within a few hours. However, building a solid, dependable database takes time and expertise. Here are ten of the worst MySQL mistakes I’ve made (some apply to any language/database)…

1. Using MyISAM rather than InnoDB

MySQL has a number of database engines, but you’re most likely to encounter MyISAM and InnoDB.

MyISAM is used by default. However, unless you’re creating a very simple or experimental database, it’s almost certainly the wrong choice! MyISAM doesn’t support foreign key constraints or transactions, which are essential for data integrity. In addition, the whole table is locked whenever a record is inserted or updated; this causes a detrimental effect on performance as usage grows.

The solution is simple: use InnoDB.

2. Using PHP’s mysql functions

PHP has provided MySQL library functions since day one (or near as makes no difference). Many applications rely on mysql_connect, mysql_query, mysql_fetch_assoc, etc. but the PHP manual states:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.

mysqli, or the MySQL improved extension, has several advantages:

an (optional) object-oriented interface prepared statements (which help prevent SQL-injection attacks and increase performance) multiple statements and transaction support Alternatively, you should consider PDO if you want to support multiple databases.

3. Not sanitizing user input

This should probably be #1: never trust user input. Validate every string using server-side PHP — don’t rely on JavaScript. The simplest SQL injection attacks depend on code such as:

$username = $_POST["name"];
$password = $_POST["password"];
$sql = "SELECT userid FROM usertable WHERE username='$username' AND password='$password';";
// run query...
// This can be cracked by entering “admin'; --” in the username field. The SQL string will equate to:
//SELECT userid FROM usertable WHERE username='admin';
// The devious cracker can log in as “admin”; they need not know the password because it’s commented out of the SQL.

4. Not using UTF-8

Those of us in the US, UK, and Australia rarely consider languages other than English. We happily complete our masterpiece only to find it cannot be used elsewhere.

UTF-8 solves many internationalization issues. Although it won’t be properly supported in PHP until version 6.0, there’s little to prevent you setting MySQL character sets to UTF-8.

5. Favoring PHP over SQL

When you’re new to MySQL, it’s tempting to solve problems in the language you know. That can lead to unnecessary and slower code. For example, rather than using MySQL’s native AVG() function, you use a PHP loop to calculate an average by summing all values in a record-set.

Watch out also for SQL queries within PHP loops. Normally, it’s more effective to run a query then loop through the results.

In general, utilize the strengths of your database when analyzing data. A little SQL knowledge goes a long way.

6. Not optimizing your queries

99% of PHP performance problems will be caused by the database, and a single bad SQL query can play havoc with your web application. MySQL’s EXPLAIN statement, the Query Profiler, and many other tools can help you find that rogue SELECT.

7. Using the wrong data types

MySQL offers a range of numeric, string, and time data types. If you’re storing a date, use a DATE or DATETIME field. Using an INTEGER or STRING can make SQL queries more complicated, if not impossible.

It’s often tempting to invent your own data formats; for example, storing serialized PHP objects in string. Database management may be easier, but MySQL will become a dumb data store and it may lead to problems later.

8. Using * in SELECT queries

Never use * to return all columns in a table–it’s lazy. You should only extract the data you need. Even if you require every field, your tables will inevitably change.

9. Under- or over-indexing

As a general rule of thumb, indexes should be applied to any column named in the WHERE clause of a SELECT query.

For example, assume we have a usertable with a numeric ID (the primary key) and an email address. During log on, MySQL must locate the correct ID by searching for an email. With an index, MySQL can use a fast search algorithm to locate the email almost instantly. Without an index, MySQL must check every record in sequence until the address is found.

It’s tempting to add indexes to every column, however, they are regenerated during every table INSERT or UPDATE. That can hit performance; only add indexes when necessary.

10. Forgetting to back up

It may be rare, but databases fail. Hard disks can stop. Servers can explode. Web hosts can go bankrupt. Losing your MySQL data is catastrophic, so ensure you have automated backups or replication in place.

11. Bonus mistake: not considering other databases!

MySQL may be the most widely used database for PHP developers, but it’s not the only option. PostgreSQL and Firebird are its closest competitors; both are open source and not controlled by a corporation. Microsoft provide SQL Server Express and Oracle supply 10g Express; both are free versions of the bigger enterprise editions. Even SQLite may be a viable alternative for smaller or embedded applications.

Have I missed your worst MySQL mistakes?