Mostrando entradas con la etiqueta class. Mostrar todas las entradas
Mostrando entradas con la etiqueta class. Mostrar todas las entradas

2012-07-13

PHPExcel y CodeIgniter para generara una exportacion a excel

Esto es un ejemplo de como implementar PHPExcel desde CodeIgniter.
Para que funciona sin problema las clases de PHPExcel las tener que poner dentro del 
path: "/application/libraries" donde esta instalado tu framework y de tu desarrollo, no en la carpeta 
"/system/libraries" ya que acá solo van las librerias del propio framework.



Prerequisitos para PHPExcel:
  1. PHP version 5.2.0 o superior
  2. PHP extension php_zip enabled
  3. PHP extension php_xml enabled
  4. PHP extension php_gd2 enabled

Link: CodeIgniter
Link: PHPExcel
Link: phpexcel.codeplex.com
Link con mas informacion de referencia: phpexcel-cheatsheet

2011-01-15

Class generador de Tree con patron MPTT + PHP + Tutoriales al estilo CakePHP

Clase para crear tree recuperandolo de la base de datos. Al mismo estilo que lo hace CakePHP

Link a la class:
mptt + bd class.zip 

childcount()
getpath()
tree()
generatetreelist()
extends DB class, for queries and execution of SQL (http://slaout.linux62.org/php/index.html)


Cómo convertir esta matriz MPTT en una estructura de árbol en PHP?
Link:
http://es.w3support.net/index.php?db=so&id=823071

SQL para MySQL donde utiliza el patron MPTT para poder genera el Tree
Link:
http://stackoverflow.com/questions/1638137/mptt-modified-preorder-tree-traversal-issue-in-php

Componet para utilizar con el frameword KOHANA para poder generar menus Tree
Link:
http://code.google.com/p/kohana-mptt/wiki/Documentation

2010-09-14

Dibi es una libreria para poder abstraerce de la base de datos.


Dibi es una libreria para poder abstraerce de la base de datos.
Link a la librer DIBI


Como utilizar las clases de Zend Framework desde nuestro proyecto web.

Como utilizar las clases de Zend Framework desde nuestro proyecto web que no trabaja con el Framework de Zend en modo MVC.

Paso 1.
Bajamos las librería de ZF desde el sitio oficial http://framework.zend.com/download/latest/
Nota: Estos ejemplos fue testeado en la versión de Zend Framework 1.10

Paso 2.
Descomprimimos el archivo que bajamos y sacamos la carpeta “library” en la carpeta que tenemos nuestro proyecto.

Paso 3.
En la carpeta de nuestro proyecto creamos un archivo llamado config-zf.php que es donde vamos a configurar donde están las clases del ZF.




Paso 4.
Creamo el archivo "test-zf.php" en donde vamos a utilizar la class “Zend_Feed  en el cual hay que poner “require ‘config-zf.php’” para que puede encontrar las clases que queremos utilizar de Zend Framework en este caso es la class "Zend_Feed" para poder leer un archivo rss.






Bueno eso es todo espero que le sea útil y empiecen a trabajar con las clases de Zend Framework sin utilizar toda la estructura del mismo. Dejando para un futuro la migración si queres migrar a la estructura de MVC de ZF.

2010-09-03

Clase para acceder a Google Weather

Interesante clase para acceder de un modo sencillo al servicio metereológico de Google.
Ejemplo:
  1. <?php  
  2. class GoogleWeatherAPI {  
  3.     private $city_code = '';  
  4.     private $city = '';  
  5.     private $domain = 'www.google.com';  
  6.     private $prefix_images = '';  
  7.     private $current_conditions = array();  
  8.     private $forecast_conditions = array();  
  9.     private $is_found = true;  
  10.   
  11.     /**  
  12.     * Class constructor  
  13.     * @param $city_code is the label of the city  
  14.     * @param $lang the lang of the return weather labels  
  15.     * @return ...  
  16.     */  
  17.        
  18.     function __construct ($city_code,$lang='fr') {  
  19.         $this->city_code = $city_code;  
  20.         $this->prefix_images = 'http://'.$this->domain;  
  21.         $this->url = 'http://'.$this->domain.'/ig/api?weather='.urlencode($this->city_code).'&hl='.$lang;  
  22.           
  23.         $content = utf8_encode(file_get_contents($this->url));  
  24.           
  25.         $xml = simplexml_load_string($content);  
  26.           
  27.         if(!isset($xml->weather->problem_cause)) {  
  28.               
  29.             $xml = simplexml_load_string($content);  
  30.   
  31.             $this->city = (string)$xml->weather->forecast_information->city->attributes()->data;  
  32.   
  33.             $this->current_conditions['condition'] = (string)$xml->weather->current_conditions->condition->attributes()->data;  
  34.             $this->current_conditions['temp_f'] = (string)$xml->weather->current_conditions->temp_f->attributes()->data;  
  35.             $this->current_conditions['temp_c'] = (string)$xml->weather->current_conditions->temp_c->attributes()->data;  
  36.             $this->current_conditions['humidity'] = (string)$xml->weather->current_conditions->humidity->attributes()->data;  
  37.             $this->current_conditions['icon'] = $this->prefix_images.(string)$xml->weather->current_conditions->icon->attributes()->data;  
  38.             $this->current_conditions['wind_condition'] = (string)$xml->weather->current_conditions->wind_condition->attributes()->data;  
  39.               
  40.             foreach($xml->weather->forecast_conditions as $this->forecast_conditions_value) {  
  41.                 $this->forecast_conditions_temp = array();  
  42.                 $this->forecast_conditions_temp['day_of_week'] = (string)$this->forecast_conditions_value->day_of_week->attributes()->data;  
  43.                 $this->forecast_conditions_temp['low'] = (string)$this->forecast_conditions_value->low->attributes()->data;  
  44.                 $this->forecast_conditions_temp['high'] = (string)$this->forecast_conditions_value->high->attributes()->data;  
  45.                 $this->forecast_conditions_temp['icon'] = $this->prefix_images.(string)$this->forecast_conditions_value->icon->attributes()->data;  
  46.                 $this->forecast_conditions_temp['condition'] = (string)$this->forecast_conditions_value->condition->attributes()->data;  
  47.                 $this->forecast_conditions []= $this->forecast_conditions_temp;  
  48.             }  
  49.         } else {  
  50.             $this->is_found = false;  
  51.         }  
  52.     }  
  53.     function getCity() {  
  54.         return $this->city;  
  55.     }  
  56.     function getCurrent() {  
  57.         return $this->current_conditions;  
  58.     }  
  59.     function getForecast() {  
  60.         return $this->forecast_conditions;  
  61.     }  
  62.     function isFound() {  
  63.         return $this->is_found;  
  64.     }  
  65.       
  66. }  
  67. $gweather = new GoogleWeatherAPI('valencia','es');   
  68. if($gweather->isFound()) {  
  69.     echo '<pre>'; print_r($gweather->getCity()); echo '</pre>';  
  70.     echo '<pre>'; print_r($gweather->getCurrent()); echo '</pre>';  
  71.     echo '<pre>'; print_r($gweather->getForecast()); echo '</pre>';  
  72. }  
  73. ?>  
Ver ejemplo en funcionamiento » »
Google Weather API » »

PHP Data Objects – PDO

PDO es una interface de acceso a datos que nos permite, mediante varios drivers, conectarnos a diferentes bases de datos. Olvídate de esto, esto, esto e incluso de esto otro, ahora solo debes preocuparte por PDO. Esta librería escrita en C viene activada por defecto desde PHP 5.1 por lo cual la podrás utilizar en la mayoría de los servidores que actualmente soportan PHP5.

La conexión

Para todos los ejemplos utilizaré MySQL, pero también podria utilizar cualquier otra de las bases de datos soportadas adaptando un poco el código que sigue:
1
$db = new PDO('driver:host=servidor;dbname=bd', user, pass);
Y el ejemplo práctico:
1
$db = new PDO('mysql:host=localhost;dbname=pruebas', 'root', '');
Ahora en $db tenemos una instancia de PDO_MySQL

Primera consulta

Para la primer consulta haremos uso de prepare, execute y fetch.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
require 'conexion.php';
 
//Nos conectamos
$db = new PDO('mysql:host=' . $servidor . ';dbname=' . $bd, $usuario, $contrasenia);
 
//Preparamos la consulta para dejarla lista para su ejecución
$consulta = $db->prepare('SELECT * FROM items');
 
//Ejecutamos la consulta
$consulta->execute();
 
//Recorremos el set de resultados mostrando la información
while($fila = $consulta->fetch())
{
 echo $fila[0] . '  ' . $fila[1] . '<br />';
}
 
//Cerramos la conexión a la vez que destruimos nuestra instancia de PDO
$db = null;

Como verás no es nada complicado y es muy similar a lo que nos acostumbramos a hacer con las clásicas funciones mysql_.
Con las funciones MySQL también debíamos validar estrictamente los parámetros de entrada para evitar inyecciones SQL. En este caso, PDO lo hará por nosotros siempre y cuando utilicemos alguna de las varias formas que nos provee para realizar consultas parametrizadas. Este es un ejemplo:
1
2
3
4
5
//Preparamos la consulta marcando donde irán los parametros con ?
$consulta = $db->prepare('SELECT * FROM items WHERE id_item = ? OR id_item = ?');
 
//Ejecutamos la consulta incluyendo los parámetros en el mismo orden en el que deben incluirse
$consulta->execute(array(2, 4));
El ejemplo anterior generará una consulta de la siguiente manera:
1
SELECT * FROM items WHERE id_item = '2' OR id_item = '4'
Otra manera de hacer lo mismo:
1
2
3
4
5
6
7
8
9
10
$id = 6;
 
//Esta vez utilizamos un nombre-clave para cada parámetro
$consulta = $db->prepare('SELECT * FROM items WHERE id_item = :id');
 
//Con dicho nombre-clave, agregamos el valor del parámetro
$consulta->bindParam(':id', $id);
 
//Y ejecutamos la consulta
$consulta->execute();
1
SELECT * FROM items WHERE id_item = '6'
Ahora bien, si no confían, intenten inyectar SQL concatenando alguna sentencia en la variable $id y verán los resultados ;-)

