Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

8 Dec 2013

Principles Of MVC for PHP Developers

Model View Controller

Javascript , HTML5 , css3 ,php , sql , Web , design , development

Being somebody terribly curious about the principles of MVC (Model-View-Controller), i was pleased to check that there's little written out here on the web that truly is sensible. Most articles or tutorials use terms like "business logic" while not shaping process what it means that, means makes understanding MVC all the tougher. Others merely gloss over what an architectural pattern is while not very explaining why you'd care regarding it. it's my hope that I will conceive to justify everything you would like to understand regarding MVC within the simplest attainable approach.
My perspective on MVC is through PHP - my scripting language of alternative - and that i have spent slightly quite three years developing climbable, R.A.D. PHP Frameworks. What I even have learned regarding MVC therein time is that it's terribly powerful, scalable, clean, and if well-coded, robust. the explanation that such revered frameworks like Ruby On Rails and Zend Framework use the principles of MVC alone ought to be a touch that there's something special concerned here.
For those of you WHO aren't aware, MVC was originally represented in terms of a style pattern to be used with Smalltalk by Trygve Reenskaug in 1979. His paper was printed below the title "Applications Programming in Smalltalk-80: a way to use Model-View-Controller", and made-up the groundwork for many future MVC implementations.

What is MVC?

follow: Javascript , HTML5 , css3 ,php , sql , Web , design , development

MVC, or Model-View-Controller is a software system design, or style pattern, that's utilized in software system engineering, whose fundamentals is predicated on the concept that the logic of an application should be separated from its presentation. Put simply, the idea say that MVC relies a stronger approach of separating the logic of your application from the show.

The MVC principle is to separate the application into three main elements, called the Model, the View, and also the Controller. Apparent from the diagram ar the direct associations (solid lines) and therefore the inferred associations (dashed lines). The inferred associations ar associations that may appear apparent from the purpose of read of the user, and not from the particular software system design.
A simple way to think about think of be to contemplate the following:
  1. A user interacts with the view - by clicking on a link or submitting a form.
  2. The Controller handles the user input, and transfers the data to the model
  3. The Model receives the knowledge} and updates it's state (adds data to a database, for instance, or calculates todays date)
  4. The view checks the state of the Model and responds consequently (listing the freshly entered information, maybe)
  5. The view waits for an additional interaction from the user.
But what will this mean to you and why do you have to think about using it?

Well, for starters, MVC has a really expert philosophy. the concept that you just ar separating the logic from the display isn't new, however MVC presents the concept nicely. Code presentation and layout ar easier, creating your application additional rectifiable. The view is within the view files, the logic in the templet, and also the controller handles all of them.

Business Logic :

This term amuses me, as a result of it implies something is going on that does not really have a definition which will be outlined properly. However, it's a straightforward concept: Business Logic is that the method of scheming the logical processes of an application. an easy calendar's business logic would be to calculate what todays date is, what day it's, and on what day all of the times during this month fall, for instance.
Don't let yourself get afraid by flashy terms. Business logic is that the process a part of the application.

Templates :

Many MVC frameworks use some kind of templet system to enforce the principle of DRY (See Below), creating it very easy to re0use code while not having to rewrite it.
I have seen MVC frameworks that run on Smarty, or their own templet engine, or none at all. an easy warning is that some templet engines have rather difficult syntax - check them out before you begin developing, you do not ant to find out an entire new language simply to induce a page to render.

DRY :

