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

20150420

Cookie Based API login using Guzzle

We've all used curl to consume external services - scraping, APIs, etc. We know that curl is awesome, but there is that feeling that you should be doing this in a more abstract way, or using something not too hardcore.

Yesterday, I had to connect to an external API using cookie based authentication. I initially thought of doing it with curl, but I remembered Guzzle, and wanted to give it a try.

Hello Guzzle
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. 
In pseudocode:
  • create a guzzle client
  • create a cookie 
  • login and update that cookie
  • use that cookie for next requests
Here is an example:

1:  // Create a Client   
2:  $client = new \GuzzleHttp\Client\Client([  
3:    'base_url' => 'http://someserver.com',  
4:    'defaults' => [  
5:      'headers' => [  
6:        'Accept' => 'application/json'  
7:      ]  
8:    ]  
9:  ]);  
10:    
11:  // Create a new cookie  
12:  $cookieJar = new \GuzzleHttp\Cookie\CookieJar();  
13:    
14:  // Send a post  
15:  $request = $client->createRequest('POST', '/api/login', [  
16:    'cookies' => $cookieJar,  
17:    'body' => [  
18:      'UserName' => 'USERNAME',  
19:      'Password' => 'PASSWORD',  
20:    
21:    ]  
22:  ]);  
23:    
24:  // ....  
25:    
26:  // Reuse the cookie for next requests  
27:  $response = $client->get('/api/user', [  
28:    'cookies' => $cookieJar  
29:  ]);  

You can store the cookie in a shared session so that you don't need to login each time you do a request.

Links:

  • Fetching a URL with Cookies using curl: http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm

20130606

PHP Sessions tricks

Here are some tips & tricks we use for PHP sessions:

Release session file using with session_write_close ...

Don't wait till the script finishes. "You all know" that when opening a session, the session file is blocked by the PHP process till the scripts releases it. So if you have a site with a lot of concurrent ajax calls that open session (logged in users?), those calls will be waiting till the session is released (so you are serializing your ajax calls in the server).

One way to prevent this is to release the session after writing to it. To do this, just have to call:
session_write_close();
after manipulating the session. You will have the session available in $_SESSION but read only. Whenever you want to write something in the session, just call:
session_start();
Links:


Use memcached to store sessions if available ...

There are a lot of benefits in this approach:

  • easy to install / deploy.
  • shared sessions between servers.
  • super fast (works in memory).
  • very easy to scale (just add more memcached servers!)

The only drawback i see in with this approach is that you dont have persistent session storage, so if you reboot memcached say bye bye to your sessions.

Installation

First install memcached, there are packages for almost any linux distribution, on debian / ubuntu:
~ apt-get install memcached
It will be available by default in localhost port  11211
Then install  the PHP extension:
~ apt-get install php5-memcache
 Finally change your PHP (/etc/php5/apache2/php.ini) setting
session.save_handler = files 
to
session.save_handler = memcache
session.save_path="tcp://127.0.0.1:11211?timeout=1&persistent=1&weight=1&retry_interval=15"
Done! restart apache and you are ready to go!.

Links:


Use Database session handler 

This is approach is widely used, and its main benefits are:

  • shared sessions between servers.
  • persistent storage.

From the manual:
To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler.
The process basically is:
  • create a table called sessions
  • create a class called for example: "MySessionHandler" implementing SessionHandlerInterface.
  • register that class as the default error handler: 

Or you can use the Session Save Handlers from Zend Framework 2 that makes you life a lot easier.


Links:

20120419

How much i hate/love "php" (or any other language)

After reading a bunch of blog posts about how much people love or hate php / like or don't like php design (herehere, here, here), i start thinking that this happens to everybody with any language and dependes of "how much you kick ass" in that language.

When you start with any (new) language, usually, that relationship starts with a lot of love to give and receive... you start doing amazing stuff, and everything is like wonderland. But at some point in your discovery, you hit the "real shit":


welcome to the real world!!


time pass and bam! you are not a rookie anymore, you want to do your stuff the right way and your lovely language is not with you. You found really ugly things in your lovely language, and you start feeling...

full of hate!!!

But think about it.. you are an expert now, you have the knowledge, you have the expertise, you can show the community the light!.. so go and do it, HELP your lovely language, stop complaining...

So this is my opinion, you start hating it when you kick ass.. period! and thats cool!

I love php and i really hate php, and im willing to see its next iteration too. 


20120412

Breadcrumbs with Zend_Navigation

I needed to create a breadcrumb into an application im developing, and i thought that would be cool to do it with Zend Framework and not just reinvent the wheel.

There is Breadcrumb helper that we can use, its very easy to setup, so here we go:

Setup navigation.xml

First we need to create an xml with our navigation map. In this case i want to recreate something like this:
  • Home - uri: /
    • Search - uri: /search
    • Management - uri: /management
      • Parameters - uri: /management/parameters
        • Parameter Detail - uri: /management/parameters/view/XYZ
The idea is to create a breadcrumb like this:
[ Home ]
[ Home / Search ]
[ Home / Management ]
[ Home / Management  / Detail ]

So i will create a /application/configs/navigation.xml as follows:

