background preloader

Php

Facebook Twitter

Easy Wins For More Performant PHP. Introduction Making your website more performant can require a lot of layers. From setting up a reverse-proxy cache with Varnish to configuring a group of load balancers, there are many well-documented options. What if you're just starting out? What if you have a smaller application? Are there things you can do now that will make difference?

This article will explore easy wins for more performant PHP you can implement either as standard practices for your development team or principles you can retrofit for an existing application. At Minimum, Upgrade to PHP 5.4 As of this article, the latest version of PHP is currently 5.5.5. If PHP 5.5.5 isn't an option, you MUST minimally begin with PHP 5.4. Running Drupal? Autoload Autoloading involves including classes in files that are used throughout your application without having to manually reference the file paths. We can use Composer to achieve this result. Composer has been covered in past articles for dependency management. Profile OpCode Caching. Laravel Cheat Sheet. Check Member's/ User's Online or Offline Status. Introduction The following piece of code will calculate the last visited time of a Member/User and calculate the time difference with the current time. And if the Member/User's last visited time is greater than 10 minutes then that will be considered OFFLINE status, otherwise ONLINE.

Background I was just searching for a time difference code in Bakery but couldn't find any simple code. I developed and used the following code to calculate the time a User/Member is online or offline. Using the code There are only three steps to follow. "I am assuming that you have a table named MEMBER (you can customize it according to your requirements)". Make a field last_visit (DATETIME) in MEMBER table.For app controller: Simply use the following code in your .ctp file according to your demand. <! Accessing Incoming PUT Data from PHP. Recently I started writing a REST service. I began in the usual way, writing a php script, calling it with a GET request, accessing the variables using the PHP superglobal variable $_GET.

I wrote code to handle a POST request and used the variables I found in $_POST. Then I tried to write a PUT request. PHP doesn't have a built-in way to do this, and at first I was a little confused as to how I could reach this information. It turns out that this can be read from the incoming stream to PHP, file_get_contents(" The above line provided me with a query string similar to what you might see on the URL with a GET request. key/value pairs separated by question marks.