Another excellent implementation of MVC is that the DRY (Don't Repeat Yourself) philosophy. basically, DRY is used by Ruby on Rails and a couple of different implementations, and therefore the plan is that you just write one thing once and once solely, re-using the code. The DRY principle is explicit  as "Every piece of information must have one, unambiguous, authoritative illustration among a system."
Correct implementation of DRY would imply that changing one component of the system doesn't amendment unrelated components, that is very logical. Personally, i believe Ruby on Rails pulls this off within the best means, and does it most easily.

Convention Over Configuration :

Convention over Configuration is a design paradigm that primarily tries to get rid of the number of selections you, as a developer, ought to create. this is often achieved by fitting the framework with the conventions that all parts typically need. The developer solely has to modification the items that basically ought to amendment.

It's quite easy, if you're thinking that about it. contemplate a form: it's parts that ar continuously needed, and those parts have states that ar typically a similar. A form has a  tag, that defines an action, method, name, id and enctype, for instance. Unless you wish to vary one thing, it's pretty simple to induce the form name, id and action from the URL (usually). we can additionally set all form strategies to POST unless otherwise explicit . Applying this plan to all parts makes building this sort of application very quick, simple and easy.

Conclusion

As touched on above, MVC is a very excellent  path to begin producing pure, scalable,very powerful, quick code in the least amount of time with the least amount of effort. Some MVC frameworks doesn't contain all of these features, most contain one or two. My advice is experiment with a few MVC frameworks and find one that works for youself.

19 Nov 2013

PHP Security: Default Vulnerabilities, Security Omissions and Framing Programmers?


php security

Secure by design is a easy conception within the security world wherever software system is designed from the ground up to be as secure as potential despite whether or not it imposes a drawback to the end user. the aim of this principle is to confirm that users WHO don't seem to be security specialists can use the software while not essentially being duty-bound to jump through hoops to learn how to secure their usage or, much worse, being tempted into ignoring security considerations that expose unaddressed security vulnerabilities as a result of ignorance, inexperience or laziness. The crux of the principle thus is to market trust within the software whereas, somewhat paradoxically, avoiding an excessive amount of complexness for the end user.

Odd although  it may seem,  this principle explains a number of PHP’s greatest security weaknesses. PHP doesn't expressly use Secure advisedly as a guideline once execution features. I’m positive its within the back of developers’ minds even as I’m certain it's influenced several if their design selections, but there ar problems after you think about how PHP has influenced the protection practices of PHP programmers.

The results of not following Secure by design is that every one applications and libraries written in PHP will inherit variety of security vulnerabilities, hereafter remarked as “By-Default Vulnerabilities”. It conjointly means defensive against key sorts of attacks is undermined by PHP not providing decent native functionality and I’ll talk over with these as “Flawed Assumptions”. Combining the 2 sets of shortcomings, we will establish PHP as existing in an environment wherever security is being compromised by relegating an excessive amount of security responsibility to end programmers.

This is the main focus of the argument I create during this article: Responsibility. once an application is intended and designed solely to fall victim to a by-default vulnerability inheritable  from PHP or because of user-land defenses supported imperfect assumptions regarding what PHP offers in terms of security defenses, WHO bears the responsibility? pointing the finger at the computer programmer isn’t wrong however it conjointly doesn’t tell the full story, and neither can it improve the protection setting for alternative programmers. At some purpose, PHP has to be control in charge of security problems that it's an on the spot influence on although its settings, its default function parameters, its documentation and its lack thereof. questions need to be asked on once the indistinct line between PHP’s default behaviour and a security vulnerability sharpens into focus.

11 Nov 2013

The Future of PHP


Javascript , HTML5 , css3 ,php , sql , Web , design , development
php-future

There has been an issue over the future of PHP. whereas some feel that its time that PHP makes means for additional advanced languages and development interfaces, there also are hardcore PHP loyalists who suppose that the simplicity of PHP can not be replicated by the other language. So, wherever do we see PHP, a number of years from now? Or rather, however can PHP develop itself keep itself updated with the dynamical needs of the planet Wide internet (WWW)? browse on and that we will discover some valid arguments on the future of PHP.

PHP Facts and the Future

1.  One of the good points of the PHP language is its large on-line community. There are around twenty million internet applications that use PHP. Developers everywhere use the language to form scripts. several helpful software system applications like video-streaming applications and content management systems area unit known  to be supported PHP, the foremost fashionable example being Drupal. Although, developers within the community will add PHP scripts and recommend changes or add new options within the core PHP package, solely regarding 450 programmers will approve such changes. The organization Zend takes care of the packaging problems with PHP. So, in terms of development, there are enough developers, and additionally directors who can defend the first package from obtaining dilute with sub-standard codes.

2.  The actual fact that PHP has stayed at the highest, and managed to obviate challenges from a lot of hyped-up languages like Java and ColdFusion, it's safe to recommend that it'll still do therefore within the future likewise. As we recently saw, PHP came up with the Model-View-Container framework of its own so as to counter the threat from Ruby-on-Rails, it once more goes to point out however easy the language is, and the way simple is it to duplicate any new “technologically” advanced interfaces and frameworks that return up currently and so.

3.  Alternative languages like Java are thought of to be superior due to its extended scope. PHP is mostly viewed to be restricted with internet applications solely. However, one can produce standalone desktop applications with the assistance of PHP and GTK. Even some open supply programming frameworks currently support PHP projects in their tool. Thus, PHP is slowly and steady starting its internet application boundary, to overcome the standalone application area.

Thus, it's pretty safe to mention that, PHP, that is understood to resist the check of your time, is sweet enough for the future likewise. Simplicity, as they are saying, is extremely advanced to realize. And, PHP happens to realize that very strongly!

6 Nov 2013

5 PHP Security Measures

Javascript , HTML5 , css3 ,php , sql , Web , design , development

For many years, PHP has been a stable, cheap platform on that to control web-based applications. Like most web-based platforms, PHP is liable to external attacks. Developers, database architects and system administrators ought to take precautions before deploying PHP applications to a live server. Most of those techniques will be accomplished with a couple of lines of code or a small adjustment to the applying settings.

#1: Manage Setup Scripts :


If the developer has put in a collection of PHP scripts from a third-party application, the scripts the application uses to put in the operating parts can even offer an access point to unscrupulous users. Most suppliers of third-party packages suggest removing the directory containing the setup scripts shortly when installation. For developers who want to retain the setup scripts, they will produce an .htaccess file that controls access to the administrative directories.

AuthType Basic
AuthName “Administrators Only”
AuthUserFile /usr/local/apache/passwd/passwords

Require valid-user

1 Nov 2013

A Note on Security of PHP

php , javascript , html5 , css3 , web design development
PHP is a powerful and versatile tool. This power and adaptability comes from PHP being a really thin framework sitting on prime of dozens of distinct 3rd-party libraries. every of those libraries have their own distinctive input data characteristics. data that will be safe to pass to at least one library might not be safe to pass to a different.

A recent internet Worm referred to as NeverEverSanity exposed a slip within the input validation within the standard phpBB message board application. Their highlighting code did not account for double-urlencoded input properly. while not correct input validation of untrusted user data combined with any of the PHP calls that may execute code or write to the filesystem you produce a potential security drawback. Despite some confusion relating to the temporal order of some unrelated PHP security fixes and also the NeverEverSanity worm, the worm did not even have something to try to to with a security drawback in PHP.

When we name security in a very internet application we actually have 2 classes. Remote and local. each remote exploit are often avoided with terribly careful input validation. If you're writing an application that asks for a user's name and age, check and ensure you're solely obtaining characters you'd expect. conjointly ensure you're not obtaining an excessive amount of data that may overflow your backend data storage or no matter manipulation functions you'll be passing this data to. A variation of the remote exploit is that the XSS or cross-site scripting drawback wherever one user enters some javascript that consequent user then views.

For local exploits we principally hear concerning open_basedir or safemode issues on shared virtual hosts. These 2 options are there as a convenience to system administrators and may in no means be thought of as an entire security framework. With all the 3rd-party libraries you'll hook into PHP and every one the inventive ways that you'll trick these libraries into accessing files, it's not possible to ensure security with these directives. The Oracle and Curl extensions each have ways that to travel through the library and browse a local file, as an example. wanting modifying these 3rd-party libraries, which might be tough for the closed-source Oracle library, there extremely is not a lot of PHP will do regarding this.

When you have PHP by itself with solely alittle set of extensions safemode and open_basedir are usually enough to frustrate the typical soul, except for crucial security things you must be using OS-level security by running multiple internet servers every as their own user id and ideally in separate jailed/chroot'ed filesystems. Better yet, use utterly separate physical servers. If you share a server with somebody you do not trust you wish to understand that you simply can ne'er reach airtight security.

11 Oct 2013

YII FRAMEWORK: A SHORT REVIEW

yii framework , web , design , development , php

Yii Framework has recieved abundant buzz within the recent times. it's rock solid PHP based mostly full stack web frameworks for quickly developing net applications. Today, we shall see why Yii is completely different from others.

Yii comes with wealthy features: 

MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access management, system, testing, etc. It will scale back your development time considerably. The in-built elements won't solely ease your development curve however also will assist you start along with your application pretty quick.

Yii solely masses the options that you simply would like. No further resource usages, no overkills. it's powerful caching support. Cached web content load quite quicker than applications developed on different platforms. it's expressly designed to figure with efficiency with Ajax. you'll be able to seamlessly integrate Ajax requests with Yii.

Security comes as customary with Yii. The framework aims at providing most security for it’s users. in-built elements build information validation and input sanitation a breeze. It includes input validation, output filtering, SQL injection and Cross-site scripting hindrance. simply tweak these gems to your needs!

Yii helps you develop clean and reusable code. It follows the MVC pattern, making certain a transparent separation of logic and presentation. Following the Yii prescribed writing vogue, you get to create robust, well organized and simply maintainable code base.

You can transfer Yii from: http://www.yiiframework.com/. In future posts, we shall try and cover Yii development a lot of.

9 Oct 2013

8 Rules to Implement Secure File Uploads

web dseign html5 javascript css3 development

The IIS semicolon file extension issue prompted me to write a number of the principles to implement file uploads firmly. this can be particularly advanced as there's sometimes no simple way to validate the content of the file.

The overall goal is to create a group of defensive layers that tightly management the method of uploading the file and later retrieval of the file. The user will continually act indirectly with the file and ne'er directly access the file system while not application control.

1. create a new file name

Do not use the user provided file name as a file name on your native system. Instead, produce your own unpredictable file name. something sort of a hash (md5/sha1) works because it is easily validated (it is simply a hex number). perhaps add a serial range or a time stamp to avoid accidental collisions. you'll add a secret to the name to form it more durable to guess the file name. If you wish to stay the original file name: use a look-up table to link the validated user equipped file name to the server created name.

2. Store the file outside of your document root

If your document root is /var/www/html, produce a directory /var/www/uploads and use it to store

16 Sept 2013

PHP Useful techniques :You Need To Know


PHP is not very "cool" these days; it's in all probability the foremost misunderstood web language as a result of all the script kiddies use it to include files on their webpages and place up forms that get hacked hours later. however i feel PHP deserves an entire ton a lot of credit than it gets; it's quick, it integrates terribly nicely with Apache, it got all the proper features in version 5, and even if you do not like using it, there is always an opportunity you may have to write some anyway. So, perhaps the following tips will assist you out:

13 Sept 2013

communication between PHP and JavaScript


While developing a WordPress theme there are various occasions once you can need to communicate between PHP and jQuery (JavaScript). The idea could seam exhausting however it's very an easy method. To pass a variable from PHP to JS you'll use an equivalent approach like passing a PHP variable to CSS. first i'll show you how to pass an easy variable and so we'll try {and} pass an Array.


Most WordPress themes have custom admin panels, wherever individuals can customise their theme. most likely you'll need to pass variables from the Admin panel to alternative sections of your theme. perhaps you'll need to use them simply within the PHP, however you'll have an effect kind settings for the awesome Nivo Slider within your panel. once user sets up the slider within the admin panel you need to somehow pass the values to jQuery.

Passing variable:

I have my variable inside the PHP file, it is called $effect. Look at the code below:
<script type="text/javascript">
 jQuery(document).ready(function($) {
  $('#slider_wrapper').nivoSlider({
   effect: ''
  });
 });
</script>
First I even have added the script tag to embed the jQuery code within the PHP code, within the script tag there's the jQuery ready() function – i'm using it therefore the code won't be run before the DOM is totally loaded. #slider_wrapper is my div that holds the Nivo Slider, so we assign the nivoSlider operate to that so as a parameter we pass the $effect worth. The apostrophes round the PHP tags area unit important without them the code won’t work!

As you'll see this is very easy all you need to actually do is echo your variable (I have used esc_attr() to flee all of the ampersand, quotes and different unwanted stuff).
Passing array:

I will show you how to pass a two dimensional array from PHP to JS. The array is named $slides_data and contains some data concerning slides. the primary dimension defines the slide ID the second name of the property. Below you'll see the structure of the Array:
$slides_data[$post->ID]['id'] = $post->ID;    
$slides_data[$post->ID]['noise'] = 'true';
$slides_data[$post->ID]['rays'] = 'true';
$slides_data[$post->ID]['background'] = '#FFFFFF';
To pass this array to JavaScript first I even have created an array within JS with an equivalent length as the PHP array, to do this I used the PHP count function (this code ought to b placed within the script tags):
var slides_data = new Array( echo count($slides_data); ?>);
At this time we've array with one dimension that is empty, not spectacular however we will get there ;) currently we are going to create a PHP loop, which will undergo all of the elements and pass them to JS.
 foreach($slides_data as $slide) { ?>
 slides_data[ echo $slide['id']; ?>] = new Array(3);
 slides_data[ echo $slide['id']; ?>][0] = ' echo $slide['background'] ?>';
 slides_data[ echo $slide['id']; ?>][1] = ' echo $slide['noise'] ?>';
 slides_data[ echo $slide['id']; ?>][2] = ' echo $slide['rays'] ?>';
 }?>
For each element of $slide_data we are making new array (that approach we will get two dimentions), at that time we are assigning the values from php array to js array. Passing array isn't terribly totally different from passing an easy variable, thats it people.

I hope you had an honest read and that i was able to assist you in some way.

12 Sept 2013

Php 5.4 : New Features


php-development-design

In this article, I talked concerning PHP's stubborn, function-over-form approach to resolution the "Web problem" and also the fight to keep things easy. we were obtaining near releasing PHP getting.0 at the time. currently here we are nearly a decade later with a shiny new PHP 5.4.0 release, and whereas much is going on during that point, there are several things that haven't modified at all.

One issue that hasn't modified is that the ecosystem is as vital as it ever was. resolution the web drawback is concerning way more than selecting a scripting language. it's concerning the complete ecosystem around it. The LAMP stack has been strong for nearly 15 years currently and it's still popular, however we are starting to see strong alternatives. PHP-FPM with nginx has been gaining quality speedily as a result of the much improved support beginning in PHP 5.3 and further efficient in 5.4. The M, or database, a part of the stack is additionally starting to become way more diverse than it had been 8 years ago. the varied NoSQL solutions and MySQL Cluster give a richer set of choices than simply throwing everything into a MyISAM table.

7 Sept 2013

The Top 5 Most Used PHP features

learn-php-development-design
learn-php-development

1. Usort

usort allows the developer to sort an array based on a compare function that's configurable by the developer. This allows you to create more complex sorting algorithms that are not provided by the standard core array sort functions.
The callback/closure function has two parameters, which are two items in the array you have asked to sort on. It's then for you to decide if the first argument is greater, smaller or equal to the second argument. This is done by returning an integer value. Anything smaller than zero will assume the first argument is smaller than the second. Zero means the arguments are equal. Greater than zero means the first argument is larger than the second.
One great application for usort that we tend to use on a daily basis is to sort a simple multi-dimensional array. For example, let's say we have an array of students that consists of an associative array of name and age. By using the usort function along with acallback/closure function, we are able to pick the age and sort by ascending or descending.
For example, the code below is sorting by the age variable for each student in the students array. The callback/closure function provides the algorithm that compares the two ages and decides if the first age is greater than the second.

  1. $successful = usort($students, function  ($a, $b) {
  2.     return $a['age'] - $b['age'];
  3. });

2. Hashing API

There was an issue not too long ago with big-name sites getting hacked and insecure hashed passwords getting stolen. Back in the day, using the MD5 function was sufficient to hash a password, so it was secure. The problem with MD5 and SHA1 is that they are fast to perform the hashing algorithm. Along with the invention of faster processors and the utilisation of GPUs, people have the ability to process many hundreds of thousands of hashes per second, even on a standard desktop computer or laptop.
The new hashing API introduced in PHP5.5 provides an easy-to-use layer on top of bcrypt to create secure (for now) hashes that are a lot harder to solve by hackers. The example below shows how any string variable can be hashed. A salt will be created automatically and the hashing routing will have a cost of 15. The cost will make the hashing more secure but slower to complete.
  1. $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 20]);

