text: -- phpMyAdmin SQL Dump
  -- version 4.2.7.1
  -- http://www.phpmyadmin.net
  --
  -- Host: localhost:3306
  -- Generation Time: Feb 02, 2015 at 05:07 PM
  -- Server version: 5.5.39
  -- PHP Version: 5.4.32
  
  SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
  SET time_zone = "+00:00";
  
  
  /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
  /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
  /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
  /*!40101 SET NAMES utf8 */;
  
  --
  -- Database: `weblog`
  --
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `blog`
  --
  
  CREATE TABLE IF NOT EXISTS `blog` (
  `blog_id` smallint(5) unsigned NOT NULL,
    `user_id` smallint(6) NOT NULL,
    `blog_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    `blog_content` longtext NOT NULL,
    `blog_title` varchar(100) NOT NULL,
    `blog_img` varchar(64) NOT NULL,
    `cat_id` tinyint(3) unsigned NOT NULL,
    `tag_id` tinyint(3) unsigned NOT NULL,
    `user_name` varchar(32) NOT NULL,
    `comment_status` varchar(20) NOT NULL DEFAULT 'open',
    `blog_type` varchar(20) NOT NULL DEFAULT 'post',
    `blog_mime_type` varchar(100) NOT NULL DEFAULT '',
    `blog_like` smallint(6) NOT NULL,
    `blog_read` smallint(5) unsigned NOT NULL,
    `comment_count` tinyint(4) NOT NULL DEFAULT '0'
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  
  --
  -- Dumping data for table `blog`
  --
  
  INSERT INTO `blog` (`blog_id`, `user_id`, `blog_date`, `blog_content`, `blog_title`, `blog_img`, `cat_id`, `tag_id`, `user_name`, `comment_status`, `blog_type`, `blog_mime_type`, `blog_like`, `blog_read`, `comment_count`) VALUES
  (1, 1, '2013-12-18 18:53:49', '<p><strong>Introduction</strong></p>\r\n<p>PHP is growing up fast. There has been a major push from the folks at Zend (the company that maintains PHP), and this focuses on two major concerns; security, and the object oriented aspects of the language. We''ve come a long way from PHP 4, which introduced a very simple and shaky object oriented interface for developers to play with. But PHP 5 changed that, and with every increment of the PHP 5 version, we are being given a great deal more functionality, as well as a new level of maturity.</p>\r\n<p>What''s new? Let''s check out a few of the new features.</p>\r\n<p><strong>Traits</strong></p>\r\n<p>Traits have been added to PHP for a very simple reason: PHP does not support multiple inheritance. Simply put, a class cannot extends more than on class at a time. This becomes laborious when you need functionality declared in two different classes that are used by other classes as well, and the result is that you would have to repeat code in order to get the job done without tangling yourself up in a mist of cobwebs.</p>\r\n<p>Enter traits. These allow us to declare a type of class that contains methods that can be reused. Better still, their methods can be directly injected into any class you use, and you can use multiple traits in the same class. Let''s look at a simple Hello World example.</p>\r\n\r\n<pre class="brush:js">\r\ntrait SayHello {\r\n    private function hello() {\r\n        return "Hello ";\r\n    }\r\n\r\n    private function world() {\r\n        return "World";\r\n    }\r\n}\r\n\r\ntrait Talk {\r\n    private function speak() {\r\n        echo $this->hello() . $this->world();\r\n    }\r\n}\r\n\r\nclass HelloWorld {\r\n    use SayHello;\r\n    use Talk;\r\n\r\n    public function __construct() {\r\n        $this->speak();\r\n    }\r\n}\r\n\r\n$message = new HelloWorld(); // returns "Hello World";\r\n</pre>\r\n \r\n<p>As can be seen in the example above, the traits ''Hello'' and ''Speak'' has methods (functions) that automatically become part of the class ''HelloWorld''. I was even able to make the methods ''hello'', ''world'', and ''speak'' private. As you know, a private method can only be called from the class it is declared in, but here, because we are using traits, this is allowed. PHP treats the methods in the traits as methods in the class using the traits. Put more simply, methods in a trait are included in the class using the methods. This gives you a lot of flexibility, as you can see.</p>\r\n \r\n<p><strong>Short Array Syntax</strong></p>\r\n<p>You now have a short array syntax available, and the idea is very simple. Consider the array:</p>\r\n \r\n<pre class="brush:js">\r\n$cars = array(''Porsche'', ''Ferrari'', ''Volkswagen'');\r\n \r\n// You now have the option of using the method in the same way \r\n// as Javascript''s literal array notation:\r\n \r\n$cars = [''Porsche'', ''Ferrari'', ''Volkswagen'']; \r\n \r\n// And for an associative array:\r\n \r\n$cars = [''cheap'' => ''Volkswagen'', ''expensive'' => ''Ferrari'']; \r\n</pre> \r\n \r\n<p><strong>Array Dereferencing</strong></p>\r\n<p>Consider the following example:</p>\r\n \r\n<pre class="brush:js">\r\n$string = ''this,is,a,string''; \r\n \r\n// Suppose we want to find the value of the second part \r\n// of that string. \r\n// Before PHP 5.4, we would have to say: \r\n \r\n$explode = explode(",", $string);\r\n$second = $explode[1]; // $second now has a value of ''is''\r\n \r\n// But this is no longer needed: \r\n \r\n$second = explode(",", $string)[1]; \r\n// $second now has a value of ''is''\r\n</pre>\r\n\r\n \r\n<p>I''m a realist, and realistically you cannot be sure that the string has more than one part (or any parts at all, but I''m assuming you''ve already checked for that), and you cannot be sure that part is not empty (I''m assuming you checked that out too). I would argue this might be something - if not used correctly - that could lead to horrible error messages (or functionality inconsistencies) popping up. Be aware when using them. </p>\r\n \r\n<p><strong>Anonymous Functions Now Support $this</strong></p>\r\n<p>Also known as closures, anonymous function now support $this. Before PHP 5.4, this could be done in a rather clumsy way: </p>\r\n \r\n<pre class="brush:js">\r\nfunction anonymous()\r\n\r\n$that = $this; \r\n// $that now is $this return function() \r\n// use ($that) { $that->hello(); }; }{\r\n</pre>\r\n \r\n<p>Now, however, we can say something like: </p>\r\n<pre class="brush:js">\r\n\r\nclass One\r\n{\r\n    function hello() {\r\n        echo ''Hello World!'';\r\n    }\r\n\r\n    function anonymous()\r\n    {\r\n        return function() {\r\n            $this->hello(); // $this wasn''t possible before\r\n        };\r\n    }\r\n}\r\n\r\nclass Two\r\n{\r\n    function __construct(One $o) // object of class One typehint\r\n    {\r\n        $x = $o->anonymous(); // get One::hello()\r\n        $x(); // execute One::hello()\r\n    }\r\n}\r\nnew Two(new One); // return ''Hello World!'' \r\n</pre>\r\n\r\n\r\n\r\n<p><strong>PHP Short Tag Is Always On</strong></p>\r\n<p>Previously, the PHP short tag (<?=) could be turned on and off in your php.ini file. This tag is now always active, regardless of the php.ini setting. </p>\r\n \r\n<p><strong>Binary Numbers</strong></p>\r\n<p>Binary numbers are now supported. Integers can be assigned in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation, and the optional sign (+ or -).</p>\r\n \r\n<p><strong>Callable Typehinting</strong></p>\r\n<p>PHP is, by definition, a weakly typed language. Typehinting was incorporated in order to make PHP a stronger typed language, however, types could (until PHP5.4) only be objects or arrays. Strings and Ints are not yet supported, but we now can perform callable typehinting. </p>\r\n<pre class="brush:js">\r\nfunction some_function(callable $a)\r\n{\r\n    return $a();\r\n}\r\n\r\nfunction some_callback_function(){return ''Hello World!'';}\r\n\r\nclass Hello{static function hi(){return ''Hello World!'';}}\r\nclass Hi{function hello(){return ''Hello World!'';}}\r\n\r\necho some_function(function(){return ''Hello World!'';}); // anonymous function\r\necho some_function(''some_callback_function''); // callback function\r\necho some_function([''Hello'', ''hi'']); // class name, static method\r\necho some_function([(new Hi), ''hello'']); // class object, method name\r\n</pre> \r\n<p><strong>High Precision Timer</strong></p>\r\n<p>PHP 5.4 introduces a timer to the session array, which can be used to measure things like script execution, as below: </p>\r\n \r\n<pre class="brush:js">\r\necho ''Execution time:'',round(microtime(true)-$_SERVER\r\n      [''REQUEST_TIME_FLOAT''], 2) . '' seconds''; \r\n</pre>\r\n \r\n<p><strong>CLI Webserver</strong></p>\r\n<p>PHP 5.4 gives us a simple test server, which is started from the command line. This is for development only, and should never be used in production, but the idea is that it is simple to test PHP applications without having to setup things like virtual hosts. </p>\r\n \r\n<p>To use the built in server, simply navigate to the directory containing your PHP file or index.php file of your application, and run: </p>\r\n \r\n<pre class="brush:js">\r\n$ php -S 0.0.0.0:8080 -t {filename}.php \r\n</pre>\r\n \r\n<p>Then open the url http://0.0.0.0:8080 in your browser and watch your application run. </p>\r\n \r\n<p><strong>Conclusion</strong></p>\r\n<p>PHP 5.4 has added a lot of functionality to the language. As with all new things, however, we must make sure we fully understand the implications of the features we are using properly, and while that has not been the focus of this article, please remember to go to php.net and make sure you are comfortable with what you are doing. </p>\r\n\r\nby: Marc Plotz\r\n', 'Whats New in PHP 5.4', 'mp.jpg', 1, 1, 'Marc Plotz', 'open', 'post', '', 0, 20, 0),
  (2, 1, '2013-12-18 18:53:49', '<p>There are a number of good practises that you should follow when developing web applications in PHP. Most of these are extremely easy to pick up and some of them will even apply to web application development in general. </p>\r\n\r\n<p><strong>1. Redirect after a successful POST request. </strong></p>\r\n<p>This is not PHP-specific. To avoid a situation where the user refreshes their browser and submits the same form data twice, you should always use the Post/Redirect/Get (PRG) pattern. A basic example of this: </p>\r\n\r\n<pre class="brush:js">\r\n \r\n//Process form data here.\r\n \r\n//If the form submission was successful.\r\nif($success){\r\n    //Redirect the user.\r\n    header(''Location: page.php?msg=success'');\r\n    exit\r\n}\r\n</pre>\r\n\r\n<p><strong>2. Don’t use the mysql_* functions. </strong></p>\r\n<p>As of PHP 5.5, the mysql functions have been officially deprecated. According to the official PHP website, the default MySQL extension will be completely removed in the future. If that doesn’t persuade you to find an alternative, then you should also consider the fact that it lacks support for a number of MySQL features. Most notably: <br>\r\n•	Prepared statements.<br>\r\n•	Transactions. .<br>\r\n•	Stored procedures. .<br>\r\n•	Asynchronous queries. .<br>\r\n•	Multiple statements. .<br>\r\nThe fact is, this ageing extension was built for MySQL version 3.23. Since then, very little has actually been added in the way of features. To put all of this into perspective, the current MySQL version is at 5.6, with 3.23 having been released back in 1999! </p>\r\n\r\n<p>OK, so what do I use instead?\r\n<p>Two good alternatives are PDO and MySQLi. Personally, I prefer using PDO  as it provides a data-access abstraction layer, which basically means that you can use the same functions to access other databases as well (PostgreSQL, SQLite, etc). </p>\r\n\r\n<p><strong>3. Do not close your PHP tags.</strong></p>\r\n<p>A lot of developers will (often religiously) place a closing PHP tag at the end of their files like so: </p>\r\n\r\n<p><pre class="brush:js">\r\n&lt?php\r\n class MyClass{\r\n    public function test(){\r\n        //do something, etc.\r\n    }\r\n}\r\n?&gt\r\n</pre>\r\n</p>\r\n\r\n<p>The problem with this is that it can introduce whitespace or newline characters if the developer is not careful. This can cause headaches later on when headers are interrupted or whitespace characters inexplicably appear in the output (this actually happened to a co-worker of mine last week). </p>\r\n<p>Ok, so what do I do?\r\nThis is perfectly acceptable: </p>\r\n\r\n<pre class="brush:js">\r\n&lt?php\r\nclass MyClass{\r\n    public function test(){\r\n        //do something, etc.\r\n    }\r\n}\r\n/* never close php tag ...\r\n</pre>\r\n\r\n\r\n<p>To be honest, the only time you should really close your PHP tags is when you are templating with PHP and HTML: </p>\r\n\r\n<pre class="brush:js">\r\n&lt?php echo $title; ?&gt\r\n&ltp&gt&lt?php echo $description; ?&gt&lt/p&gt</pre>\r\n\r\n\r\n<p><strong>4. Guard against XSS! </strong></p>\r\n<p>XSS (aka Cross-site scripting) is a vulnerability that allows attackers to execute client-side code on your website. For example: If I enter some JavaScript into a comment form and you display that comment without sanitizing it, the code in question will execute whenever a user loads the page. To defend against this type of vulnerability, you should sanitize user-submitted data before it is printed out onto the page. To achieve this, you can use the function htmlspecialchars: </p>\r\n\r\n<code>echo htmlspecialchars($userComment, ENT_QUOTES, ''utf-8'');</code>\r\n\r\n<p>This function will convert special characters into their relevant HTML entities so that they are safe for display. </p>\r\n\r\n<p><strong>5. Don’t echo out HTML! </strong></p>\r\n<p>This is a horrible practise! It looks messy, your IDE will fail to highlight the relevant HTML elements and designers who aren’t confident with PHP will find it difficult to edit or add new features. Instead, you should do something similar to the example that was shown in point three. </p>\r\n\r\n<p>6. Separate your logic from your output! </strong></p>\r\n<p>There is nothing more daunting than trying to work on a sprawling code base where the logic is intertwined with the output. To separate your logic from your presentation, you can use an MVC framework such as Laravel or a templating engine such as Twig. There are a lot of different options out there, so be sure to shop around. At the very least, you should always try and enforce this principle while you are building your web apps. </p>\r\n\r\n<p><strong>7. Learn what DRY is. </strong></p>\r\n<p>DRY stands for Don’t Repeat Yourself. i.e. You should avoid a situation where you are repeating the exact same code. This can be done via the usage of includes, functions and classes. For example, if I have a piece of code that calculates a person’s age, I can create a function like so: </p>\r\n<pre class="brush:js">\r\n \r\nfunction calculateAge($dateOfBirth){\r\n    $birthday = new DateTime($dateOfBirth);\r\n    $interval = $birthday->diff(new DateTime);\r\n    return $interval->y;\r\n} \r\n</pre>\r\n<p>Now, whenever I want to calculate a user’s age, I can just call the function above; as opposed to repeating the same logic. This is advantageous because: </p>\r\n1.	My code base is smaller as a result.\r\n2.	If I need to tweak the logic, I can edit the calculateAge function, as opposed to trawling through my code and editing several redundant instances. \r\n\r\n<p><strong>8. Never trust your users! </strong></p>\r\n<p>As highlighted in point four, users can be malicious. This means that you will have to build your web applications with the assumption that your visitors will actively attempt to exploit any vulnerabilities that they can find in your code. This frame of mind is needed, especially when you are developing sites that are open to the general public. In some cases, these vulnerabilities might be discovered by vulnerability scanners or automated web crawlers. </p>\r\n\r\n<p><strong>9. Do not run queries inside loops! </strong></p>\r\n<p>Running a query inside a large loop can be extremely expensive. In a lot of cases, the loop will grow in size, leading to more and more queries. This can lead to slow-loading web pages and a database that is under far more strain that it should be. Most of the time, these “looped queries” are used because the developer in question hasn’t learned about the importance of SQL joins. </p>\r\n\r\n<p><strong>10. Hash user passwords! </strong></p>\r\n<p>User passwords should be hashed, not stored in plain text or base encoded (seriously, I’ve actually encountered this before). A hashing function is a one way street. Once the plain text password has been passed through it, there is no way of getting it back (hence the reason we use the term “hashing”, not “encryption”). If you are using PHP >= 5.5, you should use the function password_hash. If you’re stuck on an earlier version, then you can make use of the password_combat library on Github.\r\n<p>NOTE! Functions such as md5 and sha1 are not fit for this purpose! A good password hashing function should be slow to the point where trying to crack a hash using rainbow tables etc is impracticable! </p>\r\n\r\n<p><strong>11. Use prepared statements! </strong></p>\r\n<p>If you look back at point two, you’ll see that I recommended using PDO over the mysql_*functions. One of the major advantages of using PDO is that it allows you to avail of prepared statements. In the past, PHP developers were forced to use functions such asmysql_real_escape_string like so: </p>\r\n<pre>\r\n$username = mysql_real_escape_string($username, $connection);\r\n$result = mysql_query("SELECT name FROM users WHERE username = ''$username''");\r\n</pre>\r\n\r\n<p>This function escapes special characters that might interfere with your SQL. i.e. It helps to protect against the scourge of SQL injection. However, what it won’t do is protect you from attacks that do not involve special characters such as x00, n, r, , ‘, ” and x1a. There’s also an issue where not setting the correct charset can render it useless against certain attacks. </p>\r\n<p>Fortunately, SQL injection is no match for prepared statements. With prepared statements, the SQL statement is sent to the server before the data is, thus keeping them independent of one another. This means that the database knows what statement it needs to execute well before any potentially dangerous characters are sent through. Example: </p>\r\n<pre class="brush:js">\r\n//We prepare the SQL statement. At this stage it is sent off to the database server.\r\n$stmt = $db->prepare("SELECT name FROM users WHERE username = :username");\r\n \r\n//We bind our parameters / data.\r\n$stmt->bindParam('':username'', $username);\r\n \r\n//We execute the statement.\r\n$stmt->execute(); </pre>\r\n\r\n\r\n<p>Important note: With the PDO extension, you will need to manually enable the use of “natural” prepared statements. For the purpose of portability, this extension uses emulated prepared statements by default. To switch off emulated prepared statements, you can use the following code: </p> \r\n<pre>$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);</pre>\r\n\r\n<p><strong>12. “or die()” needs to die…</strong></p>\r\n<p>If you’ve decided to completely ignore all of the points about switching to PDO, then I think it is fair to say that you’re probably handling your failed queries like so: </p>\r\n \r\n<pre>mysql_query($sql, $conn) or die(mysql_error($conn));</pre>\r\n\r\n<p>The problem with the above approach is that you cannot catch the error or log it. You also can’t control whether or not it is outputted to the screen. In the eyes of the die function, a development server and a live server are exactly the same thing! It can’t be controlled via ini settings or a site-wide configuration file. </p>\r\n<p>A better approach to this would be to use exceptions, simply because they can be caught or handled: </p>\r\n<pre class="brush:js">\r\n$res = mysql_query($sql, $conn);\r\nif($res === false){\r\n    throw new Exception(mysql_error($conn));\r\n}\r\n</pre>\r\n<p>The exception above can be caught using a TRY block or handled with a custom exception handler. This gives you far more control over how errors are dealt with. Of course, if are using the PDO extension, you could have your SQL errors throw exceptions by default by using the following attribute: </p>\r\n<pre>$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</pre>\r\n\r\n<p><strong>13. Email validation. </strong></p>\r\n<p>Avoid using regular expressions to validate email addresses. The problem with most of the regex examples floating around on the Internet is that they fail to conform to RFC 822 grammar. i.e. They will actually reject valid email addresses. The best approach is to use the filter_var function like so: </p>\r\n<pre class="brush:js">\r\n\r\nif(!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {\r\n    //Email is invalid. Show the user an error message.\r\n}\r\n</pre>\r\n\r\n<p><strong>14. Avoid short tags. </strong></p>\r\n<p>You should avoid using short tags unless you are sure that you will be deploying your code to a server that you can configure yourself. On some shared hosts, you’ll find that short tags are disabled by default and that you don’t have the ability to change any of PHP’s configuration settings. Therefore, in order to ensure some level of portability, you should stick to using </p>\r\n<code>&lt?php as opposed to &lt?</code>. \r\n<p>It might save you a lot of headaches in the future. </p>\r\n\r\n<p><strong>15. Avoid micro-optimizations. </strong></p>\r\n<p>During my time on some of the various help forums, I’ve come across several instances of beginner PHP developers stressing out over insignificant micro-optimizations. For example, you’ll often come across questions such “Does copying variables slow down my application?” </p> \r\n<p>The answer is: It probably won’t matter. If you’ve reached the point where copying variables becomes a performance issue, then you’ve got much bigger problems at hand! Instead, you should follow best practices and focus on writing clean, readable code. Most of these things are so small and insignificant that they will never become an issue. </p>\r\n\r\n<p><strong>16. Learn about database normalization. </strong></p>\r\n<p>Database Normalization is something that all developers should know about, regardless of what language they are using. A bad database design can lead to bad code, simply because the programmer in question may be forced to compensate for the lack of proper structure / design. If you are a web developer, then it is highly probable that you will be forced to create a relational database at some point or another. When that time comes, you’ll be forced to become acquainted with the process of normalizing entities and building relationships. </p>\r\n\r\n<p><strong>17. Be consistent. </strong></p>\r\nConsistency is one of the most important attributes that a programmer can have. Having to rummage through a code base that was written by an inconsistent coder is similar to running through a mine field. Folder structures that are messed up. Classes that have functions that are out of place. CamelCase and underscores used interchangeably throughout the project. It can be a complete mess. </p>\r\n\r\n<p><strong>18. Version control. </strong></p>\r\n<p>It doesn’t matter if your application is a one-page website or a sprawling complex monster; using version control software such as Git is a must in this day and age. </p>\r\n<p>The advantages?<br>\r\n•	You can easily revert to older versions of your application. .<br>\r\n•	It makes it much easier to maintain multiple different versions, allowing you to experiment with certain features. .<br>\r\n•	It helps prevent situations where you overwrite somebody else’s work. .<br>\r\n•	It gives other people the ability to submit changes to your code base. .<br>\r\n•	It can help you figure out what changes led to the introduction of a new bug. </p>\r\n\r\n<p><strong>19. Bytecode caching. </strong></p>\r\n<p>By default, PHP will always execute your code as if it is new (it isn’t a compiled language). On each request, PHP will parse your code and turn it into bytecode so that it can be executed. This will happen, regardless of whether or not your code has been left untouched for months. Obviously, this can be a waste of server resources. </p>\r\n<p>Fortunately, you can easily implement a bytecode cache if you have full control over the server that your application is hosted on. If you’re running PHP 5.5 or higher, you can avail ofOpcache, which is currently built into PHP. If you’re unfortunate enough to be stuck on an older version, you can avail of another bytecode cache called APC. These work by storing the resulting bytecode in memory so that it can be re-used. </p>\r\n<p><strong>20. Learn about common design patterns. </strong></p>\r\n<p>Design patterns are reusable solutions to common problems. Knowing about the ins and outs of proven design patterns can help you speed up the development process. It can also make it easier for other developers to read and understand your code. Fortunately for us, there are plenty of PHP-specific examples on Github. There, you’ll see PHP implementations of patterns such as the Factory Pattern and Dependency Injection. </p>\r\n\r\n<p><strong>21. When in doubt, use UTF-8! </strong></p>\r\n<p>Not sure what charset to use on your webpage? Use UTF-8: \r\n<pre>&ltmeta charset="utf-8"&gt</pre>\r\n<p>Unsure about what encoding to use for your database tables? Use utf8_unicode_ci! Connecting to your database? Well, uh, you get the point: </p>\r\n\r\n<pre>\r\n$db = new PDO(''mysql:host=localhost;dbname=database;charset=utf8'', ''root'', ''''); </pre>\r\n\r\n\r\n<p>Basically, you will need to use UTF-8 throughout your entire application! And remember: A chain is only as strong as its weakest link! Fail to use UTF-8 somewhere in your application and you might end up with garbled strings! </p>\r\n\r\n<p><strong>22. Know about the advantages of using an MVC Framework. </strong></p>\r\n<p>You might not need to use an MVC framework, but you should learn about the advantages of using one. </p>\r\n•	Enforces the separation of concerns design principle. .<br>\r\n•	Can allow for better re-use of code. .<br>\r\n•	A lot of MVC Frameworks come pre-packaged with many helpful utility classes and libraries that help you quickly address common problems such as user authentication and sending emails. This can help you speed up development. .<br>\r\n•	As touched on in point 20: Developers who understand MVC frameworks will find your code easier to understand (as opposed to a custom design that you conjured up yourself). .<br>\r\n<p>There are a lot of great PHP MVC frameworks out there. To name a few: </p>\r\n•	Laravel\r\n•	Yii\r\n•	Symfony\r\n•	CakePHP\r\n•	Zend Framework\r\n•	CodeIgniter\r\n<p>If you’re looking to find out more, you should read this post by Jeff Atwood. </p>\r\n\r\n<p><strong>23. Get a grasp on some of the fundamentals of web application security. </strong></p>\r\n<p>XSS and SQL injection are not the only vulnerabilities that you need to be aware of. The security risks posed by CSRF and Session Fixation should also be at the forefront of your mind. If you’re new to developing in PHP, you should probably take a look at the official site’s page on Security. There, you’ll find a lot of helpful information about the different types of security vulnerabilities that you will need to take into account while you are developing your applications. Take the issue relating to null bytes as an example, where <code>$_GET[''file''] is “../../etc/passwd”</code>: </p>\r\n\r\n<pre class="brush:js">\r\n$file = $_GET[''file''];\r\nif (file_exists(''/home/wwwrun/''.$file.''.php'')) {\r\n    // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists\r\n    include ''/home/wwwrun/''.$file.''.php'';\r\n    // the file /etc/passwd will be included\r\n}\r\n</pre>\r\n\r\n<p>Here, you can see that an attacker could potentially force your web application to include the/etc/passwd file. </p>\r\n<p>For further reading on web application security, be sure to check out OWASP. </p>\r\n\r\n<p><strong>24. Know what database column types to use. </strong></p>\r\n<p>In the past, I’ve come across multiple instances of developers using incorrect data types. Sometimes, it is a bit disheartening to see a great project being weighed down by bad database-related decisions. </p>\r\n<p>Some will store their price data in a VARCHAR column. Others won’t know the difference between SMALLINT, INT and BIGINT. \r\n<p>Example: Did you know that the 3 in TINYINT (3) has absolutely nothing to do with the storage size of the column? </p>\r\n<p>Did you know that storing dates in a VARCHAR column is completely stupid, and that you won’t be able to avail of the date functions as a result? </p>\r\n<p>Did you know that a BIGINT can be wasteful, simply because it is unlikely that you will ever need to store a number that is as big as 18446744073709551615? Will your text column require you to use TEXT or MEDIUMTEXT? </p>\r\n<p>All of these are questions that can be answered by having a quick read of the manual. \r\nBasically, RTFM! I’ve recently written an article called: MySQL: What columns to use? This will hopefully guide beginner developers in the right direction. </p>\r\n\r\n<p><strong>25. Don’t parse HTML with regular expressions. </strong></p>\r\n<p>Why use regular expressions to parse HTML when you can use a DOM parser such as the Document Object Model? Parsing HTML with regex can be tricky at best and it can ultimately lead to code that is bulky and unmaintainable. What if a newly-added element attribute breaks your code? Just use an XML parser / library like a sane person.\r\n\r\n<p><strong>26. var_dump, don’t echo. </strong></p>\r\n<p>I’ve often come across developers using echo to “debug” their variables, despite the fact that echo will leave out a lot of significant information. var_dump, on the other hand, will tell you what type of variable you are dealing with. It will also help you locate whitespace and newline issues. Run the <p>following example: </p>\r\n\r\n<pre class="brush:js">\r\n$str = ''Hello ''; //Example whitespace issue.\r\necho $str;\r\nvar_dump($str);\r\n// Which one is more useful?\r\n</pre>\r\n\r\n<p><strong>27. Testing your application. </strong></p>\r\n<p>Unit Testing is one of the most popular methods of testing. Basically, it involves breaking your code base down into smaller pieces (typically, functions and object methods) so that you can test them in an isolated fashion. As it stands, PHPUnit is the most popular PHP testing framework. Be sure to have a run through their start-up guide. Doing a few examples and getting your hands dirty will help you understand it better. </p>\r\n<p>For some further reading, be sure to have a look at the Wiki article on Test-driven development.\r\n\r\n<p><strong>28. Storing uploaded images. </strong></p>\r\n<p>Uploaded images should be stored on the file system and then referenced via the database. i.e. Upload the file to your web server and then store the file path of the image in a table column. You should NOT be storing images in your database unless it is completely necessary! Why? .<br>\r\n•	In many cases, you’ll find that database storage is more expensive / limited than file system storage. This is the case with many hosting solutions. <br>\r\n•	It may add an (unnecessary) strain to your database.<br>\r\n•	Accessing an image in a database may be noticeably slower than accessing an image on the file system. <br>\r\n•	The database becomes much larger. i.e. Backups take longer and the complexity of maintaining the database typically increases. <br>\r\n•	High-traffic websites such as Facebook prefer file system storage. <br>\r\n•	You will not be able to take advantage of any cloud storage solutions. <br>\r\n•	No extra coding / processing is needed to access images on a web server. <br>\r\n•	If you store your images in a database, you may lose out on OS-based optimizations such as sendfile. </p>\r\n\r\n<p><strong>29. Re-size your images on upload. </strong></p>\r\n<p>Using PHP to re-size images on-the-fly can be extremely resource intensive. In most cases, you will use more of your CPU and RAM on re-sizing an image than you would on serving a typical PHP web page. To make matters worse, the impact of re-sizing images on-the-fly will worsen with each thumbnail that is being displayed. A more-robust solution is to re-size images as soon as they have been uploaded. i.e. Re-size the image and create one or two differently-sized copies. Disk space is cheap. CPU power and RAM? Not so much. </p>\r\n<p><strong>30. Documentation.</strong></p>\r\n<p>Pick a commenting “style” and then stick with it (see point 17 about being consistent). For example: phpDocumentor is a tool that allows you to automatically generate documentation for your code, provided you stick to their style / syntax: </p>\r\n<pre class="brush:js">\r\n/**\r\n * Description of the function goes here.\r\n * \r\n * @param int $num Small description about this parameter.\r\n * @return boolean Small description about the return value.\r\n */\r\npublic function isOne($num){\r\n    if($num === 1){\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n</pre>\r\n\r\n<p><strong>31. Understand the difference between == and ===.</strong></p>\r\n<p>As a PHP developer, you should definitely take the time to read the official documentation page on comparison operators. Knowing the difference between == and === is vital. Consider the following: </p> \r\n<pre class="brush:js">\r\n$a = 1;\r\n$b = "01";\r\nif($a == $b)\r\n{\r\n    echo ''True!'';\r\n}\r\n</pre>\r\n<p>The above IF statement will equate to true, despite the fact that $b is a string and $a is an integer. This is because of type juggling. Basically, $a and $b are the considered to be equal because PHP will cast $a and $b into integers before making the comparison (in this case, we consider it to be a “loose” comparison). ===, on the other hand, will only equate to true if both variables are equal AND they are of the same type. Run the following piece of code and you’ll find that the output will be “False!” This is because $a and $b are not of the same type: </p>\r\n<pre class="brush:js">\r\n$a = 1; //integer\r\n$b = "01"; //string\r\n//This will equate to FALSE because $a is an int and $b is a string.\r\nif($a === $b){\r\n    echo ''True!'';\r\n} else{\r\n    echo ''False!'';\r\n}\r\n</pre>\r\n<p>It is fair to say that not knowing the difference between == and === will inevitably lead to buggy code. Take the following example / pit-fall: </p>\r\n<pre class="brush:js">\r\n$a = false;\r\n$b = "";\r\nif($a == $b){\r\n    echo ''Both $a and $b are considered to be false!'';\r\n}\r\n</pre>\r\n<p>A while back, I came across an issue where one of our existing cron scripts was throwing false errors. Basically, the script in question was making a HTTP request to a particular URL. After the request was completed, the custom error handler would report that it had failed, despite the fact that we all knew that it was being completed successfully. After digging into the code, I discovered that the person who had wrote the error handler had used a loose comparison like so: </p> \r\n\r\n<pre class="brush:js">\r\n$res = file_get_contents($url);\r\nif($res == false){\r\n    //request failed\r\n}\r\n</pre>\r\n\r\n<p>The problem with the code above is that the request will be considered a failure if the output of the $url is blank (in this case, it was). A message on the documentation page for file_get_contents warns us about this: </p>\r\n<p>This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. </p>\r\n\r\n\r\n<p><strong>32. Object Caching. </strong></p>\r\n<p>In many cases, it can be beneficial to cache the results of expensive database queries by storing them in memory (retrieving data from memory is a lot faster than retrieving data from disk). Think about the following scenario: <br>\r\n•	You own a social networking website. <br>\r\n•	On your home page, you display a list of newly-registered users. <br>\r\n•	Your home page is accessed 500 times per minute. <br>\r\n•	As a result, the database query that selects these users is executed 30,000 times per hour. </p>\r\n<p>It is fair to say that all of this is a bit wasteful, simply because: <br>\r\n1.It is not an important feature. If you think about it: Its only real purpose is to let other users know that the website is active. <br>\r\n2.Visitors aren’t going to care if the list in question is five or ten minutes old. <br>\r\n<p>To cache the result of this query in memory, we could use an object caching system such as Memcached or Redis. Take the following example, which uses PHP’s Memcached Extension: </p>\r\n\r\n<pre class="brush:js">\r\n//Attempt to get the newly-registered list from Memcached.\r\n$userList = $memcached->get(''newly_registered'');\r\n \r\n//If $userList is FALSE, it means that our list doesn''t exist in Memcached.\r\nif($userList === false){\r\n \r\n//Select the last 10 users from our database.\r\n$userList = $this->User->getNewlyRegistered(10);\r\n \r\n//Store the result in Memcached for 5 minutes so that any preceding\r\n//visitors in the next 5 minutes will be able to access it via\r\n    //the cache.\r\n    $memcached->set(''newly_registered'', $userList, time() + 300);\r\n}\r\n \r\nvar_dump($userList);\r\n</pre>\r\n<p>The code above will attempt to retrieve the user list from Memcached. If the list doesn’t exist, it will run the query and then store the result in Memcached for 5 minutes (once the 5 minutes are up, Memcached will evict the data from the cache and Memcached::get will return FALSE again). This means that our database query will only be executed if the key has expired and the data has been automatically “evicted.” i.e. We now run 12 queries per hour instead of 30,000. </p>\r\n\r\n<p><strong>33. HTML does NOT provide validation! </strong></p>\r\n<p>This ties back into my point about not trusting your users! On too many occasions, I’ve come across developers who seem to think that the value of a SELECT element doesn’t need to be validated by the server. </p>\r\n\r\n<pre>\r\n&ltselect name="gender"&gt\r\n    &ltoption value="1"&gtMale&lt/option&gt\r\n    &ltoption value="2"&gtFemale&lt/option&gt\r\n&lt/select&gt\r\n</pre>\r\n\r\n\r\n“The value can only be 1 or 2, r-right?!” Wrong!\r\n<p>A lot of beginner developers seem to be under the impression that the value of a SELECT element can be trusted because it “restricts” the user and forces them to select from a predefined list of values.\r\nUnfortunately, this isn’t the case, as an attacker can easily edit the values of a SELECT element by opening up Firebug or Chrome Developer Tools. \r\nThis goes for hidden form fields as well! What if I were to open up Firebug and change “1” to “Hello”?  \r\nWhat if I were to replace “2” with “3”? \r\nWhat would happen if I modified the value of your hidden input field? How will your application react? </p>\r\n<p>Conclusion: HTML can be edited by anyone. Form values can be tampered with and fields can be deleted with ease. </p>\r\n\r\n<p><strong>34. JavaScript validation is not a substitute for server-side validation! </strong></p>\r\n<p>The amount of web forms that rely on client-side validation is absolutely frightening! What happens if the user decides to disable JavaScript? What happens if an attacker decides to open up Chrome Developer Tools and modify your code? To put it bluntly: JavaScript should be treated in the same respect as HTML. Both are sent to the browser. Both can be modified by the end-user. Neither of them can be trusted. </p>\r\n\r\n<p><strong>35. Learn about error reporting in PHP. </strong></p>\r\n<p>There are number of different types of errors in PHP . Some of the most common ones are: <br>\r\n•	E_ERROR: This is a fatal runtime error. Your application cannot recover from an E_ERROR. Therefore, the script is halted. Example cause: Attempting to call a function that doesn’t exist. <br>\r\n•	E_PARSE: This occurs whenever PHP fails to parse / compile your code. Your script will not run as a result. Example cause: Failing to close your brackets properly. <br>\r\n•	E_WARNING: This is a runtime warning that does not prevent the rest of your application from running. Example: Trying to access a file or URL that doesn’t exist. <br>\r\n•	E_NOTICE: An E_NOTICE occurs whenever PHP encounters something that may indicate an error. Example: Trying to access an array index that doesn’t exist. <br>\r\n•	E_STRICT: Occurs whenever PHP warns you about the future compatibility of your code. Example cause: Using functions or language features that have been deprecated. </p>\r\n\r\n<p>Development Environment</p>\r\n<p>In a development environment, you should display ALL errors. Hiding warnings and notices in a development environment is bad practice, simply because you should be fixing the root causes; not attempting to cover them up! Sweeping “dirt” like this under the rug may lead to the appearance of annoying bugs that are difficult to identify! To display all of the possible PHP errors, you can insert the following directives into your PHP.ini file: </p>\r\n\r\n<pre>\r\ndisplay_errors = On\r\ndisplay_startup_errors = On\r\nerror_reporting = -1\r\nlog_errors = On\r\n</pre>\r\n\r\n<p>If you do not have access to your PHP.ini file, you can place the following piece of code at thetop of your script: \r\nerror_reporting(-1);\r\nini_set("display_errors", 1); </p>\r\n\r\n<p>Production / Live Environment</p>\r\n<p>In a production / live environment, errors should be logged, but not displayed to the end user. Displaying PHP errors in a live environment is not recommended. This is because: <br>\r\n1.	They are not user friendly. <br>\r\n2.	Warnings and notices can break the display / layout of your website. <br>\r\n3.	They can provide an attacker with critical information about the internal workings of your application. </p>\r\n<p>To hide PHP errors, you can insert the following directives into your PHP.ini file: \r\n<pre>\r\ndisplay_errors = Off\r\ndisplay_startup_errors = Off\r\nerror_reporting = E_ALL\r\nlog_errors = On\r\n</pre>\r\n</p>\r\n\r\n\r\n<p>If you do not have access to your PHP.ini file, you can place the following code at the top of your script: <br>\r\nerror_reporting(0); <br>\r\n<br>\r\n<a href="http://thisinterestsme.com/php-best-practises/">Source:This Interst Me</a>\r\n\r\n', 'PHP Best Practises', 'user.jpg', 3, 0, 'TIM', 'open', 'post', '', 0, 17, 0),
  (3, 1, '2013-12-19 01:54:41', '<p>I have posted some information about Standard PHP Library recently. Because SPL is one of my favourite PHP extension I decided to write about another neat feature from this toolbox about iterators. </p>\r\n<p>According to wikipedia:<br>\r\nIn computer programming, an iterator is an object that enables a programmer to traverse a container.\r\nIn SPL we can find a lot of implemented Iterators. Most of them are decorators, so they work with other types of iterators. </p>\r\n\r\n<p><strong>Examples of SPL iterators</strong></p>\r\n<p><strong>ArrayIterator : </strong> with ArrayIterator we can create iterators from array. This is necessary to use with decorators. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(1, 2, 3));\r\n \r\nforeach ($arrayIterator as $element) {\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# 1 2 3\r\n</pre>\r\n<p>Note: in some cases instead of ArrayIterator we can use ArrayObject class, which allows objects work as arrays</p>\r\n\r\n<p><strong>RecursiveArrayIterator :</strong> ArrayIterator has one drawback. It works only with one dimensional arrays. When we want to use multi dimensional arrays, we should use RecursiveArrayIterator. </p>\r\n<p>To iterate through recursive iterator we can use RecursiveIteratorIterator. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$recursiveArrayIterator = new RecursiveArrayIterator(\r\n	array(''a'', array(''b'', array(''c'')), array(''d''))\r\n);\r\n \r\nforeach(new RecursiveIteratorIterator($recursiveArrayIterator) as $element)\r\n{\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# a b c d\r\n</pre>\r\n<p>Note: some other iterators also have Recursive version. You can find them here All of them implement RecursiveIterator interface</p>\r\n\r\n<p><strong>Filter Iterator</strong> : FilterIterator is responsible for filter unwanted values. It is abstract class with abstract method accept(), which should return true when value is valid, false otherwise.</p>\r\n<p>Filter values greather than 3: </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(2, 4, 6)); \r\n \r\nclass GreatherThanThreeFilterIterator extends FilterIterator{	\r\n	public function accept()	{		\r\n		return $this->getInnerIterator()->current() > 3;	\r\n	}\r\n}\r\n \r\nforeach (new GreatherThanThreeFilterIterator($arrayIterator) as $element) {\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# 4 6\r\n</pre>\r\n<p>Note: to get value for filter we have to invoke $this->getInnerIterator()->current() method.</p>\r\n\r\n<p><strong>RegexIterator</strong> : Another interesting iterator which can be used for filter values using regular expressions. Print elements that starts with <code>is_ prefix</code>.</p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(''is_one'', ''is_two'', ''was_three''));\r\n \r\nforeach (new RegexIterator($arrayIterator, ''/is_*/'') as $element) {\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# is_one  is_two\r\n</pre>\r\n\r\n<p><strong>LimitIterator :</strong>LimitIterator, as we can guess from name, is responsible for limiting data for iteration. It can be handy when we want to paginate our collection.</p>\r\n\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(''one'', ''two'', ''three'')); \r\n \r\nforeach (new LimitIterator($arrayIterator, 2, 1) as $element) {\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# three\r\n</pre>\r\n\r\n<p><strong>DirectoryIterator : </strong> DirectoryIterator provide decent method for getting contents from directory. All files and directories are represented by SplFileInfo object, so all system information can be get for them. Below example of DirectoryIterator usage with FilterIterator to print only files from directory. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$directoryIterator = new DirectoryIterator(''.'');\r\n \r\nclass OnlyFilesFilterIterator extends FilterIterator{\r\n \r\n	public function accept()	{\r\n		return ! $this->getInnerIterator()->current()->isDir();\r\n	}\r\n}\r\n \r\nforeach(new OnlyFilesFilterrIterator($directoryIterator) as $file) {\r\n	print $file->getFilename();\r\n	print PHP_EOL;\r\n} \r\n</pre>\r\n\r\n<p><strong>InfiniteIterator :</strong> Using InfiniteIterator we can infinitely iterate through collection. So after reaching last element we start iterate from first one automatically. It can be useful for instance when we create some small server or we want to perform some actions before some situation occurs. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$arrayIterator = new ArrayIterator(array($task1, $task2, $task3));\r\n$infiniteTaskIterator = new InfiniteIterator($arrayIterator);\r\n \r\nforeach ($infiniteTaskIterator as $task) {\r\n \r\n	$performSucceded = $task->perform();\r\n	if (false === $performSucceded) {\r\n		break;\r\n	}\r\n	usleep(200);\r\n}\r\n</pre>\r\n\r\n<p><strong>AppendIterator </strong> : With AppendIterator we can join more iterators and iterate through them. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$arrayIterator = new ArrayIterator(array(2, 4, 6));\r\n$arrayIterator2 = new ArrayIterator(array(7, 8, 9)); \r\n \r\n$appendIterator = new AppendIterator();\r\n$appendIterator->append($arrayIterator);\r\n$appendIterator->append($arrayIterator2);\r\n \r\nforeach ($appendIterator as $element) {\r\n	print $element;\r\n	print PHP_EOL;\r\n}\r\n# 2 4 6 7 8 9\r\n</pre>\r\n\r\n<p><strong>GlobIterator </strong>  : GlobIterator works almost the same as handy glob() function, but return iterator insted of array and elements are SplFileInfo objects. Below code will return all dot files from current directory. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$globIterator = new GlobIterator(''.*'');\r\n \r\nforeach($globIterator as $file) {\r\n	print $file;\r\n	print PHP_EOL;\r\n}\r\n</pre>\r\n\r\n<p><strong>EmptyIterator </strong> :  On first sight this iterator seems useless. But actually is not. Imagine your method return collection of data, and this collection is used by iterator decorators.\r\nBut when your collection is empty – what to do ? </p>\r\n<p>We can return false for example, but this will break our decorators chain or create Iterator from empty array. But for more clarity we can return EmptyIterator.</p>\r\n\r\n<p><strong>SplFileObject</strong></p>\r\n<p>Using SplFileObject we can iterate through file rows. It is similar to iterating through result of file function</p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$fileObject = new SplFileObject(''FILE'');\r\n \r\nforeach ($fileObject as $fileRow) {\r\n	print $fileRow.PHP_EOL;\r\n}\r\n</pre>\r\n\r\n<p><strong>Iterator functions</strong></p>\r\n<p><strong>iterator_count</strong> : Counting elements inside iterator. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(1, 2, 3));\r\nprint iterator_count($arrayIterator);\r\n# 3\r\n</pre>\r\n\r\n<p><strong>iterator_apply</strong></p>\r\n<p>This function calls a callback function for every element in a iterator. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$arrayIterator = new ArrayIterator(array(1, 2, 3));\r\n \r\nfunction triple(Iterator $iterator) {\r\n    print $iterator->current()*3;\r\n    return true;\r\n}\r\n</pre>\r\n\r\n<p>Note: you can return false to break invoking chain</p>\r\n\r\n<p>This is very useful function which creates array from iterator. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$directoryIterator = new GlobIterator(''.*'');\r\nvar_dump(iterator_to_array($directoryIterator));\r\n# array of SplFileInfo objects\r\n</pre>\r\n', 'Standard PHP Library Iterators', 'Slawek_Lukasiewicz.jpg', 1, 2, 'Slawek Lukasiewicz', 'open', 'post', 'spl.jpg', 0, 17, 0);
  INSERT INTO `blog` (`blog_id`, `user_id`, `blog_date`, `blog_content`, `blog_title`, `blog_img`, `cat_id`, `tag_id`, `user_name`, `comment_status`, `blog_type`, `blog_mime_type`, `blog_like`, `blog_read`, `comment_count`) VALUES
  (4, 1, '2014-09-05 00:00:00', '<p>Date and time manipulation in PHP is mostly connected with functions like: date, time or strtotime. They can be sufficient, but if we want to deal with dates like with objects we can use DateTime class. DateTime class is not only straightforward wrapper for standard functions, it has a lot of additional features for example timezones. </p>\r\n\r\n<p><strong>Date creation </strong></p>\r\n\r\npublic DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )\r\n\r\n<p>During DateTime object creation we can set time and timezone. Time can be represented as one of supported formats</p>\r\n\r\n\r\n<p>Date and time formats examples: </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$date = new DateTime(''2014-08-07 10:20:30'');\r\nprint $date->format(''d-m-Y H:i'');\r\n# 07-08-2014 10-20\r\nprint PHP_EOL;\r\n \r\n$date = new DateTime(''@223311122'');\r\nprint $date->format(''d-m-Y H:i'');\r\n# 28-01-1977 14-52\r\nprint PHP_EOL;\r\n\r\n$date = new DateTime(''9/24/72 12:20'');\r\nprint $date->format(''d-m-Y H:i'');\r\n# 24-09-1972 12-20\r\nprint PHP_EOL;\r\n</pre>\r\n\r\n<p>Notice: When using timestamp notation (@TIMESTAMP) timezone is ignored\r\nIf we dont set timezone, the current timezone will be use. </p>\r\n\r\n\r\n<p><strong>Format date</strong></p>\r\n\r\n<p>\r\nDate is formatted by format method. It takes one parameter, format, which is format accepted by date function. Examples can be found above. </p>\r\n\r\n\r\n<p><strong>Date Comparison</strong></p>\r\n\r\n\r\n\r\n\r\nWe can compare DateTime objects with PHP comparison operators. \r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$dateA = new DateTime(''2014-07-05'');\r\n$dateB = new DateTime(''2014-07-07'');\r\nvar_dump($dateA > $dateB);\r\n# false\r\nvar_dump($dateA < $dateB);\r\n# true\r\n</pre>\r\n\r\n<p><strong>Altering date</strong></p>\r\n\r\nDateTime object is mutable, it means that we can change date or time after creation. We can change date or time with setDate(), setTime() or setTimestamp() methods. \r\n<pre class="brush:js">\r\n&lt?php\r\n$date = new DateTime();\r\n$date->setDate(2013, 11, 12);\r\n$date->setTime(15, 10);\r\nprint $date->format(''d-m-Y H:i'');\r\n#12-11-2013 15:10</pre>\r\n\r\n<p>Another possibility for altering date are sub and add methods, for respectively subtracting and adding date interval to our object. These methods takesDateInterval object as argument. According to documentation, DateInterval is: </p>\r\n\r\n\r\n<p>Representation of date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimes constructor supports.\r\nExample of using 2 days interval. </p>\r\n\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$date = new DateTime(''2014-10-10'');\r\n$date->add(new DateInterval(''P2D''));\r\nprint $date->format(''d-m-Y'');\r\n#12-10-2013\r\n\r\nprint PHP_EOL;\r\n \r\n$date = new DateTime(''2014-10-10'');\r\n$date->sub(new DateInterval(''P2D''));\r\nprint $date->format(''d-m-Y'');\r\n#08-10-2013</pre>\r\n\r\n<p>More information about creating DateInterval object can be found here.DateInterval has also static method createFromDateString, which can create DateInterval object from relative parts of date string, as show below. </p>\r\n<pre>$dateInterval = DateInterval::createFromDateString(''2 days'');</pre>\r\n\r\n<p>We can also increment or decrement DateTime object using modify method. </p>\r\n \r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$date = new DateTime(''2014-10-10'');\r\n$date->modify(''+1day'');\r\nprint $date->format(''d-m-Y'');\r\n#11-10-2013</pre>\r\n\r\n<p>Modify accepts strtotime format. </p>\r\n<p>Notice: Sometimes modify can behave unintuitive. Derick Rethans wrote article about one such case. </p>\r\n<p>Above methods return $this, so they can be used for method chaining. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n$date = new DateTime();\r\n$date->setDate(2013, 11, 12)->setTime(15, 10);\r\nprint $date->format(''d-m-Y H:i'');\r\n#12-11-2013 15:10</pre>\r\n\r\n<p><strong>Calculating difference between two DateTime objects</strong></p>\r\n\r\n<p>This is one of my favorite features in DateTime class. Using diff method we can calculate difference between two DateTime objects. Diff method returns DateInterval object. </p>\r\n <pre class="brush:js">\r\n&lt?php\r\n\r\n$dateA = new DateTime(''2014-10-10'');\r\n$dateB = new DateTime(''2014-10-12'');\r\n \r\n$interval = $dateA->diff($dateB);\r\nprint $interval->format(''days: %R %d'');\r\n#days: +2\r\n\r\n$interval = $dateB->diff($dateA);\r\nprint $interval->format(''days: %R %d'');\r\n#days: -2</pre>\r\n\r\n<p>Diff method has also second optional parameter, absolute when true is passed difference is return as absolute. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$dateA = new DateTime(''2014-10-10'');\r\n$dateB = new DateTime(''2014-10-12'');\r\n \r\n$interval = $dateB->diff($dateA);\r\nprint $interval->format(''days: %R %d'');\r\n#days: -2\r\n\r\nprint PHP_EOL;\r\n \r\n$interval = $dateB->diff($dateA, true);\r\nprint $interval->format(''days: %R %d'');\r\n#days: +2\r\n</pre>\r\n\r\n<p><strong>Iterating through date period</strong></p>\r\n<p>Another interesting class is DatePeriod, which can be used for iterating through some period of time. We can set start date (DateTime), interval for iterating (DateInterval), and optionally end date (DateTime). It can be really useful. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$dateStart = new DateTime(''2014-10-10 10:00'');\r\n$dateEnd = new DateTime(''2014-10-10 14:00'');\r\n$periodInterval = new DateInterval(''PT1H'');\r\n \r\n$datePeriod = new DatePeriod($dateStart, $periodInterval, $dateEnd);\r\n \r\nforeach ($datePeriod as $hourPeriod) {\r\n	print $hourPeriod->format(''d-m-Y H:i'');\r\n	print PHP_EOL;\r\n}\r\n# 10-10-2014 10:00\r\n# 10-10-2014 11:00\r\n# 10-10-2014 12:00\r\n# 10-10-2014 13:00</pre>\r\n\r\n<p>DatePeriod has more types of constructors and can be used in completely different way. </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n$date1 = new DateTime(); \r\n$eightynine_days_ago = new DateInterval( "P89D" ); \r\n$eightynine_days_ago->invert = 1; //Make it negative. \r\n$date1->add( $eightynine_days_ago ); \r\n</pre>\r\n\r\n<p>and then $date1 is now 89 days in the past. </p>\r\n\r\n<p>NOTE : This DateInterval Class</p>\r\n<pre class="brush:js">\r\n&lt?php\r\n// Built in with PHP\r\nDateInterval {\r\n/* Properties */\r\npublic integer $y ; // years\r\npublic integer $m ; // months\r\npublic integer $d ; // days\r\npublic integer $h ; // hours\r\npublic integer $i ; // minutes\r\npublic integer $s ; // seconds\r\npublic integer $invert ; \r\npublic mixed $days ;\r\n/* Methods */\r\npublic __construct ( string $interval_spec )\r\npublic static DateInterval createFromDateString ( string $time )\r\npublic string format ( string $format )\r\n}</pre>\r\n\r\n<p>days</p>\r\n<p>If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE. </p>\r\n\r\n<p>Parameters</p> \r\n<p>interval_spec</p>\r\n\r\n<p>An interval specification. </p>\r\n<p>The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.\r\nHere are some simple examples. </p>\r\nTwo days is P2D.<br> \r\nTwo seconds is PT2S. <br>\r\nSix years and five minutes isP6YT5M.<br>\r\n\r\n<p>Note: </p>\r\n<p>The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. \r\nSo years before months, months before days, days before minutes, etc. </p> \r\n<p>Thus one year and four days must be represented as P1Y4D, not P4D1Y.<br>\r\nThe specification can also be represented as a date time. A sample of one year and four days would beP0001-00-04T00:00:00. But the values in this format can not exceed a given period''s roll-over-point (e.g. 25hours is invalid).</p>\r\n', 'Working With Date And Time In Object Oriented Way', 'Slawek_Lukasiewicz.jpg', 1, 1, 'Slawek Lukasiewicz', 'open', 'post', 'date.jpg', 0, 43, 0),
  (5, 2, '2014-09-15 00:00:00', '<p>If your website has hundreds of pages with many visitors everyday, you might want to implement some sort of caching mechanism for your website to speed up page loading time. Each client-server request consist of multiple database queries, server response and the processing time increasing overall page loading time. The most common solution is to make copies of dynamic pages called cache files and store them in a separate directory, which can later be served as static pages instead of re-generating dynamic pages again and again.</p>\r\n<p><strong>Understanding Dynamic pages & Cache Files</strong></p>\r\nCache files are static copies generated by dynamic pages, these files are generated one time and stored in separate folder until it expires, and when user requests the content, the same static file is served instead of dynamically generated pages, hence bypassing the need of regenerating HTML and requesting results from database over and over again using server-side codes. For example, running several database queries, calculating and processing PHP codes to the HTML output takes certain seconds, increasing overall page loading time with dynamic page, but a cached file consist of just plain HTML codes, you can open it in any text editor or browser, which means it doesn’t require processing time at all.<br>\r\n<strong>Dynamic page :</strong>— The example in the picture below shows how a dynamic page is generated. As its name says, it’s completely dynamic, it talks to database and generates the HTML output according to different variables user provides during the request. For example a user might want to list all the books by a particular author, it can do that by sending queries to database and generating fresh HTML content, but each request requires few seconds to process also the certain server memory is used, which is not a big deal if website receives very few visitors. However, consider hundreds of visitors requesting and generating dynamic pages from your website over and over again, it will considerably increase the pressure, resulting delayed output and HTTP errors on the client’s browser.<br>\r\n<img src="http://localhost/mvc/public/assets/img/blog/phpcache1.jpg" alt="webcode" /><br> \r\n<p><strong>Cached File :</strong>— Picture below illustrates how cached files are served instead of dynamic pages, as explained above the cached files are nothing but static web pages. They contain plain HTML code, the only way the content of the cached page will change is if the Web developer manually edits the file. As you can see cached files neither require database connectivity nor the processing time, it is an ideal solution to reduce server pressure and page loading time consistently.</p>\r\n<img src="http://localhost/mvc/public/assets/img/blog/phpcache2.jpg" alt="webcode" /><br>\r\n<p><strong>PHP Caching</strong></p>\r\nThere are other ways to cache dynamic pages using PHP, but the most common method everyone’s been using is PHP Output Buffer and Filesystem Functions, combining these two methods we can have magnificent caching system.<br>\r\n<strong>PHP Output buffer :</strong>— It interestingly improves performance and decreases the amount of time it takes to download, because the output is not being sent to browser in pieces but the whole HTML page as one variable. The method is insanely simple take a look at the code below :\r\n<pre class="brush:js">\r\n\r\nob_start(); // start the output buffer\r\n/* the content */\r\nob_get_contents();  gets the contents of the output buffer \r\nob_end_flush(); // Send the output and turn off output buffering\r\n\r\n</pre>\r\n<p>When you call ob_start() on the top of the code, it turns output buffering on, which means anything after this will be stored in the buffer, instead of outputting on the browser. The content in the buffer can be retrieved using ob_get_contents(). You should call ob_end_flush() at the end of the code to send the output to the browser and turn buffering off.</p><br>\r\n<strong>PHP Filesystem :</strong>— You may be familiar with PHP file system, it is a part of the PHP core, which allow us to read and write the file system. Have a look at the following code.\r\n<pre class="brush:js">\r\n\r\n$fp = fopen(''/path/to/file.txt'', ''w'');  //open file for writing\r\nfwrite($fp, ''I want to write this'');    //write \r\nfclose($fp);                            //Close file pointer\r\n\r\n</pre>\r\n<p>As you can see the first line of the code fopen() opens the file for writing, the mode‘w’ places the file pointer at the beginning of the file and if file does not exist, it attempts to create one. Second line fwrite() writes the string to the opened file, and finally fclose() closes the successfully opened file at the beginning of the code.</p><br>\r\n<p><strong>Implementing PHP caching</strong></p>\r\nNow you should be pretty clear about PHP output buffer and filesystem, we can use these both methods to create our PHP caching system. Please have a look at the picture below, the Flowchart gives us the basic idea about our cache system.\r\n<p>The cycle starts when a user request the content, we just check whether the cache copy exist for the currently requested page, if it doesn’t exist we generate a new page, create cache copy and then output the result. If the cache already exist, we just have to fetch the file and send it to the user browser.<br><img src="http://localhost/mvc/public/assets/img/blog/phpcache3.jpg" alt="webcode" /><br>\r\nTake a look at the Full PHP cache code below, you can just copy and paste it in your PHP projects, it should work flawlessly as depicted in above Flowchart. You can play with the settings in the code, modify the cache expire time, cache file extension, ignored pages etc.</p>\r\n<pre class="brush:js">\r\n\r\n//settings\r\n$cache_ext  = ''.html''; //file extension\r\n$cache_time = 3600;  //Cache file expires afere these seconds (1 hour = 3600 sec)\r\n$cache_folder = ''cache/''; //folder to store Cache files\r\n$ignore_pages = array('''', ''''); \r\n\r\n$dynamic_url = ''http://''.$_SERVER[''HTTP_HOST''] \r\n                        .$_SERVER[''REQUEST_URI'']\r\n                        .$_SERVER[''QUERY_STRING'']; \r\n                        // requested dynamic page (full url\r\n\r\n$cache_file  = $cache_folder.md5($dynamic_url).$cache_ext; \r\n               // construct a cache file\r\n$ignore = (in_array($dynamic_url,$ignore_pages))?true:false; \r\n          //check if url is in ignore list\r\n\r\nif (!$ignore && file_exists($cache_file) \r\n    && time() - $cache_time < filemtime($cache_file)) \r\n    { \r\n      //check Cache exist and it''s not expired.\r\n      ob_start(''ob_gzhandler'');  //Turn on output buffering,\r\n      //"ob_gzhandler" for the compressed page with gzip.\r\n      readfile($cache_file); \r\n      //read Cache file\r\n      echo ''<!-- cached page - ''.date(''l jS \\of F Y h:i:s A'',\r\n      filemtime($cache_file)).'', Page : ''.$dynamic_url.'' -->'';\r\n      ob_end_flush(); //Flush and turn off output buffering\r\n      exit(); //no need to proceed further, exit the flow.\r\n}\r\n//Turn on output buffering with gzip compression.\r\nob_start(''ob_gzhandler''); \r\n\r\n######## Your Website Content Starts Below #########\r\n\r\nHTML TEMPLATE HERE\r\n\r\n######## Your Website Content Ends here ######### \r\n\r\nif (!is_dir($cache_folder)) { //create a new folder if we need to\r\n    mkdir($cache_folder);\r\n}\r\nif(!$ignore){\r\n    $fp = fopen($cache_file, ''w'');  //open file for writing\r\n    fwrite($fp, ob_get_contents()); //write contents of the output buffer in Cache file\r\n    fclose($fp); //Close file pointer\r\n}\r\nob_end_flush(); //Flush and turn off output buffering \r\n\r\n</pre>\r\n<p>You must place your PHP content between the enclosed comment lines, In fact I’d suggest putting them in separate header and footer file, so that it can generate and serve cache files for all the different dynamic pages. If you read the comment lines in the code carefully, you should find it pretty much self explanatory.</p>\r\n<p>1. Get the currently requested URL location.<br>\r\n2. Construct a location path for the cache file, convert URL to MD5 hash for the fixed cache file name.<br>\r\n3. Check whether URL is in ignore list.<br>\r\n4. Check for existing unexpired cache file, if exist, just open and output the content with gzip compression.<br>\r\n5. Or else, we create a new cache file and output the HTML result with gzipcompression.</p>\r\nSource from : www.sanwebe.com/2013/09/php-cache-dynamic-pages-speed-up-load-times\r\n\r\n\r\n', 'PHP Cache Dynamic Pages To Speed Up Load Times', 'Saran_Chamling.jpg', 1, 1, 'Saran Chamling', 'open', 'post', 'cache.jpg', 0, 32, 0),
  (6, 1, '2014-10-08 00:00:00', '<p>This tip is a guide to writing database operation code in PHP - the Object Oriented way.\r\nI have come across people asking me the proper way of writing database operation code in PHP on a number of occasions. Not wanting to answer the same question over and over again, I have decided to publish the answer here.</p>\r\n<br>\r\n<p><strong>The Approach</strong></p>\r\n<p><strong>Step 1</strong>: Create a PHP page called "config.php" that defines the database related parameters. </p>\r\n<pre class="brush:js">\r\n\r\n// config.php     \r\n      define(''DB_USER'', "username");\r\n      define(''DB_PASSWORD'', "password");  \r\n      define(''DB_DATABASE'', "database name"); \r\n      define(''DB_SERVER'', "ip address of database server"); \r\n\r\n</pre>\r\n\r\n<p><strong>Step 2</strong>: Create a PHP page that contains a class that takes care of the database connection chore, call it "db_connect.php".</p>\r\n<pre class="brush:js">\r\n\r\n// db_connnect.php\r\nclass DB_Connect {\r\n     private $con;\r\n \r\n    // constructor\r\n    function __construct() {\r\n        // connecting to database\r\n        $this->con = $this->connect();\r\n    }\r\n \r\n    /**\r\n     * Function to connect with database\r\n     */\r\n    private function connect() {\r\n\r\n      // import database connection variables\r\n      require_once __DIR__.''/config.php'';\r\n\r\n      try {\r\n        $conn = new PDO(''mysql:host=''.DB_SERVER.'';\r\n                         dbname=''.DB_DATABASE, DB_USER, DB_PASSWORD);\r\n\r\n        $conn->setAttribute(PDO::ATTR_ERRMODE, \r\n                            PDO::ERRMODE_EXCEPTION);\r\n        } catch(PDOException $e) {\r\n            echo ''ERROR: '' . $e->getMessage();\r\n        }\r\n        return $conn;\r\n    }\r\n    \r\n    public function getDbConnection(){\r\n        return $this->con;\r\n    }\r\n}\r\n\r\n</pre>\r\n\r\n<p><strong>Step 3</strong>: Create a PHP page that contains a class that contains all the functions for all your SQL queries, say "db_functions.php". You will include every SQL query as a function in this file. That will promote reusability and maintainability. </p>\r\n<pre class="brush:js">\r\n\r\n// db_functions.php\r\nclass DB_Functions {\r\n    private $con;\r\n    // constructor\r\n    function __construct() {\r\n        require_once __DIR__.''/db_connect.php'';\r\n\r\n        // connecting to database\r\n        $db = new DB_Connect();\r\n        $this->con = $db->getDbConnection();\r\n    }\r\n \r\n    public function selectUser($id) {\r\n        try {\r\n            $stmt = $this->con->prepare(''SELECT * FROM user WHERE id = :id'');\r\n            $params = array('':id'' => $id);\r\n            $stmt->execute($params);\r\n            return $stmt;\r\n        } catch(PDOException $e) {\r\n            echo ''ERROR: '' . $e->getMessage();\r\n        }\r\n    }\r\n \r\n    public function otherSQLfunction($parameter) {\r\n        // other sql code\r\n    }\r\n}\r\n</pre>\r\n\r\n<p><strong>Step 4</strong>: Finally, your other PHP files will simply need to call the appropriate functions in the "db_functions.php" whenever they need to query the database. </p>\r\n<pre class="brush:js">\r\n     require_once __DIR__.''/db_functions.php'';\r\n\r\n     $db = new DB_Functions();\r\n     $result = $db->selectUser($id);\r\n \r\n     //  other code\r\n</pre><br>\r\n\r\n<p><strong>Points of Interest</strong></p>\r\nIt seems to be a hassle to split code into separate files, but that extra work when it is done correctly is only required once at the initial stage. With proper planning and design, your subsequent coding and maintenance will be a breeze.<br><br>\r\n<p><strong>License</strong></p>\r\nThis article, along with any associated source code and files, is licensed under <strong>The Code Project Open License</strong> (CPOL)\r\n\r\n<p><a href="http://www.codeproject.com/Members/peterleow">Source from : Code Project</a></p>\r\n', 'PHPs Database Operation Go OOP', 'Peter_Leow.jpg', 1, 3, 'Peter Leow', 'open', 'post', 'pdo.jpg', 0, 65, 0),
  (7, 1, '2014-11-02 00:00:00', '<p>This post will explain PHP autoload and name space concept using a few basic question and answer about PHP autoload along with some examples.</p>\r\n<p><strong>What is Autoloading in PHP? </strong> </p>\r\n<p>PHP provides helper functions to include or import PHP files, if it has not been included before. if we use PHP autoload then we don''t need to write <em>require</em>  or <em>include</em>  statement for each PHP class files. We should to use modern PHP way now.</p>\r\n\r\n<p><strong>Why we need auto loading? </strong> </p>\r\n\r\n<p>It is a good question. why we need it, although we can write <em> require</em> or <em> include</em> statements whenever we need. As PHP has evolved using OOPs concept, we create more classes for our PHP project and create a separate PHP file for each single PHP class. Hence we increase the number of <em> require</em> or <em>include</em> statements. therefore we need some standard way to include each files rather specifying include statement by our self every time. that is why PHP has provided some useful methods to resolve this problem. </p>\r\n\r\n<p><strong>PHP Autoloading Methods</strong></p>\r\n<p>PHP uses two function, one is magic method<em> __autoload</em> and another is <em>spl_autoload_register</em>. each of these have their own benefit. they accept one parameter which turns into class name whenever we instantiate that class object. inside these method we could write our logic to load PHP class file. </p> \r\n\r\n<p><strong>What is difference between __autoload and sp_autload_resgister function? </strong></p>\r\n<p><em>__autoload </em>method is magic method which means you can define it only once. therefore you would have only one logic to include PHP class files whereas <em>spl_autoload_register</em> is defined function which accept function name as parameter and we can define specified function with our logic. that mean we can have multiple implementation of inclusion of PHP files with help of <em>spl_autoload_register. </em> </p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\n/**\r\n * autoload method\r\n */\r\nfunction __autoload($class)\r\n{\r\n  require $class.''.php'';\r\n}\r\n\r\n//spl_autoload_register\r\n\r\n/**\r\n * autoload method one\r\n */\r\nfunction autoloadOne($class)\r\n{\r\n  require "/dir-one/".$class.".php";\r\n}\r\n\r\n/**\r\n * autoload method two\r\n */\r\nfunction autoloadTwo($class)\r\n{\r\n  require "/dir-two/".$class.".php";\r\n}\r\n\r\n//register auto loader\r\nspl_autoload_register("autoloadOne");\r\nspl_autoload_register("autoloadTwo");\r\n</pre><br>\r\n<p><strong>What is namespace? </strong></p>\r\n<p>PHP normally wont allow two class with same name. but later 5.3 introduce concept of namespace which create a ownership of class so that two different class can have same class name but with different ownership. </p>\r\n\r\n<p><strong>What is importance of namespace in autloading</strong></p>\r\n<p>when we autoload class we get a parameter into autload function. when you echo that parameter it will print that class name and namespace provides directory structure for classes.</p>\r\n<pre class="brush:js">\r\n&lt?php\r\n\r\nnamespace Module\\User\\Controller;\r\nnamespace Module\\User\\Entity;\r\nnamespace Module\\User\\Form;\r\nnamespace Module\\User\\Validator;\r\n</pre><br>\r\n<p>If we autoload above class then we will get whole namespace of that class along with class name e.g <em>namespace_autoload.php</em></p>\r\n<pre class="brush:js">\r\n&lt?php\r\nfunction __autoload($class)\r\n{\r\n  echo "class path = ".$class;\r\n  die ;\r\n}\r\n\r\nnew \\Module\\User\\Controller();\r\n\r\n// it will print\r\n// class path = Module\\User\\Controller\r\n</pre><br>\r\n<p>with help of this information we can organize classes according to our project directory structure. let say you have following project structure</p>\r\n<pre class="brush:js">\r\nproject\r\n |__Module\r\n |    |__User\r\n |         |__Controller\r\n |         |__Entity\r\n |         |__Form\r\n |\r\n |__autoload.php\r\n\r\n</pre><br>\r\nthen you can create PHP classes with namespace as<br>\r\n<pre class="brush:js">\r\n\r\nproject\r\n |__Module\r\n |    |__User\r\n |         |__Controller // class : IndexController , namespace Module\\User\\Controller\r\n |         |__Entity     // class : User , namespace Module\\User\\Entity\r\n |         |__Form       // class : UserForm , namespace Module\\User\\Form\r\n |\r\n |__autoload.php\r\n\r\n</pre><br>\r\n<em>autoload.php</em><br>\r\n<pre class="brush:js">\r\n\r\n&lt?php\r\n\r\n//include namespace\r\n\r\nuse Module\\User\\Controller\\IndexController;\r\nuse Module\\User\\Entity\\User;\r\nuse Module\\User\\Form\\UserForm;\r\n\r\n/**\r\n * Autload project files\r\n */\r\nfunction __autoload($class)\r\n{\r\n  echo $class;\r\n  require $class;\r\n}\r\n\r\n// instantiate classes\r\n$controller = new IndexController();\r\n//(it will print)  Module\\User\\Controller\\IndexController and load this class\r\n\r\n$user = new User();\r\n//(it will print)  Module\\User\\Entity\\User  and load this class\r\n\r\n$userForm = new UserForm();\r\n//(it will print) Module\\User\\Form\\UserForm  and load this class\r\n\r\n</pre>\r\nas you can see how namespace helps to organize project structure and autoload the classes. <br><br>\r\n\r\n<p><strong>What is difference between following two sets of statements</strong></p>\r\n<pre class="brush:js">\r\nnamespace autoloading                           Direct include files\r\n============================================================================\r\nuse Module\\User\\Controller\\IndexController;  	require "Module\\User\\Control...\r\nuse Module\\User\\Entity\\User;       	            require "Module\\User\\Entity..	\r\nuse Module\\User\\Form\\UserForm;                  require "Module\\User\\Form\\..       		\r\n============================================================================\r\n\r\n</pre>\r\n<p>General difference is require statement accept full directory path where in case of namespace we can set logic to autoload PHP files with different directory structure and can minimize the namespace length. \r\nLet see the example, suppose you have following directory for your project library files. </p>\r\n<pre class="brush:js">\r\nproject\r\n |\r\n |__vendor\r\n |\r\n |__lib\r\n   |\r\n   |__src\r\n     |\r\n     |__components\r\n       |\r\n       |__HTTP  //Request, Response classes\r\n       |\r\n       |__Controller  //BaseController classes\r\n       |\r\n       |__Form //BaseForm classes\r\n\r\n ..... many more files\r\n\r\n</pre><br>\r\n\r\n\r\nUsing require statement need to write following code. <br>\r\n<pre class="brush:js">\r\n\r\n&lt?php\r\n\r\n require "/vendor/lib/src/components/HTTP/Request";\r\n require "/vendor/lib/src/components/HTTP/Response";\r\n require "/vendor/lib/src/components/Controller/BaseController";\r\n require "/vendor/lib/src/components/Form/BaseForm";\r\n</pre>\r\n<p>Which is very lengthy and not properly organized. </p>\r\n\r\n<p>With help of autoload and namespace we can reduce and class path and organize structure in much proper ways. </p>\r\n<pre class="brush:js">\r\n\r\n&lt?php\r\n\r\ndefine("LIB_PATH", "/vendor/lib/src/components");\r\n\r\nuse HTTP\\Request;\r\nuse HTTP\\Response;\r\nuse Controller\\BaseController;\r\nuse Form\\BaseForm;\r\n\r\n/**\r\n *  autoload lib class files\r\n */\r\nfunction __autoload($class)\r\n{\r\n  // set class path\r\n  $class_path = LIB_PATH.$class;\r\n\r\n  //include class file\r\n  echo $class_path;\r\n  require $class_path;\r\n}\r\n\r\n$request = new Request;\r\n// (it will print)  /vendor/lib/src/components/HTTP/Request\r\n\r\n$controller = new BaseController;\r\n// (it will print)  /vendor/lib/src/components/Controller/BaseController\r\n\r\n</pre>\r\n<p><strong>Summary</strong></p>\r\no	autoload helps to load all PHP classes of a PHP project.<br>\r\no	namespace helps to organize your PHP classes<br>\r\no	combination of autoload and namespace organize and load PHP project in standardized way. </p> \r\nSource : <a href="http://www.zainabed.com/" target="_blank">zainabed.com</a>', 'Build Autoload PHP Classes', 'Zainul_Abedin.jpg', 1, 1, 'Zainul Abedin', 'open', 'post', 'spl.jpg', 0, 15, 0);
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `category`
  --
  
  CREATE TABLE IF NOT EXISTS `category` (
  `cat_id` tinyint(3) unsigned NOT NULL,
    `cat_name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
    `blog_count` smallint(4) unsigned NOT NULL,
    `snip_count` smallint(4) unsigned NOT NULL,
    `tut_count` smallint(4) unsigned NOT NULL
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;
  
  --
  -- Dumping data for table `category`
  --
  
  INSERT INTO `category` (`cat_id`, `cat_name`, `blog_count`, `snip_count`, `tut_count`) VALUES
  (1, 'PHP-Basic', 3, 0, 0),
  (2, 'PHP-OOP', 3, 0, 0),
  (3, 'PHP-Framework', 0, 0, 0),
  (4, 'PHP-Security', 0, 0, 0),
  (5, 'Best-Practices', 1, 0, 0),
  (6, 'Scaling-Webapp', 0, 0, 0),
  (7, 'Web-Server', 0, 0, 0),
  (8, 'Bootstrap', 0, 0, 0),
  (9, 'HTML-CSS', 0, 0, 0),
  (10, 'JQuery', 0, 0, 0);
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `category_post`
  --
  
  CREATE TABLE IF NOT EXISTS `category_post` (
  `id` int(10) unsigned NOT NULL,
    `cat_id` int(10) unsigned NOT NULL,
    `blog_id` int(10) unsigned NOT NULL,
    `snip_id` int(10) NOT NULL,
    `tut_id` int(10) NOT NULL
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8 ;
  
  --
  -- Dumping data for table `category_post`
  --
  
  INSERT INTO `category_post` (`id`, `cat_id`, `blog_id`, `snip_id`, `tut_id`) VALUES
  (1, 1, 1, 0, 0),
  (2, 5, 2, 0, 0),
  (3, 1, 3, 0, 0),
  (4, 2, 4, 0, 0),
  (5, 1, 5, 0, 0),
  (6, 2, 6, 0, 0),
  (7, 2, 7, 0, 0);
  
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `comment`
  --
  
  CREATE TABLE IF NOT EXISTS `comment` (
  `com_id` smallint(5) unsigned NOT NULL,
    `com_content` smallint(5) NOT NULL,
    `com_email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
    `com_name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
    `com_img` varchar(256) COLLATE utf8_unicode_ci DEFAULT NULL,
    `blog_id` smallint(5) unsigned DEFAULT NULL,
    `user_id` smallint(4) unsigned NOT NULL,
    `user_name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `is_published` tinyint(1) NOT NULL DEFAULT '0'
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=9 ;
  
  --
  -- Dumping data for table `comment`
  --
  
  INSERT INTO `comment` (`com_id`, `com_content`, `com_email`, `com_name`, `com_img`, `blog_id`, `user_id`, `user_name`, `created_at`, `is_published`) VALUES
  (1, 0, 'm2mlike@adas.org', 'Malik', NULL, 0, 0, '', '2014-10-10 21:53:21', 0),
  (2, 0, 'beb@jga.com', 'bebe', NULL, 0, 0, '', '2014-10-15 20:07:08', 0),
  (3, 0, 'beb@jga.com', 'bebe', NULL, 0, 0, '', '2014-10-15 20:07:50', 0),
  (4, 0, 'sdadad@fff.lop', 'Eden Sachot', NULL, 0, 0, '', '2014-10-20 11:19:42', 0),
  (5, 0, 'Ha2lim@ad.com', 'pa2limo', NULL, 0, 0, '', '2014-10-30 22:28:55', 0),
  (6, 0, 'asd', 'Sahadev Ali', NULL, 0, 0, '', '2014-10-30 22:38:49', 0),
  (7, 0, 'Erb23@gmail.com', 'Eric Baldwin', NULL, 0, 0, '', '2014-11-01 18:04:27', 0),
  (8, 0, 'peter_coda@slam.com', 'Peter Zen', NULL, 0, 0, '', '2014-11-01 19:25:12', 0);
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `notes`
  --
  
  CREATE TABLE IF NOT EXISTS `notes` (
  `note_id` int(11) NOT NULL,
    `note_text` text COLLATE utf8_unicode_ci NOT NULL,
    `user_id` bigint(20) NOT NULL
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data' AUTO_INCREMENT=3 ;
  
  --
  -- Dumping data for table `notes`
  --
  
  INSERT INTO `notes` (`note_id`, `note_text`, `user_id`) VALUES
  (1, 'catatan harian', 1),
  (2, 'sudah mandi', 1);
  
  -- --------------------------------------------------------
  
  --
  -- Table structure for table `page`
  --
  
  CREATE TABLE IF NOT EXISTS `page` (
  `page_id` smallint(4) unsigned NOT NULL,
    `page_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    `page_content` longtext NOT NULL,
    `page_title` varchar(128) NOT NULL,
    `page_img` varchar(64) DEFAULT NULL,
    `page_type` varchar(8) NOT NULL DEFAULT 'post'
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  
  -- --------------------------------------------------------
  --
  -- Table structure for table `users`
  --
  
  CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL COMMENT 'auto incrementing user_id of each user, unique index',
    `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique',
    `user_password_hash` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password in salted and hashed format',
    `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique',
    `user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
    `user_account_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'user''s account type (basic, premium, etc)',
    `user_has_avatar` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 if user has a local avatar, 0 if not',
    `user_rememberme_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s remember-me cookie token',
    `user_creation_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the creation of user''s account',
    `user_last_login_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of user''s last login',
    `user_failed_logins` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s failed login attempts',
    `user_last_failed_login` int(10) DEFAULT NULL COMMENT 'unix timestamp of last failed login attempt',
    `user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
    `user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
    `user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
    `user_provider_type` text COLLATE utf8_unicode_ci,
    `user_facebook_uid` bigint(20) unsigned DEFAULT NULL COMMENT 'optional - facebook UID'
  ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data' AUTO_INCREMENT=1 ;
  
  
  
  --
  -- Indexes for table `page`
  --
  ALTER TABLE `page`
   ADD PRIMARY KEY (`page_id`);
  
  --
  -- Indexes for table `tag`
  --
  ALTER TABLE `tag`
   ADD PRIMARY KEY (`tag_id`);
  
  --
  -- Indexes for table `users`
  --
  ALTER TABLE `users`
   ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `user_name` (`user_name`), ADD UNIQUE KEY `user_email` (`user_email`), ADD KEY `user_facebook_uid` (`user_facebook_uid`);
  
  --
  -- AUTO_INCREMENT for dumped tables
  --
  
  --
  -- AUTO_INCREMENT for table `blog`
  --
  ALTER TABLE `blog`
  MODIFY `blog_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
  --
  -- AUTO_INCREMENT for table `category`
  --
  ALTER TABLE `category`
  MODIFY `cat_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
  --
  -- AUTO_INCREMENT for table `category_post`
  --
  ALTER TABLE `category_post`
  MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
  --
  -- AUTO_INCREMENT for table `category_tag`
  --
  ALTER TABLE `category_tag`
  MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=20;
  --
  -- AUTO_INCREMENT for table `comment`
  --
  ALTER TABLE `comment`
  MODIFY `com_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=9;
  --
  -- AUTO_INCREMENT for table `notes`
  --
  ALTER TABLE `notes`
  MODIFY `note_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
  --
  -- AUTO_INCREMENT for table `page`
  --
  ALTER TABLE `page`
  MODIFY `page_id` smallint(4) unsigned NOT NULL AUTO_INCREMENT;
  --
  -- AUTO_INCREMENT for table `tag`
  --
  ALTER TABLE `tag`
  MODIFY `tag_id` tinyint(4) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=20;
  --
  -- AUTO_INCREMENT for table `users`
  --
  ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',AUTO_INCREMENT=5;
  /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
  /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
  /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
  