As you can see it represents the navigation map i want in the breadcrumb. Each uri specifies an option in our navigation map.

Bootstrap

You have to bootstrap the navigation, here is the init method for your Boostrap.php :
Check on line 12 the 'nav' parameter, its the first element that correspond to the configuration section we want to use.

Add it to your layout

After setting up our navigation, we need to add the breadcrumb to our layout template. My layout file looks like this:



This is the basic configuration im using:

  • setMinDepth(0) gets and sets the minimum depth a page must have to be included by the helper. Setting NULL means no minimum depth.
  • setLinkLast(false) I don't want a link in the last option of the breadcrumb.
  • setSeparator(" / ") sets text with which to separate aggregated content.

Select the options in our controllers

Finally we need to tell Zend_Navigation where we are so it can show the right breadcrumb options.
To activate the breadcrumb on every action of a controller we need to get the uri and then pass it to the navigation object:

If we are in some weird uri and want to show /search in the breadcrumb you just have to use the uri parameter to search the right option.

This is the final result (using Twitter Bootstrap styling):

Hope it helps.

20111007

Zend Framework: How to access your configuration from the application.ini file

There are many ways of getting the config from our application.ini file. The usual way is to load it using Zend_Config in our Boostrap class. The other way is to load it from a parameter in the front controller (Zend_Application put it there).

Using Bootstrap
Add this to your Boostra.php file:


You can fetch the config wherever you want using: 
$config = Zend_Registry::get("config");
Loading from Front controller
From a View action:

From outside the controller:

20101119

Crear un demonio con PHP y PEAR

 Hoy tuve la necesidad de crear un demonio para WHObyYOU por lo que voy a compartir con uds el resultado.
Un demonio es un proceso / programa que corre en segundo plano (de forma pasiva). La mayoría de la veces, cuando uno necesita correr un proceso continuamente; termina haciendo tareas programadas (cron jobs) con las ventajas y desventajas de este tipo de implementación. La mayor desventaja de una tarea programada es el solapamiento de la tarea con otra. Hay que hacer alguna magia para que esto no pase.
Con demonios esto no importa ya que una tarea no comienza hasta que empieza la otra (dentro del mismo proceso).

El ejemplo que voy a mostrar ahora es simplemente para mostrarles como hacer el demonio con PEAR::System_Daemon.

Primero hay que instalar pear, en Unbuntu
sudo apt-get install php-pear
Luego instalar PEAR::System_Daemon
sudo pear install -f System_Daemon
Luego de instalar el paquete, lo unico que tenemos que hacer es :
require_once "System/Daemon.php"; // Include the Class
System_Daemon::setOption("appName", "mydaemon");
System_Daemon::start();

A continuación muestro un script de ejemplo, que lo unico que hace es grabar en un log cada 5 segundos con un máximo de 5 veces.



Paso a explicar las diferentes partes del script:

En la línea 1 indicamos que este script se ejecutará con PHP.
En la linea 3 incluimos la clase System_Daemon de par.

En la linea 5 configuramos el demonio, "appName" y "appDir" son los únicos requeridos para que funcione.
$options = array(
    "appName" => "pruebaDiego",
    "appDir" => dirname(__FILE__)
);
Lineas 13 y 14 creo el demonio (crea un proceso hijo, se separa del proceso padre y el proceso padre muere).

Luego creo un while(true) y le genero una condición de salida: podría ser por una falla del programa, captura de una excepción, cualquier cosa. En este caso la condición de salida se da cuando el bucle se ejecutó 5 veces.

En la línea 21 escribo en el log. El System_Daemon nos ofrece una forma simple de escribir un log, en este caso el archivo de log es:
/var/log/pruebaDiego.log
Para ejecutar el script simplemente, hay que ejecutar
$ sudo ./test.php 
Luego podemos ver el log:
$ tail -f /var/log/pruebaDiego.log

Por más información:
  

20101112

Introducción a Zend_Queue

Esta semana tuve que armar un Queue para un proyecto en el que estamos trabajando (WHObyYOU.com) y obviamente intenté hacerlo con Zend_Queue.

En este caso necesitaba consumir en "tiempo real" la Streaming Api de Twitter (ya haré un post sobre esto),  por lo que necesitaba procesar los tweets fuera el proceso que consumía el stream.

Zend_Queue es bastante simple y no tiene mucho misterio. En este caso vamos a usar el adaptador de Base de Datos (Zend_Queue_Adapter_Db) para guardar nuestros mensajes.

Primero creamos las tablas que necesitamos (queue y message), en el caso de mysql:


La defincion de tablas la pueden encontrar en Zend/Queue/Adapter/Db/mysq.sql

Creamos el queue utilizando una clase abstracta:



Luego agreguemos un Tweet al queue, supongamos que un Tweet es una array:



Luego a procesar los mensajes. En el caso de este proyecto, hicimos una tarea programada (cron) que corre cada 30 segundos y procesa el queue. Zend_Queue retorna los mensajes usando Zend_Queue_Message_Iterator (lo pueden ver en la documentacion).



Esto se puede mejorar mucho creando nuestros propios adaptadores, eso vendrá en una próxima entrega.