Altas, Bajas y Modificaciones

El mecanismo sigue siendo el mismo que en las consultas anteriores, preparar la consulta, agregar los parámetros y ejecutar.
alta
1
2
3
4
5
6
$item = $_POST['item'];
 
$inserta = $db->prepare('INSERT INTO items (item) VALUES (:item)');
$inserta->bindParam(':item', $item);
 
$inserta->execute();
baja
1
2
3
4
5
6
$id = $_GET['id'];
 
$borra = $db->prepare('DELETE FROM items WHERE id_item = :id');
$borra->bindParam(':id', $id);
 
$borra->execute();
modificación
1
2
3
4
5
6
7
8
$item = $_POST['item'];
$id = $_POST['id'];
 
$actualiza = $db->prepare('UPDATE items SET item = :item WHERE id_item = :id');
$actualiza->bindParam(':item', $item);
$actualiza->bindParam(':id', $id);
 
$actualiza->execute();
Y esto es todo por el momento, solo un primer acercamiento a PDO. Podés bajarte todos estos ejemplos y varios mas desde aquí. Para que funcionen debes contar con un servidor que soporte PHP5 con las librerías PDO_MySQL instaladas, debes crear una base de datos, ejecutar el fichero items.sql y editar el archivo conexion.php con los datos que correspondan.

