Últimos snippets
Patrón Singleton en PHP5
Esto permite que se obtenga una simple instancia de la clase Example.
<?php class Example { // Hold an instance of the class // A private constructor; prevents direct creation of object private function __construct() { echo 'I am constructed'; } // The singleton method { $c = __CLASS__; self::$instance = new $c; } return self::$instance; } // Example method public function bark() { echo 'Woof!'; } // Prevent users to clone the instance public function __clone() { } } ?>
<?php // Error porque el constructor es privado $test = new Example; // Devuelve siempre la misma instancia $test = Example::singleton(); $test->bark(); // Lanzará un error $test_clone = clone($test); ?>
En PHP patrón singleton por admin hace on 30/1/08 | Comentarios
Patrón Factory method en PHP5
Al definir este método en una clase se nos permite que los drivers sean cargados al vuelo. Si la clase Example fuera una clase de abstracción de base de datos, cargar un manejador de MySQL y SQLite podría ser hecho como sigue:
<?php class Example { // The factory method { if (include_once 'Drivers/' . $type . '.php') { $classname = 'Driver_' . $type; return new $classname; } else { throw new Exception ('Driver not found'); } } } ?>
<?php // Load a MySQL Driver $mysql = Example::factory('MySQL'); // Load a SQLite Driver $sqlite = Example::factory('SQLite'); ?>
En PHP patrón factory method php5 por admin hace on 30/1/08 | Comentarios
Ejemplo básico para generar una imagen con GD
http://www.washeebo.com/sargento/03_php/0301/0301.php
<?php // Definimos los headers // Creamos la imagen $imagen = imagecreate(400,300); // Agregamos contenido $blanco = imagecolorallocate($imagen,255,255,255); $negro = imagecolorallocate($imagen,0,0,0); $rojo = imagecolorallocate($imagen,200,0,0); $verde = imagecolorallocate($imagen,0,130,0); $gris = imagecolorallocate($imagen,140,140,140); imagefilledrectangle($imagen,50,50,145,250,$verde); imagefilledrectangle($imagen,255,50,350,250,$rojo); imagefilledellipse($imagen,200,150,80,80,$gris); imagerectangle($imagen,50,50,350,250,$negro); // Damos salida a la imagen imagegif($imagen); // Destruimos la imagen imagedestroy($imagen); ?>
En PHP GD imagen por admin hace on 30/1/08 | Comentarios
Transparencia con CSS
- La especificación CSS3 tiene la propiedad opacity, la cual toma valores entre 0 (invisible) y 1 (opaco). - Los navegadores Mozilla poseen la propiedad -moz-opacity que toma los mismos valores que la propiedad anterior. - Internet explorer posee el filtro opacity que toma valores entre 0 y 100.
#caja { opacity: 0.2; -moz-opacity: 0.2; filter: alpha(opacity=20); }
En CSS transparencias por admin hace on 30/1/08 | Comentarios
Esquinas redondeadas con Prototype
<script> var Rounded = Class.create(); Rounded.prototype = { initialize : function(el){ var x, el = $(el), background = el.style.backgroundColor; for(x=0;x<11;x++){ var d = "<div style='background: " + background + "; border-style: solid; border-color: white; height: 1px; overflow: hidden; border-width: 0 " + this.index[x] + "px'> </div>"; new Insertion.Top(el, d); new Insertion.Bottom(el, d); } }, } new Rounded('blah'); </script>
En JavaScript esquinas prototype por admin hace on 30/1/08 | Comentarios
Hack CSS para Internet Explorer 7
Usar !important cuando no queremos dar cierta propiedad a IE6
body { background: #fff; /* Todos los navegadores */ *background: #000; /* IE6 e IE7 */ }
Hack exclusivo para IE7
body { background: #fff !important; /* Firefox, IE7 y los demás */ background: #000; /* IE6 y anteriores */ }
Más en http://granimpetu.com/articulos/hack-css-para-internet-explorer-7/
body { background: #fff !important; /* Firefox y los demás */ *background: #000 !important; /* Sólo IE7 */ *background: #ccc; /* Sólo IE6 */ }
En CSS hacks por admin hace on 30/1/08 | Comentarios
htaccess para protegerse contra el Hotlinking
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # Options +FollowSymlinks RewriteCond %{REQUEST_FILENAME} .(jpg|png|gif|bmp)$ [NC] RewriteCond %{HTTP_REFERER} !^$ [NC] RewriteCond %{HTTP_REFERER} !tu_ web.com [NC] RewriteCond %{HTTP_REFERER} !feedburner.com [NC] RewriteCond %{HTTP_REFERER} !bloglines.com [NC] RewriteCond %{HTTP_REFERER} !newsgator.com [NC] RewriteCond %{HTTP_REFERER} !netvibes.com [NC] RewriteCond %{HTTP_REFERER} !newsalloy.com [NC] RewriteCond %{HTTP_REFERER} !gritwire.com [NC] RewriteCond %{HTTP_REFERER} !rojo.com [NC] RewriteCond %{HTTP_REFERER} !blogrovr.com [NC] RewriteCond %{HTTP_REFERER} !alesti.org [NC] RewriteCond %{HTTP_REFERER} !fastladder.com [NC] RewriteCond %{HTTP_REFERER} !google. [NC] RewriteCond %{HTTP_REFERER} !yahoo. [NC] RewriteCond %{HTTP_REFERER} !msn. [NC] RewriteCond %{HTTP_REFERER} !ask. [NC] RewriteCond %{HTTP_REFERER} !altavista. [NC] RewriteCond %{HTTP_REFERER} !attensa.com [NC] RewriteCond %{HTTP_REFERER} !search?q=cache [NC] RewriteRule (.*) http://www.otro_servidor.com/imagen_alt.jpg [NC,L] </IfModule>
En Otros hotlinking htaccess apache por admin hace on 30/1/08 | Comentarios
Filtro de parámetros en PHP5
Validar email
<?php if (filter_has_var ( INPUT_POST , ’submit’)) { $submit = filter_input(INPUT_POST, ’submit’, FILTER_SANITIZE_SPECIAL_CHARS); } ?>
Más: http://www.anieto2k.com/2007/12/05/filtro-de-parametros-en-php5/
<?php ?>
En PHP filter sanitaze parametros por admin hace on 30/1/08 | Comentarios
Hacer backup de MySQL desde un script en PHP
<?php // Añade tu codigo de autentificación aquí, etc. // ¿ Donde se almacena la copia? Debe ser escribible por el servidor web // y estar fuera del directorio raiz de la web, para que nadie pueda // bajarse tu BD desde su navegador // para crear enlaces a esta pagina ( accion del formulario, etc.) /**** ALGUNAS FUNCIONES ****/ function doHeader($title) { // crea una encabezado de página sencillo. ?><html><head><title> } function doFooter() { // crea un pie de página sencillo ?></body></html><?php } // si la variable filename en POST no está vacia, es que se ha enviado // el formulario // ahora validaremos y verificaremos las entradas // para saber lo que tenemos y abortar si hay algo mal $n = 0; /* pondremos cualquier error dentro de este array, y al final los listaremos todos para que los vea el usuario y pueda corregirlos */ $errors[$n] = "Debe introducir un nombre de fichero."; $n++; } $errors[$n] = "Debe introducir un nombre de usuario MySQL."; $n++; } $errors[$n] = "Debe introducir un password MySQL ."; $n++; } // Ha seleccionado copiar una BD, pero no han dicho cual if ($_POST['backupall'] == 'false' AND $errors[$n] = "Has selecciona copiar una base de datos, ". "pero no especificaste cual."; $n++; } if ($n > 0) { // Si hubo errores en la fase de validacion... // muestra una pagina de error doHeader('Remote Database Backup'); ?><h1>Remote Database Backup</h1> <h2>No se pudo realizar la copia.</h2> <ul> // recorre los errores <?php foreach ($errors as $err) { ?><li> </li><?php } ?> </ul> <a href="<?php echo THISPAGE;?>"> Volver al formulario de Backup</a> <?php doFooter(); } // Si estamos aqui, es que se ha acabado bien la validación // hacemos "escape shell" a los argumentos para evitar // la inyección de código // recuerda que esto es solo seguridad basica, se deberian // añadir mas capas para mayor seguridad // Queremos copiar todas las bases de datos? $backupall = ($_POST['backupall'] == 'false') ? false : true; // Si queremos copiar todas, ponemos esto con -A en el comando, // sino, lo ponemos con el nombre de la base de datos a copiar $dbarg = $backupall ? '-A' : $_POST['backupwhichdb']; // formamos el comando a ejecutar $command = "mysqldump ".$dbarg." -u ".$_POST['mysqluser']. " -p".$_POST['mysqlpass']." -r \"".BACKUPDIR.$_POST['filename']. "\" 2>&1"; // creamos una cabecera y mostramos el progreso al usuario // Podria tomar su tiempo doHeader('Remote Database Backup'); ?><h1>Ejecutando el backup, por favor espere...</h1><?php // execute the command we just set up // si eligieron comprimir con bzip, entonces se hace if ($_POST['bzip'] == 'true') { } // OK, terminamos. Digale al usuario lo que ha pasado. // Si ocurrio algun error, se muestran en la llamada a system() ?><h2>Comando ejecutado. Si hubo errores, Se mostrarán arriba.</h2> <a href="<?php echo THISPAGE;?>"> Volver al formulario de Backup</a> <?php // pretty footer doFooter(); // y salidos, hemos terminado! } // Si el formulario no se envió, entonces se muestra al usuario // por primera vez con su cabecera doHeader('Remote Database Backup'); ?><h1>Remote Database Backup</h1> <p><em><strong>Por favor:</strong> una vez pulse Crear, la copia podría durar unos 15 seg. para que se cree. La página no se cargará inmediatamente, ten paciencia.</em></p> <form name="dbbackup" method="post" action="<?php echo THISPAGE;?>"> Nombre del fichero: <strong><?php echo BACKUPDIR;?></strong> <input type="text" name="filename" value="<?php echo date('dMY_H.i.s').'.sql';?>" /><br /> <input type="checkbox" name="bzip" value="true" id="bzipTick" /> <label for="bzipTick">Usar Bzip2 para compresion</label><br /><br /> Nombre de usuario MySQL: <input type="text" name="mysqluser" value="" /><br /> Password MySQL: <input type="password" name="mysqlpass" value="" /><br /><br /> Backup ¿ de que ?<br /> <input type="radio" name="backupall" value="true" id="backupallTrue" /> <label for="backupallTrue">Todas las bases de datos</label><br /> <input type="radio" name="backupall" value="false" id="backupallFalse" /> <label for="backupallFalse">Una en especifico</label> <input type="text" name="backupwhichdb" value="" /><br /> <br /><br /> <input type="submit" value="Crear" /> </form> <?php // el pie de página doFooter(); ?>
En PHP backup MySQL por admin hace on 30/1/08 | Comentarios
Función para generar cadenas para URLs
function slug($slug) { $temp = ""; foreach ($slug as $token) { $temp .= $token." "; } return $slug; }
En PHP url friendly rewrite por admin hace on 30/1/08 | Comentarios
