martes, 9 de diciembre de 2014

php log variables to file

a quick way to view a variable content without interrupt the webpage with a var_dump or print_r


file_put_contents('/path_to_file/file.txt', var_export($variable, true));

jueves, 8 de mayo de 2014

testing mod rewrite apache

file .htaccess
RewriteEngine On 
RewriteRule ^.*$ index.php

file index.php
<?php
print 'mod_rewrite works!';
?>

Simply put this two files in /var/www/test_mod_rewrite and from the browser call localhost/test_mod_rewrite. "mod_rewrite_works!" should be printed

sábado, 26 de abril de 2014

move dropbox folder in debian



You could just create a symlink to ~/Dropbox

ln -s <dir-that-you-want-to-sync> ~/Dropbox

domingo, 16 de febrero de 2014

php json header


For JSON:

header('Content-Type: application/json');


For JSON-P:

header('Content-Type: application/javascript');

martes, 11 de febrero de 2014

fatal error: libcouchbase/couchbase.h: No such file or directory

Installing couchbase library from php I found this little fatal error:

fatal error: libcouchbase/couchbase.h: No such file or directory

This is because the C library not was installed properly. Just run:

sudo wget -O /etc/apt/sources.list.d/couchbase.list packages.couchbase.com/ubuntu/couchbase-ubuntu1204.list 
wget -O- packages.couchbase.com/ubuntu/couchbase.key | sudo apt-key add - 
sudo apt-get update 
sudo apt-get install libcouchbase2 libcouchbase-dev

and then:

sudo apt-get install php-pear 
sudo pecl install couchbase 
sudo apt-get install build-essential
Update php.ini with extension=couchbase.so and restart apache.

lunes, 10 de febrero de 2014

Couchbase cbrestore example

Finally I can get cbrestore working after "guess" the syntax. Couchbase official cbrestore documentation is really poor.

The magic line:

sh cbrestore /home/user/Descargas/backup2014-02-10 http://Administrator:password@localhost:8091 --bucket-source=demo --bucket-destination=demo

jueves, 30 de enero de 2014

Disallowed Key Characters WTF??!!

For any weird reason, when I send some forms  this message is displayed:

Disallowed Key Characters

WTF? What I changed?? I don't know. I only know one thing: when this message appeared, I had to start debugging the FRAMEWORK, not my code, not your code, just the framework.

I found the problem in file system/core/Input.php, line 727, function _clean_input_keys{}

When I have a POST field containing "-", this doesnt match the preg_match("/^[a-z0-9:_\/-]+$/i", $str), I dont know why because the "-" IS HERE!!! then ...

I run this: var_dump(preg_match("/^[a-z0-9:_\/-]+$/i", '-')); die(); and of course was TRUE.

Conclusion: I don't know WTF is happening (It's like a devil '-' different from '-'), but, if you are seeing "Disallowed Key Characters" message and you have a post field called, for example "login-submit", rename this field to "login_submit" and maybe all the things start working again.

domingo, 12 de enero de 2014

Codeigniter dinamic route from database

What if we want to route from a db table? I search all the web and I dont find a solution that makes me happy, so, I build one.

File /core/MY_Router.php: we extend the core router to add the database functionality.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
CUSTOM ROUTER FUNCTION TO CHECK FOR CITY SLUG PLUS CONTROLLERS */
 class MY_Router extends CI_Router{

public function __construct(){
        parent::__construct();
        $this->config =& load_class('Config', 'core');
        $this->uri =& load_class('URI', 'core');

        require_once(BASEPATH.'database/DB'.EXT);
        $this->db = DB();
    }


public function _set_routing(){

$db_routes = $this->db
->where('active', 1)
->get('routes')
->result();

foreach ($db_routes as $route) {

$this->routes[$route->slug] = 'coupons/index/' . $city->slug;
$this->routes[$route->slug . '/(:any)'] = 'coupons/index/' . $city->slug . '/$1';
}

parent::_set_routing();
}
}

We need to change one character in system/core/Router.php to avoid overwrite the routes array.

In line 141 change this:
$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; 

to this:
$this->routes += ( ! isset($route) OR ! is_array($route)) ? array() : $route;

(NOTE THE + SIGN)

That's all. Efective and Beautiful.

jueves, 19 de diciembre de 2013

codeigniter debug helper

Little helper to print_r variables with pre

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('pr'))
{
    function pr($thing)
    {
        echo '<pre>';
        var_dump($thing);
        echo '</pre>';
        die();        
    }   
}

martes, 17 de septiembre de 2013

restart and stop apache tomcat in linux

# Restart
sudo /etc/init.d/tomcat7 restart 

# Stop
sudo /etc/init.d/tomcat7 stop

miércoles, 28 de agosto de 2013

php ternary operator - operador ternario en php

muy util en vistas:

<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
esa cosa, equivale a todo este if:
<?php
if ($age < 16) {
$agestr = 'child';
} else {
$agestr = 'adult';
}
?>

jueves, 22 de agosto de 2013

swap dom elements with jquery

Util función para intercambiar elementos en el dom:


function swapElements(elm1, elm2) {
var parent1, next1,
parent2, next2;

parent1 = elm1.parentNode;
next1 = elm1.nextSibling;
parent2 = elm2.parentNode;
next2 = elm2.nextSibling;

parent1.insertBefore(elm2, next1);
parent2.insertBefore(elm1, next2);
}