2010-09-02

Clase PHP para generar documentos PDF a partir de HTML

mPDF es una clase de PHP que genera archivos PDF a partir de HTML codificado en UTF-8. Se basa en FPDF, HTML2FPDF, y UFPDF, con una serie de mejoras. La gran mejora aportada respecto a las anteriormente mencionadas librerías, es que permite generar archivos PDF "al vuelo", a partir de HTML, con soporte a estilos CSS.
mPDF » »

TimThumb: script en PHP para generar thumbnails

TimThumb es un script realizado en PHP que permite hacer thumbnails "al vuelo" de imágenes. El script es opensource y muy sencillo de utilizar. Tan sólo hay que copiar el código fuente del script en un documento denominado por ejemplo "timthumb.php", guardarlo en una carpeta del sitio web (por ejemplo "scripts") y realizar una llamada como la siguiente:
  1. <img src="/scripts/timthumb.php?src=/images/whatever.jpg&h=150&w=150&zc=1" alt="">  
Se requiere de la librería GD y de los permisos necesarios de escritura.
TimThumb » »

2010-08-08

NuCaptcha, captchas basados en vídeos


Parecía ser una buena solución pero en la práctica, los captchas nos han traído más molestias que beneficios, llegando en alguna ocasión al punto, al menos en mi caso, de dejar de registrarme o comentar en sitios web, debido a que me denegaban el código que introducía, a pesar, según qué casos, los introducía correctamente según me mostraban en las imágenes. Pues bien, ahora viene una nueva alternativa a los captchas con NuCaptcha.

NuCaptcha es, tal y como indica en su web, una plataforma de seguridad que usa el vídeo en movimiento para autenticar la interacción web humana. Y nada mejor que ver los ejemplos que nos indica en su portada, donde sustituye las imágenes con los códigos distorsionados por vídeos en movimiento, reproducidos mediante Adobe Flash, donde podemos ver claramente el código que deberemos de introducir en cualquier web en la que vayamos a interactuar.

Actualmente NuCaptcha está disponible para PHP, .NET, y Java, y nos da una serie de herramientas para implementarlo en nuestro sitio web, incluido un plugin para WordPress, y sea el método que usemos, API o plugins, deberemos de registrarnos para disponer de nuestra clave privada.

2010-08-06

Librería PHP para evitar SQL injection y XSS

Algo que debemos tener muy en cuenta cuando realizamos nuestra aplicación web es limpiar la entrada de datos de contenido malicioso, ya sea para SQL injection o cross-site scripting (XSS). Los frameworks suelen tener su propia librería que se encarga de ello, pero para aquellos que no usen framework o hagan una aplicación muy sencilla, esta librería les vendrá muy bien.

Genius Open Source Libraries

Vía / PHPDeveloper.org


2010-07-29

Cache de páginas con PHP con PHPguru.org

Caching with PHP5

Question: Whats the best way to improve performance of your website?
Answer: Get rid of it, and stop worrying.

Unfortunately, that's not always practical (livelihoods etc). So lets have a look at caching instead. Rather miraculously I've just written and published some nifty caching code.

The code is PHP5 only, and built with a static class mindset. This kinda uses the OOP system as namespaces, though also uses inheritance to reuse common code. The code is separated out into three classes, Cache, OutputCache and DataCache. Groups and unique IDs are used to identify individual cached content. This comes in handy if you have to clear just a certain section of the cached data.

The Cache class is the base class, and contains common code for generating filenames, and reading and writing data files. Most of the code here is protected, as you shouldn't be interfacing with this class directly except in one instance, which is enabling or disabling the cache.
Output Cache

The OutputCache class is used for caching the generated output of your scripts, or certain sections of them. It has Start and End methods, and is used like this:

if (!OutputCache::Start("myGroup", "myID", 600)) {

// Generate some output (as you do)...

OutputCache::End();
}

?>

So whats happening here? Well first off the call to Start() passes the group, unique ID and the TTL (Time To Live) for this particular bit of caching. So the data will be uniquely identified on disk by the group/id combo, and will be considered stale after the TTL number of seconds have passed. This function returns true if the data is found in the cache, and also prints the data to the screen. This means the code inside the if() block is skipped (thanks to the not (!) operator), and so the data isn't printed twice.

If however, the given combo of group/id isn't found in the cache, the Start() method will return false. When this happens output buffering is turned on to record the output. The code inside the if() block will then run (again - the not (!) operator), generate the output (which gets buffered), and then call the End() method. This method stops output buffering, saves the data to disk, and then prints it.

Elegant, efficient, and sexy. What more could you ask for?
Data Cache