Parse_str(file_get_contents(" This loads the variable $post_vars with the associative array of variables just like you'd expect to see from a GET request. Simple Example And here's what happened when I request the same script using two different HTTP verbs. Via GET: Via PUT: 20 All Too Common Coding Pitfalls For Beginners. Regardless of our current skill level, we all were beginners at one point in time.

Making classic beginner mistakes comes with the territory. Today, we've asked a variety of Nettuts+ staff authors to chime in with their list of pitfalls and solutions - in a variety of languages. Learn from our mistakes; don't do these things! JavaScript Tips 1 - Unnecessary DOM Manipulation The DOM is slow. This code actually modifies the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string.

When building large strings, storing each piece of the string as an item within an array element and calling join() is arguably more elegant than string concatenation. 2 - Inconsistent Variable & Function Names in JavaScript It wouldn't make sense to add another variable, called Something. 3 - Use hasOwnProperty() in for...in Loops 5 - Event Binding.

PDO

Login. Formulaires. PHP Coding Guidelines | PHP Developer. These are the guidelines that I follow when writing my PHP scripts, unless a coding standard already exists for the project I’m working on. It can be helpful to have something like this if you’re working on a joint project. N.B. These are only the guidelines that I personally chose to follow for the code I write.

This is not an indication that any other coding styles, guidelines or standards are wrong. Why are guidelines important? First of all, let’s make one point clear: it doesn’t matter what your guidelines are, so long as everyone understands and sticks to them. It cannot be emphasised enough that guidelines are only useful if they are followed. If you are running a joint project, you might consider putting your foot down and basically refuse to accept any code that does not conform to your published guidelines, regardless of its technical merit (or lack thereof). Editor settings Tabs v. spaces Ahh, the endless debate of tabs v. spaces. Linefeeds Naming conventions Variable names N.B. Php-mobile-detect - PHP class for mobile device detection. Working with Files in PHP. You may well be familiar with databases such as MySQL and Access which are an ever-increasingly common means of storing data. But data is also stored in files, like Word documents, event logs, spreadsheets, image files, and so on.

Databases generally require a special query language to retrieve information, whereas files are ‘flat’ and usually appear as a stream of text. Most often when working with files you’ll read from or write to them. When you want to read the contents of a file you first have to open it, then read as much of the contents as you want, then close the file when you’re finished.

When writing to a file, it also needs to be opened (or perhaps created if it doesn’t already exist), then you write your data to it, and close the file when you have finished. You may also find it useful to find out more about the file by examining its attributes before you start working with it. File Attributes File Size The function filesize() retrieves the size of the file in bytes. Summary. S blog: PHP Sucks! But I Like It! I read a rather interesting post yesterday called PHP: a fractal of bad design. It's been getting a lot of traffic among the PHP community lately because it's rather inflammatory. But to be honest, it does make a lot of really good points. It also makes a lot of mistakes and misses a bigger picture. A Few Mistakes The post makes quite a few mistakes and odd apples to oranges comparisons. No Debugger - PHP has xdebug which works quite well as an interactive debugger.Lack Of Threading - This is true, but he lists it as a difficulty, and I list it as a positive, since the application lifecycle is per request (I'll expand more on this shortly).== Is Useless - Actually, it's quite useful, if used appropriately.

Now, out of such a long post, that's a really short list of gripes. My Stance I actually agree with the majority of what he said in his post. But it's also incredibly powerful. As Brandon Savage points out: It's About The Customer. HTTP is a first-class citizen. Thoughts? Phpquery - phpQuery - jQuery port to PHP. Pewpew - PHP's Embedded Webserver | PHP-GTK Community. This is a tiny tool that allows you to launch the built in PHP 5.4 HTTP test server with a few clicks. It allows you to select which PHP binary you want to use (in case you have multiple on your system) and the document root of the test server. Click the picture for a larger screenshot of the application running. Keep in mind PHP-GTK 2 does not currently support PHP 5.4.

On Windows it is easy to install PHP-GTK separate from PHP 5.4 however on Unix systems you're going to have to do all that nifty --prefix play if you want side by side PHP versions. The built in PHP test HTTP server is only in 5.4+ so that is why I bring that up. You can find it at Github. Grocery Crud - Un générateur de CRUD basé sur CodeIgniter. Grocery Crud est un générateur de CRUD PHP basé sur le framework CodeIgniter. Dans vos applications web et en particulier dans vos espaces d'administration, vous répétez toujours les mêmes tâches à savoir: Créer une fonction de listing, de création d'une nouvelle entrée, la fonction de modification et celle de suppression.

En d'autres terme, créer un CRUD (Create Read Update Delete). Bien que basé sur le framework PHP CodeIgniter, Grocery Crud ne nécessite pas de connaissances dans le domaine. Avec quelques lignes de code, l'outil va générer un CRUD simple et efficace: 01.function my_boss_is_in_a_hurry() 03. 04. 06. 08. Vous l'aurez compris, dans cet exemple, le générateur va créer un CRUD à partir de la table customers avec les champs spécifiés avec la méthode columns. Le CRUD créé sera complet et avec une touche d'ajax, très ergonomique: On retrouve bien le générateur d'administration de Symfony 1.x ou le générateur de CRUD de la version 2.

Site Officiel. PHP Bug Lost - Déboguer et monitorer vos applications. Comme le Profiler de Symfony2, PHP Bug Lost permet d'ajouter une console de débug et de monitoring sur ses sites à partir d'un seul fichier. En ajoutant ce script, vous pourrez monitorer et déboguer plus facilement vos applications en regroupant toutes les informations essentielles en bas de page, à la manière du profiler de Sf2 ou de Firebug. Ainsi en mode console de déboguage, vous pourrez visualiser les variables instanciées sur votre page, visualiser les requêtes SQL, gérer la gestion de message (erreur, warning, message), le temps d'exécution des pages, etc. En phase de production, il est possible de paramétrer l'envoi automatique d'alertes par email en fonction des variables prédéfinies comme le temps d'exécution de requêtes sql qui dépasseraient 30 secondes,… Site officiel. Gérer l’envoi de SMS en PHP : TextMagic vous aide. Avez-vous déjà remplacé l’envoi d’un mail par un SMS ?

En effet, tout comme de nombreux sites le proposent désormais, envoyer un notification par un message texte, autrement dit un SMS, au lieu d’une notifications par courrier électronique, autrement dit un mail, peut être très utile dans le cas d’informations sensibles, ou urgentes. Après quelques fouilles sur le Web, j’ai retenu quelques solutions, dont il est très simple de mettre en place. En tout cas pas plus difficile que d’envoyer un mail… Laissez-moi vous montrer comment ! À mon insu, l’envoi de SMS peut être très facile puisqu’il vous suffit d’envoyer un mail… En effet, vous pouvez envoyer votre texte à une adresse e-mail et il sera délivré au numéro que vous avez spécifié. En revanche, cette solution est, dans certain cas, peu optimale… Pourquoi ? Ci-dessous un schéma simplifié de la façon dont un message peut être envoyé à partir d’une application Web sur un dispositif sans fil : Source de l’image TextMagic en quelques mots … Hypertext Preprocessor.

Creating a Secure Login System the Right Way | Tinsology. Making a custom login system is a common task for beginning PHP developers. Jumping right into it, however, may not be the best approach. There are several important aspects to building a login system that not only makes it work, but makes it safe. Updated on December 15th 2009: Added Session Control Section Updated on December 15th 2010: Switched to sha256 Getting Started To begin with, we’ll create our login form. The above example is stripped down; there is no formatting or styles so it will most likely won’t look to great if you copy and paste the code.

Notice that our input fields are given name attributes, this is important as we will need to identify and access these values by this name. Storing our Data Actually we can’t process the data just yet. In the above SQL code we create a table called users having columns id, username, password, and salt. There are a few keywords in the above code that I’ll define for you. Each column also has a data type. Populating our Table Sign Me Up. 10 super useful PHP snippets you probably haven’t seen. Text messaging with PHP using the TextMagic API If for some reason, you need to send text messages to your clients cell phones, you should definitely have a look to TextMagic. They provide an easy API which allow you to send SMS to cell phones.

Please note that the TextMagic service isn’t free. The example below shows how easy it is to send a SMS to a cell phone using the TextMagic API: // Include the TextMagic PHP lib require('textmagic-sms-api-php/TextMagicAPI.php'); // Set the username and password information $username = 'myusername'; $password = 'mypassword'; // Create a new instance of TM $router = new TextMagicAPI(array( 'username' => $username, 'password' => $password )); // Send a text message to '999-123-4567' $result = $router->send('Wake up!

' Source: Detect location by IP Here is an useful code snippet to detect the location of a specific IP. Source: Check if server is HTTPS. If PHP Were British. When Rasmus Lerdorf first put PHP together, he - quite sensibly, despite his heritage - chose not to write it in Greenlandic or Danish. Good job too - that would have been rather unpleasant to work with. He opted instead, being in Canada, for a more local tongue. No, not French. Not Canadian English either. No, he went for that bastard dialect of the Queen's English commonly referred to as "US English". PHP developers in Britain have been grumpy about this ever since. A Slap in the Face $variable_name $variable_name The first, but maybe the most important, of many changes that will allow PHP to achieve a more elegant feel is to remove that symbol so beloved by the US and replace it with something altogether more refined. £variable_name £variable_name Getting Started How many of today's British programmers have been put off at the outset by the brazen informality of this simple yet obscenely Americanised program, colloquially referred to as "Hello World"?

Abbreviations Eloquence Spelling Manners. Free Online Tutorial PHP - PAGE. Twig - The flexible, fast, and secure PHP template engine - Homepage. Détecter si le visiteur vient d’un iPhone iPad iPod Android | eBuildy blog, Web, Adobe flex, JQuery,Flash,Prestashop. Avec tous ces mobiles et surtout les forfaits qui vont avec, la part des visiteurs venant d’un mobile est à présent significative. Le hic est que les tailles d’écran proposé (à part le iPad qui n’est pas un mobile…) est souvent minuscule, et donc, très souvent le site visité est inapproprié à la navigation sous mobile. Il existe 3 solutions de détection: Avec un fichier .htaccessAvec un script PhpAvec du Javascript Détection htaccess L’avantage: le visiteur est redirigé de suite sans charger la page par défaut.

La redirection est donc “propre” (par exemple sur un sous domaine: RewriteCond %{HTTP_USER_AGENT} "ipod|iphone|ipad" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "android|palm" RewriteRule (.*) [R=301,L] Ce code est très simple, mais demande de tout refaire dans le sous domaine (images, javascript, css et surtout services Php JSON ou XML si vous en avez…). RewriteCond %{REQUEST_URI} !

Détection Php. 10 super useful PHP snippets. 11 jQuery and PHP Tutorials. Geo Tools. Adaptive Images - Des images adaptées auto aux résolutions écran. [PHP 5.1] Classe d'Upload et Redimensionnement. Object-Oriented PHP: Working with Inheritance. Dompdf - HTML to PDF converter (PHP5) Benchmarks. Phar – PHP archiving practice. Les flashcodes, comment les générer automatiquement et facilement avec PHP. Photobooth with PHP, jQuery and CSS3 | Tutorialzine | Webdesign code.