uso:
swapElements(i[0], k[0]);

no olvidarse si i y k fueron extraidos del dom con jquery de colocar el subindice.
 

miércoles, 31 de julio de 2013

Primeros pasos en laravel 4


Hoy les vengo a contar sobre este framework que llegó a mi casi por casualidad por ser el que utilizó un cliente para crear un CMS, al cual nos ha solicitado adaptar numerosos templates.

A primera vista parece un poco complejo comparado con codeigniter, pero a medida que fuí aprendiendo a utilizarlo no ha dejado de sorprenderme, lo práctico que resulta blade (el parseador de vistas y templates), y la potencia y flexibilidad que nos da el archivo de routes es increible, por ejemplo.

El ORM resulta fácil de aprender y nos simplifica la vida con las consultas evitando todos esos mugrosos joins que usaba antes en codeigniter. Todavía hay muchisimas funciones del framework que aún no he investigado pero en este momento ya puedo afirmar que aprender laravel vale la pena.

Me he descargado recientemente la versión 4 del framework recien sacada del horno. Comenzaré a utilizarla para un proyecto personal, no se sorprendan si muchas de las siguientes entradas del blog están dedicadas a laravel4.

lunes, 15 de julio de 2013

copy things from one server to another - copiar archivos entre servidores

Con scp copiamos carpetas o archivos entre servers sin tener que descargar todo y volverlo a subir. Solo ejecutar el comando y se arreglan entre ellos.

copy from a remote machine to my machine:
scp user@192.168.1.100:/home/remote_user/Desktop/file.txt /home/me/Desktop/file.txt

copy from my machine to a remote machine:
scp /home/me/Desktop/file.txt user@192.168.1.100:/home/remote_user/Desktop/file.txt

copy all file*.txt from a remote machine to my machine (file01.txt, file02.txt, etc.; note the quotation marks:
scp "user@192.168.1.100:/home/remote_user/Desktop/file*.txt" /home/me/Desktop/file.txt

copy a directory from a remote machien to my machine:
scp -r user@192.168.1.100:/home/remote_user/Desktop/files /home/me/Desktop/.

lunes, 8 de julio de 2013

many dropbox in the same ubuntu - muchos dropboxes en ubuntu

Tienes la necesidad de tener varias cuentas de dropbox conviviendo en tu equipo? Bueno a mi me pasa, una para el trabajo, una para la vida ... se puede usar varios dropbox en ubuntu de la siguiente manera:

HOME=$HOME/nombredelanuevacarpetadedropbox /usr/bin/dropbox start -i

Con esto aparece el típico instalador de dropbox permitiendonos sincronizar otra cuenta.

Si queremos que el nuevo dropbox se inicie con el sistema editamos sudo gedit /etc/rc.local

agregamos

su tunombredeusuario -c “HOME=$HOME/nombredelanuevacarpetadedropbox /usr/bin/dropbox start”

y listo.

martes, 2 de julio de 2013

codeigniter log data to the db

Creé este pequeño model para debuguear un script que corre en background. Su mision es loguear cualquier tipo de información con un stamp de tiempo en la bd.

Su uso es muy simple. Solo cargamos el modelo y hacemos: $this->blog->message('acá la cosa que queremos loguear');

a continuacion la clase:

/*
--
-- Table structure for table `logs`
--

CREATE TABLE IF NOT EXISTS `logs` (
`stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`message` varchar(2000) NOT NULL,
`type` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/


dblog->message($thingToLog);
*
* by Patricio Gabriel Maseda ** 2013 ** patricio.mase@gmail.com
*
*/

class Dblog extends CI_Model {

public function __construct(){

parent::__construct();
}

public function message($message){

return $this->db
->set('message', $message)
->set('type', 'message')
->insert('logs');
}
}

viernes, 17 de mayo de 2013

removing mate desktop on ubuntu -- removiendo escritorio mate en ubunt

bueno me agarró por probar mate 1.6. Si después quieren sacarlo como me pasa a mi agarran y hacen:

sudo apt-get remove mate-archive-keyring mate-notification-daemon atril atril-common caja caja-common engrampa engrampa-common eom eom-common gir1.2-mate-panel libatril libcaja-extension libmarco libmatedesktop libmatekbd libmatekeyring libmatemenu libmatepanelapplet libmatepolkit libmateweather libmateweather-common libmatewnck libmatewnck-common marco marco-common mate-applets mate-applets-common mate-backgrounds mate-calc mate-control-center mate-core mate-desktop mate-desktop-common mate-desktop-environment mate-dialogs mate-icon-theme mate-media mate-media-common mate-media-gstreamer mate-menus mate-panel mate-panel-common mate-polkit mate-power-manager mate-power-manager-common mate-screensaver mate-screensaver-common mate-session-manager mate-settings-daemon mate-settings-daemon-common mate-settings-daemon-gstreamer mate-system-monitor mate-terminal mate-terminal-common mate-themes mate-utils mate-utils-common pluma pluma-common


 Saludos

domingo, 24 de marzo de 2013

Ver log errores PHP en tiempo real (watch PHP errors in real time)


Para ver la lista de procesos:
top

Para ver los logs en tiempo real:

tail -f /var/log/apache2/users/*

(o cambiar por la carpeta o archivo que sea necesario)