The DataCache is used to cache data structures, as opposed to script output. This allows you to cache the creation of large arrays for example, or the results of slow queries. This is helpful if your pages are rather dynamic, though some areas aren't. Or in a recently experienced situation of mine: You have one central DB server, and multiple front end webservers. A common setup. If the load is getting high on the database, you might want to move some portion of queries (ORDER BY RAND() is a good example) to the webservers instead of the database server. Thus randomisation (eg using shuffle()) happens on one of 5 webservers, instead of your single resource limited database server. Anyway, some code:

if (!$data = DataCache::Get("myGroup", "myOtherID")) {

$result = $db->query("SELECT BIG_ASS_QUERY()");

DataCache::Put("myGroup", "myOtherID", 600, $result);
}

// Do something useful with $result

?>

So in this example (very similar to output caching), if the data is cached, it's assigned to $data and the if() block is skipped. If not, then the if() block is run, and the data is cached at the Put() method call.
Miscellaneous Bits

There's a few configuration bits and bobs you can twiddle with if you like twiddling. setPrefix() as you can well imagine sets the prefix used in the cache data filenames. This defaults to "cache_". setStore() sets where the data files themselves are stored. This defaults to "/dev/shm/", since this is a convenient way to store the data files in shared memory. If you don't have this, try changing the path to "/tmp/". Must be given with a trailing slash.

And last, and least (so as not to be a corny ass), there's the static variable Cache::$enabled. That's how your refer to static class variables in case you didn't know. This is a boolean which enables or disables the cache. Surprising that.

C'est tout. Get the code here.

Fuente: LINK EJEMPLO LINK CLASES

Clase para crear Captcha con PHP demanera simple.

La utilización de captcha es muy importante en todos los sitios Web, principalmente cuando se tiene algún tipo de formulario que realice la acción de mandar un email o registrar información en la base de datos.

SimpleCaptcha es una clase en PHP que nos permite realizar captcha fácilmente, su estilo particular se asemeja al captcha que utiliza Google para sus formularios.

Para poder utilizarlo debemos bajarnos el paquete que vendrá con un ejemplo incluido.

Este es un ejemplo básico de como utilizarlo:

Paso 1: Generar la imagen captcha con php

Primero iniciamos sesión para poder guardar la variable captcha en ella, luego instanciamos la clase SimpleCaptcha.
Podemos también configurar las opciones que vienen por defecto.

  1. session_start();

  2. $captcha = new SimpleCaptcha();

  3. //$captcha->wordsFile = 'words/es.php';
  4. //$captcha->session_var = 'secretword';
  5. //$captcha->imageFormat = 'png';
  6. //$captcha->scale = 3; $captcha->blur = true;
  7. //$captcha->resourcesPath = "/var/cool-php-captcha/resources";

  8. $captcha->CreateImage();

Paso 2: Crear el formulario html

Este es un simple formulario donde en el src de la imagen pondremos la ruta del captcha generado con php.

  1. <div>
  2. <img src="captcha.php" id="captcha" /><br/>
  3. <a href="#"
  4. onclick="document.getElementById('captcha').src='captcha.php?
  5. '+Math.random();" id="change-image">
  6. Recargar Captcha.a> <br/>
  7. <input type="text" name="captcha" id="captcha-form" />
  8. <input type="submit" value="Enviar" />
  9. div>

Paso 3: Validar el captcha

  1. if (!emptyempty($_REQUEST['captcha'])) {

  2. $txt=trim(strtolower($_REQUEST['captcha']));

  3. if ( emptyempty($_SESSION['captcha']) ||
  4. $txt != $_SESSION['captcha'] ){
  5. echo "Captcha incorrecto";
  6. } else {
  7. echo "Captcha correcto!";
  8. }
  9. unset($_SESSION['captcha']);
  10. }


Fuente: Link Link2

Implementando un sistema de caché en PHP

Hace unos días, os comentaba que es una caché y como entenderla en el marco de la programación web. Para seguir con el aprendizaje de este sistema, he desarrollado una pequeña clase que permite cachear información (strings, arrays, resultados de base de datos, objetos…) en nuestra máquina y descongestionar así el motor de base de datos, por poner un ejemplo.

Lo primero que debemos hacer es pensar en que necesitamos para su correcto funcionamiento, así que, manos a la obra.

Como sabemos, una caché es un sistema al que le pasamos un objeto X y él lo almacenará en su sistema de una manera determinada, por lo tanto, necesitaremos una función que dado un identificador único y unos datos, guardará la información. Además de esto, necesitamos indicarle un tiempo de vida (ttl) a esa información cacheada, sino estaremos devolviendo eternamente el valor almacenado.

Un concepto que nos puede resultar interesante es el de caché de grupo. Imaginemos que tenemos un sistema que va cacheando información de nuestra base de datos; tenemos una tabla user y una tabla user_profile y cacheamos los resultados de ambas tablas por separado. Imaginemos también que por temas de LOPD el usuario solicita que eliminemos todos sus datos de nuestras máquinas, así que eliminaremos el registro de la tabla user y user_profile y procederemos a eliminar el cacheo de los datos de cada tabla por separado. Si tuviesemos agrupada la información de usuario, con una única llamada a la función remove y pasándole el identificador de grupo, eliminará la caché de ambas tablas.

A medida que vaya explicando cada función, os pondré el resultado final para que os hagais una idea de como va quedando el código:
LINK
DESCARGAR CLASE: cache.class.php

2010-07-15

Fragmento caché - una introducción / PHP

Este artículo le dará a conocer que la nueva forma de gran alcance de la optimización de la velocidad sitio web llamado una caché fragmentada. Se basa en ideas utilizadas en otras partes para hacer que la técnica aún más poderosa. Una aplicación PHP se encuentra disponible para su descarga.
Por Patrick van Bergen

Código fuente

Este artículo viene con dos archivos de PHP (5,3) Código fuente: el real de la clase FragmentCache y un archivo de prueba. Este código fuente está sujeta a la licencia MIT.

Optimización de contenido web

Cuando un sitio web en la complejidad aumenta y comienza a depender de numerosas fuentes de datos y miles de líneas de código, se retrasa, no importa qué lenguaje de programación o bases de datos usado. Y eso afecta tanto a la hora de servir a la página y el número de páginas por segundo que pueden ser atendidas por su servidor web. Hay muchas maneras de este problema se puede abordar y todas ellas deben ser consideradas. Más de hardware y más rápido, más y mejor software, y luego está la optimización de código fuente.

Aca hay esta clase para hacer Cachin con PHP 5.3

Este artículo viene con dos archivos de PHP (5,3)
Código fuente: el real de
la clase FragmentCache y un archivo de prueba.
Este código fuente está sujeta a la
licencia MIT.

2010-06-28

Dynamic DOCX generation es una clase para trabajar archivos DOCx con PHP


Dynamic DOCX generation

Dynamic generation of reports in .docx (Microsoft Open Office or OOML) format:
Editable text
Lists and tables
Dynamic charts: pie charts, bar graphs…
Personalized headers and footers
Tables of content
Images
Automatic conversion to other formats (PDF, HTML)
And much more…

2010-03-26

50 gandes utilidad PHP Tools - Class - Clases - IDE

50 herramientas útiles de PHP que puede mejorar significativamente el flujo de trabajo de programación. Entre otras cosas, usted encontrará una gran cantidad de bibliotecas y clases que ayudan en la depuración, las pruebas de perfiles y de creación de código en PHP.

Link relacionados:

Debugging Tools

  • Wincachegrind
    Wincachegrind interpreta los archivos profile de Xdebug y los muestras de una manera simple, esta aplicacion es compatible con Windows es un simple ejecutable.
    El cual busca los archivos cachegrind.out.* que genera xDebug segun su configuracion.
    Podes obtener muchos detalles de lo que consume cada unos de tus script PHP y encontrar los cuellos de botella para mejor la performan.

    Para configurar xDebug tenes que poner esto en el PHP.ini Ejemplo de mi configuracion para desarrollar:
    [xDebug]
    # xDebug No es compatible con la extencion Zend Optimaser y Zend Studio Debugger
    # por eso hay que desactivar estas extenciones cuando trabajamos con xDebug

    #ProFile netbeans-xdebug

    [xDebug PHP5.2.11]
    #zend_extension_ts=C:/wamp/bin/php/php5.2.11/ext/php_xdebug-2.0.5.dll
    zend_extension_ts=C:/wamp/bin/php/php5.2.11/ext/php_xdebug-2.1.0-5.2-vc6.dll
    xdebug.remote_enable=1
    xdebug.remote_handler=dbgp
    xdebug.remote_mode=req
    xdebug.remote_host=127.0.0.1
    xdebug.remote_port=9000

    [xDebug PHP5.3]
    #zend_extension=C:/wamp/bin/php/php5.3.0/ext/php_xdebug-2.0.5.dll
    #xdebug.remote_enable=1
    #xdebug.remote_handler=dbgp
    #xdebug.remote_mode=req
    #xdebug.remote_host=127.0.0.1
    #xdebug.remote_port=9000

    # xDebug ProFile
    xdebug.profiler_append=1
    xdebug.profiler_enable=1
    xdebug.profiler_enable_trigger=1
    xdebug.profiler_output_name = cachegrind.out.%s
    #xdebug.profiler_output_name = cachegrind.out
    xdebug.profiler_output_dir ="C:/wamp/tmp/grind-out/"

  • Dentro de el archivos que queres hacer el profile tenes que poner esto.
    xdebug_get_profiler_filename(); /* Esto envia la orden a xDebug a generear el archivo
    que luego analizas con WinCacheGrind*/

  • Webgrind
    Webgrind is an Xdebug profiling Web front end in PHP 5. It implements a subset of the features of kcachegrind, installs in seconds and works on all platforms. For quick ‘n’ dirty optimizations, it does the job.

    Webgrind in 50 Extremely Useful PHP Tools

  • Xdebug
    Xdebug is one of the most popular debugging PHP extensions. It provides a ton of useful data to help you quickly find bugs in your source code. Xdebug plugs right into many of the most popular PHP applications, such as PHPEclipse and phpDesigner.
  • Gubed PHP Debugger
    As the name implies, Gubed PHP Debugger is a PHP debugging tool for hunting down logic errors.
  • DBG
    DBG is a robust and popular PHP debugger for use in local and remote PHP debugging. It plugs into numerous PHP IDE’s and can easily be used with the command line.
  • PHP_Debug
    PHP_Debug is an open-source project that gives you useful information about your PHP code that can be used for debugging. It can output processing times of your PHP and SQL, check the performance of particular code blocks and get variable dumps in graphical form, which is great if you need a more visual output than the one given to you by print_r() or var_dump().
  • PHP_Dyn
    PHP_Dyn is another excellent PHP debugging tool that’s open-source. You can trace execution and get an output of the argument and return values of your functions.
  • MacGDBp
    MacGDBp is a live PHP debugger application for the Mac OS. It has all the features you’d expect from a fully featured debugger, such as the ability to step through your code and set breakpoints.

Testing and Optimization Tools

  • PHPUnit
    PHPUnit is a complete port of the popular JUnit unit testing suite to PHP 5. It’s a tool that helps you test your Web application’s stability and scalability. Writing test cases within the PHPUnit framework is easy; here’s how to do it.
  • SimpleTest
    SimpleTest is a straightforward unit-testing platform for PHP applications. To get up and running with SimpleTest quickly, read through this pragmatic tutorial that shows you how to create a new test case.

    Simpletest in 50 Extremely Useful PHP Tools

  • Selenium
    Selenium Remote Control (RC) is a test tool that allows you to write automated Web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. It can be used in conjunction with PHPUnit to create and run automated tests within a Web browser.
  • PHP_CodeSniffer
    PHP_CodeSniffer is a PHP 5 script for detecting conformance to a predefined PHP coding standard. It’s a helpful tool for maintaining uniform coding styles for large projects and teams.
  • dBug
    dBug is ColdFusion’s cfDump for PHP. It’s a simple tool for outputting data tables that contain information about arrays, classes and objects, database resources and XML resources, making it very useful for debugging purposes.

    11 Dbug in 50 Extremely Useful PHP Tools

  • PHP Profile Class
    PHP Profile Class is an excellent PHP profiling tool for your Web applications. Using this class will help you quickly and easily gain insight into which parts of your app could use some refactoring and optimization.

Documentation Tools

  • phpDocumentor
    phpDocumentor (also known as phpdoc and phpdocu) is a documentation tool for your PHP source code. It has an innumerable amount of features, including the ability to output in HTML, PDF, CHM and XML DocBook formats, and has both a Web-based and command-line interface as well as source-code highlighting. To learn more about phpDocumentor, check out the online manual.
  • PHP DOX
    An AJAX-powered PHP documentation search engine that enables you to search titles from all PHP documentation pages.

Security Tools

  • Securimage
    Securimage is a free, open-source PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse.
  • Scavenger
    Scavenger is an open-source, real-time vulnerability management tool. It helps system administrators respond to vulnerability findings, track vulnerability findings and review accepted and false-positive answered vulnerabilities, without “nagging” them with old vulnerabilities.
  • PHP-IDS
    PHP-IDS (PHP-Intrusion Detection System) is a simple-to-use, well-structured, fast and state-of-the-art security layer for your PHP-based Web application.
  • Pixy: PHP Security Scanner
    Pixy is a Java program that performs automatic scans of PHP 4 source code, aimed to detect XSS and SQL injection vulnerabilities. Pixy takes a PHP program as input and creates a report that lists possible vulnerable points in the program, along with additional information for understanding the vulnerability.

Image Manipulation and Graphs

  • PHP/SWF Charts
    PHP/SWF Charts is a powerful PHP tool that enables you to create attractive Web charts and graphs from dynamic data. You can use PHP scripts to generate and gather data from databases, then pass it to this tool to generate Flash (SWF) charts and graphs.
  • pChart – a chart-drawing PHP library
    pChart is a PHP class-oriented framework designed to create aliased charts. Most of today’s chart libraries have a cost; this one is free. Data can be retrieved from SQL queries or CSV files or can be manually provided.

    Chart in 50 Extremely Useful PHP Tools

  • WideImage
    WideImage is a PHP library for dynamic image manipulation and processing for PHP 5. To be able to use the library, you should have the GD PHP extension installed on your Web server.
  • MagickWand For PHP
    MagickWand For PHP is a PHP module suite for working with the ImageMagick API, which lets you create, compose and edit bitmap images. It’s a useful tool for quickly incorporating image-editing features in your PHP applications.

PHP Code Beautifier

  • PHP_Beautifier
    PHP Beautifier is a PEAR package for automatically formatting and “beautifying” PHP 4 and PHP 5 source code.
  • PHPCodeBeautifier
    PHPCodeBeautifier is a tool that saves you from hours of reformatting code to suit your own way of presenting it. A GUI version allows you to process files visually; a command-line version can be batched or integrated with other tools (like CVS, SubVersion, IDE, etc.); and there is also an integrated tool of PHPEdit.
  • GeSHi – Generic Syntax Highlighter
    GeSHi is designed to be a simple but powerful highlighting class, with the goal of supporting a wide range of popular languages. Developers can easily add new languages for highlighting and define easily customizable output formats.

Version-Control Systems

  • Phing
    Phing is a popular project version-control system for PHP. It is a useful tool for organizing and maintaining different builds of your project.
  • xinc
    xinc is a continuous integration server version-control system written in PHP 5 (i.e. continuous builds instead of nightly builds). It works great with other systems such as Subversion and Phing.

