background preloader

9 Useful PHP Functions and Features You Need to Know

9 Useful PHP Functions and Features You Need to Know
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+. Even after using PHP for years, we stumble upon functions and features that we did not know about. Some of these can be quite useful, yet underused. 1. You may already know that PHP allows you to define functions with optional arguments. First, here is an example with just optional arguments: Now, let's see how we can build a function that accepts any number of arguments. 2. Many PHP functions have long and descriptive names. Think of it like a more capable version of the scandir() function. You can fetch multiple file types like this: Note that the files can actually be returned with a path, depending on your query: If you want to get the full path to each file, you can just call the realpath() function on the returned values: 3. By observing the memory usage of your scripts, you may be able optimize your code better. PHP has a garbage collector and a pretty complex memory manager. 4. 5.

Créer un menu à onglets avec CSS Introduction Propos Je vais montrer comment utiliser le langage des feuilles de style en cascade (CSS) pour créer un menu à onglets. La technique utilisée n'a rien de nouveau, mais elle sera l'occasion d'aborder plusieurs sujets rarement traités en un même endroit. Tout au long de mon exposé, je ferai référence à des considérations méthodologiques, notamment sur les principes de développement, les outils de validation et les raccourcis d'écriture CSS. Les plus pressés peuvent aller directement au fichier HTML complet, ainsi qu'aux feuilles de style « normal.css », « ie.css » et « ie6.css ». Explication du projet Le menu doit ressembler à ce qui suit : Ce menu doit également répondre aux exigences suivantes : Bref, le résultat doit être valide, accessible, multi-navigateur et indépendant de CSS, de JavaScript ou d'un outil de pointage particulier. Matériel et préparation Pour réaliser ce projet, j'aurai besoin des trois images suivantes : Vous pouvez choisir de faire autrement. Retourner au plan

Criando funções que aceitem N argumentos Hoje vou mostrar pra vocês como é facil criar uma função que aceite um número indeterminado de argumentos, é o mesmo caso das funções min() e max(), onde você pode passar 1, 2 ou 200 argumentos e ela irá funcionar perfeitamente. O ponto-chave desse tipo de função é o uso de duas outras funções nativas do PHP, são elas: func_num_args() e func_get_args(). A função func_num_args() (quando usada dentro de uma outra função) retorna o número de argumentos que foram passados para essa função. E a função func_get_args() retorna uma lista (array) com os argumentos que foram passados para essa função. Vamos criar uma função para calcular a média de uma quantiade qualquer de números: Perceba que, na definição da função, não colocamos nada no lugar dos parâmetros/argumentos que ela necessita… Exatamente por que a quantidade de argumentos será variável. Agora vamos pegar o total e a lista de argumentos passados para a função: No final das contas, nossa função ficou assim: O uso dela é bem simples:

SQL Injection Cheat Sheet Find and exploit SQL Injections with free Netsparker SQL Injection Scanner SQL Injection Cheat Sheet, Document Version 1.4 About SQL Injection Cheat Sheet Currently only for MySQL and Microsoft SQL Server, some ORACLE and some PostgreSQL. Most of samples are not correct for every single situation. Samples are provided to allow reader to get basic idea of a potential attack and almost every section includes a brief information about itself. Examples; (MS) means : MySQL and SQL Server etc. Table Of Contents Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks Ending / Commenting Out / Line Comments Line Comments Comments out rest of the query. -- (SM) DROP sampletable;-- # (M) DROP sampletable;# Line Comments Sample SQL Injection Attacks Username: admin'-- SELECT * FROM members WHERE username = 'admin'-- This is going to log you as admin user, because rest of the SQL query will be ignored. Inline Comments Classical Inline Comment SQL Injection Attack Samples ID: /*! Stacking Queries Hints,

PHP Gerenciar é sempre o maior desafio quando falamos de empresas, é uma tarefa difícil, desgastante e que exige o máximo da nossa produtividade, mas não se preocupe, existem ferramentas desenvolvidas … Alguns programadores que iniciam com javascript acabam passando sempre por problemas de como entender Hoisting e Escopo, afinal WTF Man ??? Em mais uma promoção em parceria com a Novatec Editora, irei sortear aqui o livro Curso intensivo de Python. No mês passado na Caelum estava conversando com o time da Alura sobre quais features podiamos criar. Em mais uma promoção em parceria com a Novatec Editora, irei sortear aqui o livro [Expressões Regulares] Uma Abordagem Divertida. Esse é meu primeiro review pra um livro da editora Casa do Código. Em mais uma promoção em parceria com a Novatec Editora, irei sortear aqui o livro Lauren Ipsum onde o autor ensina computação para crianças diferentemente de tudo o que já …