3. SimpleXML Class

When we have to deal with XML files we tend to use the SimpleXML class. This easy-to-use class gives you the ability to read and edit XML files via objects. Using these objects gives you the ability to return values and iterate over arrays in the usual ways, as well as a set of simple methods to modify the XML’s structure. If you just need to grab something specific in the XML then using the built-in method of XPath, you can return a set of SimpleXML Element objects for just the path that you provided.
As well as reading XML, SimpleXML also provides the methods to create new documents and/or inject elements back into the imported XML. This can then be saved all in a few lines of code.
The SimpleXML class is provided as a standard extension for PHP. Although it’s not in the core of PHP, it is enabled by default.
The example below shows a very simple example to get a list of public photos from Flickr and display the content html of each photo.
  1. /* Load flickr Public Feed */
  2. $xml = simplexml_load_file('http://api.flickr.com/services/feeds/photos_public.gne');
  3. if(is_object($xml)){
  4.     /* Get each entry and echo the content tag */
  5.     foreach($xml->entry as $photo) echo $photo->content;
  6. }

4. glob

The glob function provides an easy one-line solution for creating an array of path names using a pattern you provide. glob may not be as fast as using the opendir and readdir combination, but if you just want to iterate over a directory, or you’re searching for a specific file type such as an image, then using glob could be a good solution to your problem.
The first argument is a glob pattern string that's similar to a regular expression in the way that it functions, but the syntax to create the pattern has some differences. This allows you to search for a varied subset of files and folders that are contained in a directory.
One big disadvantage of using glob is that all the results are stored into memory in one go. If you have a very large folder full of files you can soon run out of memory, and in this instance, it would be better to use opendir and readdir as it creates a read stream buffer.
Using the example below we are able to return all the image files in the $imagePath directory. An array will be returned to the $images variable.
  1. /* Find all image files in image folder */
  2. $images = glob($imagePath.'*.{gif,jpeg,jpg,png}',GLOB_BRACE);

5. array_map

The standard core functions that PHP provide tend to perform faster, than creating your own similar functions using PHP code. A great example of this is utilising array_map instead of creating a for or which loop. array_map allows you to create a function called a callback that will be applied to every item in an array you supply.
For example, if you had an array of lowercase letters, a callback function can be created to uppercase all the characters in the array. On a small-sized array, the speed increase would be quite small, but once you start using larger arrays, you can really see a significant difference in speed.
In the example below we are converting the alphabet from lowercase to uppercase. We have provided the array_map function with a string of the name of the function we want to process. In this case we are using strtoupper to convert each letter in the array.

If there’s a need for more complex functionality, we can also provide the array_map function, a closure like in the usort example above.
  1. $alphabet=array();
  2. /* Create lower Case Alphabet */
  3. for($i=97;$i<123;$i++) $alphabet[]=chr($i);
  4. /* Convert to Uppercase */
  5. $upperCaseAlphabet = array_map('strtoupper',$alphabet);