Useful Extensions, Utilities and Classes

  • SimplePie
    SimplePie is a PHP class that helps you work with RSS feeds. Check out the online RSS and Atom feed reader, which demonstrates a simple Web application that uses SimplePie.

    Spie in 50 Extremely Useful PHP Tools

  • HTML Purifier
    HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier not only removes all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive white list, it also makes sure your documents are standards-compliant. Open source and highly customizable.
  • TCPDF
    TCPDF is an open-source PHP class for generating PDF documents.
  • htmlSQL
    htmlSQL is a unique tool. It is a PHP class for querying HTML values in an SQL-like syntax. Check out the live demonstration of how htmlSQL works.
  • The Greatest PHP Snippet File Ever (Using Quicktext for Notepad++)
    “A little something for all coders: a snippets file that I use for PHP coding. This is designed to be used with Quicktext for Notepad++, but feel free to adapt it to whatever text editor you prefer.”
  • Creole
    Creole is a database abstraction layer for PHP5. It abstracts PHP’s native database-specific API to create more portable code while also providing developers with a clean, fully object-oriented interface based loosely on the API for Java’s JDBC.
  • PHPLinq
    LINQ is a component that adds native data querying capabilities to PHP using a syntax reminiscent of SQL. It defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational databases and third-party data sources. [via]
  • PHPMathPublisher
    With PhpMathPublisher, you can publish mathematical documents on the Web using only a PHP script (no LaTeX programs on the server and no MathML).

    Math in 50 Extremely Useful PHP Tools

  • phpMyAdmin
    If you’re working with PHP, there’s a big chance you’re set up in a LAMP configuration. phpMyAdmin is Web-based tool for managing, building, importing, exporting and exploring MySQL databases.
  • PHPExcel
    PHPExcel is a set of useful PHP classes for working with Microsoft Excel files. PHPExcel allows you to read Excel files and write to them. This is useful for dynamically generating Excel spreadsheets for downloading.
  • Phormer
    Phormer is a PHP-based photo gallery management application that helps you to store, categorize and trim your photos online.
  • xajax PHP Class Library
    xajax is a PHP class for easily working with PHP AJAX applications. It gives you an easy-to-use API for quickly managing AJAX-related tasks. Check out the xajax Multiplier demo and the Graffiti Wall demo to see the xajax PHP class in action.
  • PHP User Class
    PHP User Class is an excellent script that helps you create a system for user authentication (i.e. registration, log in, account profile, etc.). It’s a useful utility to have around if you require user registration for your Web applications.
  • PHP-GTK
    PHP-GTK is a PHP extension for the GTK+ toolkit (a robust toolkit for developing GUIs). It is a suite of useful OOP functions and classes to help you rapidly build cross-platform, client-side GUI’s for your application.

PHP Online Tools and Resources

  • Minify!
    Minify is a PHP 5 app that can combine multiple CSS or JavaScript files, compress their content (i.e. remove unnecessary white space and comments) and serve the results with HTTP encoding (via Gzip/deflate) and headers that allow optimal client-side caching. This will help you follow several of Yahoo!’s Rules for High Performance Websites.

    Minify in 50 Extremely Useful PHP Tools

  • HTTP_StaticMerger: Automatic “merging” of CSS and JavaScript files
    This library automatically merges sets of static files (CSS or JavaScript) and speeds up page loading (by lowering the number of HTTP queries). It is recommended to use this together with caching reverse-proxy to minimize the response time.
  • PHP Object Generator
    PHP Object Generator is an open-source Web-based tool that helps you quickly construct PHP objects and leverage object-oriented programming (OOP) principles in your code.

    03 Object Generator in 50 Extremely Useful PHP Tools

  • gotAPI/PHP
    gotAPI is a useful online tool for quickly looking up PHP functions and classes. Also check out the Quick PHP look-up widget example in case you’d like to include this awesome look-up feature on your website.

    04 Gotapi in 50 Extremely Useful PHP Tools

  • koders
    koders is a search engine for open-source and downloadable code. It currently has over a billion lines of code indexed and isn’t limited to just PHP.
  • PECL
    PECL is a directory of all known PHP extensions and a hosting facility for downloading and developing PHP extensions.

In-Browser Tools (Firefox Add-Ons)

  • FirePHP
    FirePHP is a Firefox extension that allows you to log data in Firebug. It has a variety of useful logging features, such as the ability to change your error and exception handling on the fly and to log errors directly to the Firebug console. To learn more about what FirePHP can do, check out the FirePHP guide on how to use FirePHP. For developers using the Zend PHP framework, you might find this guide on using FirePHP with Zend useful.

    01 Firephp in 50 Extremely Useful PHP Tools

  • phpLangEditor
    phpLangEditor is a very handy Firefox add-on for translating language files and variables in your script.

    02 Phplangeditor in 50 Extremely Useful PHP Tools

  • PHP Lookup
    PHP Lookup is a built-in search bar to help you quickly look up references to PHP syntax.
  • PHP Manual Search
    PHP Manual Search is a handy search bar that searches official PHP documentation from within your Web browser.

Frameworks for PHP

  • Dwoo
    Dwoo is a PHP 5 template engine positioned as an alternative to Smarty. It is (nearly) fully compatible with its templates and plug-ins, but it is being written from scratch and is aimed to go one step further with a cleaner code base.
  • CodeIgniter
    CodeIgniter is a powerful, high-performance, open-source PHP framework that helps you author PHP applications rapidly. CodeIgniter is known for having a light footprint, thereby reducing your server’s work. You can get up and running with CodeIgniter in a jiffy: it has an awesome online manual, a couple of helpful video tutorials and an active user forum.

    Codeigniter in 50 Extremely Useful PHP Tools

  • YII Framework
    Here is a high-performance component-based PHP framework that is supposed to be more efficient than CodeIgniter, CakePHP, ZF and Symfony. An optimal solution for developing large-scale Web applications. Yii supports MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX support, authentication and role-based access control, scaffolding, input validation, widgets, events, theming and Web services.
  • NetBeans
    A dedicated PHP coding environment and complete integration with web standards. The NetBeans PHP editor is dynamically integrated with NetBeans HTML, JavaScript and CSS editing features such as syntax highlighting and the JavaScript debugger. NetBeans IDE 6.5 fully supports iterative development, so testing PHP projects follows the classic patterns familiar to web developers.
  • Solar
    Solar is a PHP 5 development framework for Web applications derived from the Savant templating engine. Solar uses the MVC architectural pattern and has a host of classes and functions for securing your Web app against SQL injection, cross-website scripting (XSS) and other common exploits.

    Solar in 50 Extremely Useful PHP Tools

  • symfony
    symfony is an open-source PHP 5 Web application framework that is well known for its modularity and useful library of classes. To get up and running as fast as possible, you should check out the pragmatic symfony online tutorial called “The symfony 1.2 advent calendar tutorial,” which takes you through a step-by-step example of building your own symfony-based Web application.
  • PEAR – PHP Extension and Application Repository
    PEAR is a popular framework and distribution system for reusable PHP components. The purpose of the framework is to provide a structured library of open-source code for PHP users, a system for code distribution and package maintenance and a standard style for PHP code.
  • Propel
    Propel is an Object-Relational Mapping (ORM) framework for PHP 5. It allows you to access your database using a set of objects, providing a simple API for storing and retrieving data.
  • {{macro}} template engine
    {{macro}} compiles initial templates into executable PHP scripts with very clean syntax (much cleaner than WACT and Smarty) and executes them very fast. The engine doesn’t use an XML-like syntax; there are only two data scopes, global and local, and no more data sources (all data is displayed with regular PHP variables); and the system supports all WACT features such as templates wrapping and including.Macro in 50 Extremely Useful PHP Tools
  • Zend Framework
    The Zend Framework by Zend Technologies (the creators of PHP’s scripting engine) is a popular PHP Web application framework that embraces the principles of PHP OOP; it’s very extensible and has built-in utilities for working with free Web service APIs, such as those of Google, Flickr and Amazon.
  • Qcodo
    Qcodo is an excellent open-source PHP Web application framework. It’s subdivided into two parts: (1) Code Generator, and (2) Qforms. Code Generator handles the creation of object code and PHP and HTML front-end code from your data model. Qforms is an intuitive system for handling and creating complex PHP-driven HTML Web forms. Check out demos of applications that use Qcodo and presentational material that covers Qcodo.

    Qc in 50 Extremely Useful PHP Tools

  • SAJAX
    SAJAX is a JavaScript and AJAX application framework that works well with PHP (as well as several other server-side scripting languages). See SAJAX at work by going to Wall live demonstration.
  • Smarty
    Smarty is a popular PHP templating system to help you separate PHP logic and front-end code (HTML, CSS, JavaScript). It will keep your projects modular and easier to maintain.
  • CakePHP
    CakePHP is one of the leading PHP frameworks for creating robust, fully-featured Web applications. CakePHP has an extensive and well-organized online manual. If you want to learn via video tutorials, check out the CakePHP screencasts.

    Cake in 50 Extremely Useful PHP Tools

  • Savant2
    Savant2 is another popular object-oriented PHP templating system. Instead of a special syntax unique to Savant2, you use PHP syntax to develop your project’s template.
  • PHPSpec
    PHPSpec is a simple and intuitive PHP framework. It follows the Behavior-Driven Development principle and therefore allows you to write behavior-oriented code, oftentimes in plain English.

PHP IDEs and Editors

  • PHPEclipse
    PHPEclipse is a popular PHP source-code editor that is open source and runs on all the major operating systems, such as Windows, Linux and Mac OS. It has all the features you’d expect from a PHP source-code editor, such as code-folding, syntax highlighting, hover-over tool tips and support for XDebug and DBG.

    07 Php Eclipse in 50 Extremely Useful PHP Tools

  • PhpED
    PhpED is an excellent IDE for Windows users. It is one of the most robust and feature-packed IDEs currently out on the market and has useful features such as a built-in source-code profiler to find bottlenecks in your PHP source code and excellent integration with third-party apps and services just as front-end code validation.

    08 Phped in 50 Extremely Useful PHP Tools

  • phpDesigner
    phpDesigner is a lightweight PHP editor/IDE that also handles front-end code and markup remarkably well. Check out the phpDesigner online tutorials, as well as screencasts on phpDesigner to help you learn more about the IDE.

    09 Phpdesigner in 50 Extremely Useful PHP Tools

  • Zend Studio
    Zend Studio is an excellent PHP IDE for Eclipse. It’ll help you develop, deploy and manage Rich Internet Applications (RIAs) in an intuitive interface.

    10 Zend Studio in 50 Extremely Useful PHP Tools

  • Aptana PHP
    Aptana PHP is an open-source IDE extension/plug-in to be used in conjunction with Aptana Studio. To learn more, be sure to check out the online documentation about Aptana PHP.
  • PDT
    PDT is a PHP Development Tools framework that’s part of the Eclipse project. PDT includes all the necessary tools for you to create PHP-based Web applications.
  • VS.Php
    VS.Php is a PHP IDE for MS Visual Studio, making it a great IDE for recently converted ASP developers who have used MS VS to develop Web applications. To get you up and running ASAP with VS.Php, check out Jcx.Software’s online tutorials as well as its online documentation.
  • PHPEdit
    PHPEdit is an excellent PHP editor/IDE with a ton of useful features and a very intuitive user interface. To learn more about why PHPEdit is a good IDE, read the 10 reasons to use PHPEdit and view the introductory screencast about PHPEdit.

Sources and Resources