CSS Sprite Generator | Project Fondue PHP has a cool function that automatically highlights PHP code called highlight_string(); Theoretically this could be used to roll your own code highlighting on a site, rather than rely on JavaScript or some kind of external service to do it. In this article I'll show you the basics of how it works, then extended it with a few tricks. Since JavaScript is so similar to PHP in syntax, we can trick the function into highlighting JavaScript code as well. Then finally how we can bust out some smarts to auto-tab the code. Special thanks to Benjamin Mayo (Darren Beige) who wrote the format_javascript() function we'll check out below. Basic Usage The highlight_string() function just accepts a string, which must begin with <? <? The resulting HTML is: Which looks like this: Pretty wild eh? Trick it into highlighting JavaScript Benjamin Mayo (Darren Beige) put together a PHP function that would trick PHP into highlighting JavaScript code instead of exclusively PHP. View Demo Download Files How it works

VirtualBox et Ubuntu Server, un vrai serveur de développement en local Lorsque l’on développe des sites web, il est bien utile d’avoir un serveur où faire ses tests, ne serait-ce que pour éviter de casser un site déjà en ligne. Pour cette raison, il n’est pas rare d’installer sur sa machine locale des programmes tels que EasyPHP ou WAMP Server (sous windows). Mais ces logiciels sont souvent assez limités, et parfois assez loin de la réalité d’un serveur web. Pour cette raison, j’ai pour habitude de configurer une machine virtuelle me servant de serveur local, sur laquelle j’installerai le strict minimum pour faire tourner mes projets en cours de développement. Le but du jeu est de configurer la machine virtuelle pour qu’elle fonctionne exactement de la même façon que si je me connectais à un serveur distant chez mon hébergeur. Puisque la configuration d’une telle machine est parfois un poil compliquée, voici un tutoriel pour créer pas à pas votre propre serveur local avec VirtualBox et Ubuntu Serveur. Installer VirtualBox Tout d’abord, pourquoi VirtualBox ?

jQuery and PHP inline editing Inline editing as it’s known, or being able to edit content directly on a page is a great tool have under your belt. I’m going to run through exactly how it works as well as how to POST the updated text content through to a PHP script for server side processing to put in the database. The Code It looks a little complex so i’m going to quickly run through exactly what’s going on. When you visit the demo page are presented with a block of text. If you hover your mouse over the text you’ll see a little edit icon similar to when you want to edit content on FaceBook.If the user clicks on the block of code the text is replaced with a form textarea with the option to save or cancel any changes. Now in a little more detail This tutorial uses binding and unbinding. The PHP In this example I haven’t added the database connection script. The HTML The HTML is simply a list item with the class ‘inlineEdit’ this makes the content of the element editable.

Skeleton: Beautiful Boilerplate for Responsive, Mobile-Friendly Development What Is It? Skeleton is a small collection of CSS files that can help you rapidly develop sites that look beautiful at any size, be it a 17" laptop screen or an iPhone. Skeleton is built on three core principles: Responsive Grid Down To Mobile Skeleton has a familiar, lightweight 960 grid as its base, but elegantly scales down to downsized browser windows, tablets, mobile phones (in landscape and portrait). Fast to Start Skeleton is a tool for rapid development. Style Agnostic Skeleton is not a UI framework. The Grid Skeleton's base grid is a variation of the 960 grid system. One Eleven Two Ten Three Nine Four Eight Five Seven Six Code Example Typography The typography of Skeleton is designed to create a strong hierarchy with basic styles. Heading <h3> Heading <h4> Heading <h5> Heading <h6> This is a blockquote style example. Buttons Buttons are intended for action and thus should have appropriate weight. Click Me For Action Forms Support for Skeleton Examples & Extensions Downloads (A la 960.gs PSD template)

Activer les logs de requêtes MySQL à la volée - Le blog d'un DSI Voici une astuce pour activer/désactiver les logs de requêtes (general log) de MySQL sans avoir à redémarrer le service. 1. Préparation du serveur Il va quand même falloir redémarrer le service au moins une fois pour activer un paramètres par défaut : l'emplacement du fichier de log. Ceci est facultatif mais nous évitera d'avoir à le respécifier à chaque fois. Pour ce faire, il suffit d'éditer le fichier my.ini (ou my.cnf sous Linux) et d'ajouter/modifier la directive suivante : general_log_file = E:/MySQL/Logs/query.log il faut donc logiquement redémarrer le service pour prendre en compte ce paramètre. 2. Dans une invite de commande MySQL ou tout autre outil capable d'exécuter des requêtes mysql avec un utilisateur ayant des droits d'admin, il faut lancer la commande suivante : SET GLOBAL general_log = 'ON'; Les logs sont activés et ajoutés au fichier défini ci-dessus. 3. Il suffit de repasser le paramètre à OFF : SET GLOBAL general_log = 'OFF';

Related: