Snippets - Webeame Snippets


Añadir snippet

Últimos snippets



Patrón Singleton en PHP5

El patrón Singleton se aplica a situaciones en las cuales hay la necesidad de tener una sola instancia de una clase. El ejemplo más común de esto es una conexión de base de datos. Tendremos una simple instancia fácilmente accesible a muchos otros objetos.
  1. <?php
  2. class Example
  3. {
  4. // Hold an instance of the class
  5. private static $instance;
  6.  
  7. // A private constructor; prevents direct creation of object
  8. private function __construct()
  9. {
  10. echo 'I am constructed';
  11. }
  12.  
  13. // The singleton method
  14. public static function singleton()
  15. {
  16. if (!isset(self::$instance)) {
  17. $c = __CLASS__;
  18. self::$instance = new $c;
  19. }
  20.  
  21. return self::$instance;
  22. }
  23.  
  24. // Example method
  25. public function bark()
  26. {
  27. echo 'Woof!';
  28. }
  29.  
  30. // Prevent users to clone the instance
  31. public function __clone()
  32. {
  33. trigger_error('Clone is not allowed.', E_USER_ERROR);
  34. }
  35.  
  36. }
  37.  
  38. ?>
Esto permite que se obtenga una simple instancia de la clase Example.
  1. <?php
  2. // Error porque el constructor es privado
  3. $test = new Example;
  4.  
  5. // Devuelve siempre la misma instancia
  6. $test = Example::singleton();
  7. $test->bark();
  8.  
  9. // Lanzará un error
  10. $test_clone = clone($test);
  11.  
  12. ?>

En PHP patrón singleton por admin hace on 30/1/08 | Comentarios



Patrón Factory method en PHP5

El patrón Factory permita la instancia de objetos en tiempo de ejecución. Es llamado el patrón Factory puesto que es responsable de "manufacturar" un objeto.
  1. <?php
  2. class Example
  3. {
  4. // The factory method
  5. public static function &factory($type)
  6. {
  7. if (include_once 'Drivers/' . $type . '.php') {
  8. $classname = 'Driver_' . $type;
  9. return new $classname;
  10. } else {
  11. throw new Exception ('Driver not found');
  12. }
  13. }
  14. }
  15. ?>
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:
  1. <?php
  2. // Load a MySQL Driver
  3. $mysql = Example::factory('MySQL');
  4.  
  5. // Load a SQLite Driver
  6. $sqlite = Example::factory('SQLite');
  7. ?>

En PHP patrón factory method php5 por admin hace on 30/1/08 | Comentarios



Ejemplo básico para generar una imagen con GD

  1. <?php
  2.  
  3. // Definimos los headers
  4. header("Content-type: image/gif");
  5.  
  6. // Creamos la imagen
  7. $imagen = imagecreate(400,300);
  8.  
  9. // Agregamos contenido
  10. $blanco = imagecolorallocate($imagen,255,255,255);
  11. $negro = imagecolorallocate($imagen,0,0,0);
  12. $rojo = imagecolorallocate($imagen,200,0,0);
  13. $verde = imagecolorallocate($imagen,0,130,0);
  14. $gris = imagecolorallocate($imagen,140,140,140);
  15.  
  16. imagefilledrectangle($imagen,50,50,145,250,$verde);
  17. imagefilledrectangle($imagen,255,50,350,250,$rojo);
  18. imagefilledellipse($imagen,200,150,80,80,$gris);
  19. imagerectangle($imagen,50,50,350,250,$negro);
  20.  
  21. // Damos salida a la imagen
  22. imagegif($imagen);
  23.  
  24. // Destruimos la imagen
  25. imagedestroy($imagen);
  26.  
  27. ?>
http://www.washeebo.com/sargento/03_php/0301/0301.php

En PHP GD imagen por admin hace on 30/1/08 | Comentarios



Transparencia con CSS

// introduce aquí la descripción
  1. #caja {
  2. opacity: 0.2;
  3. -moz-opacity: 0.2;
  4. filter: alpha(opacity=20);
  5. }
- 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.

En CSS transparencias por admin hace on 30/1/08 | Comentarios



Esquinas redondeadas con Prototype

  1. <script>
  2.  
  3. var Rounded = Class.create();
  4. Rounded.prototype = {
  5. initialize : function(el){
  6. var x, el = $(el), background = el.style.backgroundColor;
  7.  
  8. for(x=0;x<11;x++){
  9. var d = "<div style='background: " + background + "; border-style: solid; border-color: white; height: 1px; overflow: hidden; border-width: 0 " + this.index[x] + "px'>&nbsp;</div>";
  10. new Insertion.Top(el, d);
  11. new Insertion.Bottom(el, d);
  12. }
  13. },
  14. index : new Array(0,1,1,1,2,2,3,4,5,7,10)
  15. }
  16.  
  17. new Rounded('blah');
  18.  
  19. </script>

En JavaScript esquinas prototype por admin hace on 30/1/08 | Comentarios



Hack CSS para Internet Explorer 7

Un asterisco delante de la propiedad CSS y así sólo será reconocida por Internet Explorer 6 y 7
  1. body {
  2. background: #fff; /* Todos los navegadores */
  3. *background: #000; /* IE6 e IE7 */
  4. }
Usar !important cuando no queremos dar cierta propiedad a IE6
  1. body {
  2. background: #fff !important; /* Firefox, IE7 y los demás */
  3. background: #000; /* IE6 y anteriores */
  4. }
Hack exclusivo para IE7
  1. body {
  2. background: #fff !important; /* Firefox y los demás */
  3. *background: #000 !important; /* Sólo IE7 */
  4. *background: #ccc; /* Sólo IE6 */
  5. }
Más en http://granimpetu.com/articulos/hack-css-para-internet-explorer-7/

En CSS hacks por admin hace on 30/1/08 | Comentarios



htaccess para protegerse contra el Hotlinking

Visto en http://www.perraco.com/protegete-de-manera-efectiva-contra-el-hotlinking/
  1. <IfModule mod_rewrite.c>
  2. RewriteEngine On
  3. RewriteBase /
  4.  
  5. # Options +FollowSymlinks
  6.  
  7. RewriteCond %{REQUEST_FILENAME} .(jpg|png|gif|bmp)$ [NC]
  8. RewriteCond %{HTTP_REFERER} !^$ [NC]
  9. RewriteCond %{HTTP_REFERER} !tu_ web.com [NC]
  10. RewriteCond %{HTTP_REFERER} !feedburner.com [NC]
  11. RewriteCond %{HTTP_REFERER} !bloglines.com [NC]
  12. RewriteCond %{HTTP_REFERER} !newsgator.com [NC]
  13. RewriteCond %{HTTP_REFERER} !netvibes.com [NC]
  14. RewriteCond %{HTTP_REFERER} !newsalloy.com [NC]
  15. RewriteCond %{HTTP_REFERER} !gritwire.com [NC]
  16. RewriteCond %{HTTP_REFERER} !rojo.com [NC]
  17. RewriteCond %{HTTP_REFERER} !blogrovr.com [NC]
  18. RewriteCond %{HTTP_REFERER} !alesti.org [NC]
  19. RewriteCond %{HTTP_REFERER} !fastladder.com [NC]
  20. RewriteCond %{HTTP_REFERER} !google. [NC]
  21. RewriteCond %{HTTP_REFERER} !yahoo. [NC]
  22. RewriteCond %{HTTP_REFERER} !msn. [NC]
  23. RewriteCond %{HTTP_REFERER} !ask. [NC]
  24. RewriteCond %{HTTP_REFERER} !altavista. [NC]
  25. RewriteCond %{HTTP_REFERER} !attensa.com [NC]
  26. RewriteCond %{HTTP_REFERER} !search?q=cache [NC]
  27. RewriteRule (.*) http://www.otro_servidor.com/imagen_alt.jpg [NC,L]
  28.  
  29. </IfModule>

En Otros hotlinking htaccess apache por admin hace on 30/1/08 | Comentarios



Filtro de parámetros en PHP5

Comprobar y limpiar una variable POST
  1. <?php
  2. if (filter_has_var ( INPUT_POST , ’submit’)) {
  3. $submit = filter_input(INPUT_POST, ’submit’, FILTER_SANITIZE_SPECIAL_CHARS);
  4. }
  5. ?>
Validar email
  1. <?php
  2. var_dump(filter_var('nombre@correo.com', FILTER_VALIDATE_EMAIL));
  3. ?>
Más: http://www.anieto2k.com/2007/12/05/filtro-de-parametros-en-php5/

En PHP filter sanitaze parametros por admin hace on 30/1/08 | Comentarios



Hacer backup de MySQL desde un script en PHP

Visto en http://www.leemiblog.com/Articulos/Programacion/Hacer-backup-de-MySQL-desde-un-script-en-PHP.html
  1. <?php
  2.  
  3. // Añade tu codigo de autentificación aquí, etc.
  4.  
  5. // ¿ Donde se almacena la copia? Debe ser escribible por el servidor web
  6. // y estar fuera del directorio raiz de la web, para que nadie pueda
  7. // bajarse tu BD desde su navegador
  8. define('BACKUPDIR', '/var/www/privatedata/');
  9.  
  10. // para crear enlaces a esta pagina ( accion del formulario, etc.)
  11. define('THISPAGE', $_SERVER['PHP_SELF']);
  12.  
  13. /**** ALGUNAS FUNCIONES ****/
  14. function doHeader($title) {
  15. // crea una encabezado de página sencillo.
  16. ?><html><head><title>
  17. <?php echo $title;?></title></head><body><?php
  18. }
  19.  
  20. function doFooter() {
  21. // crea un pie de página sencillo
  22. ?></body></html><?php
  23. }
  24.  
  25. // si la variable filename en POST no está vacia, es que se ha enviado
  26. // el formulario
  27. if (!empty($_POST['filename'])) {
  28. // ahora validaremos y verificaremos las entradas
  29. // para saber lo que tenemos y abortar si hay algo mal
  30. $errors = array();
  31. $n = 0;
  32. /* pondremos cualquier error dentro de este array, y al final
  33. los listaremos todos para que los vea el usuario
  34. y pueda corregirlos */
  35. if (empty($_POST['filename'])) { // no hay nombre de fichero
  36. $errors[$n] = "Debe introducir un nombre de fichero.";
  37. $n++;
  38. }
  39.  
  40. if (empty($_POST['mysqluser'])) { // no hay usuario MySQL
  41. $errors[$n] = "Debe introducir un nombre de usuario MySQL.";
  42. $n++;
  43. }
  44.  
  45. if (empty($_POST['mysqlpass'])) { // no hay password MySQL
  46. $errors[$n] = "Debe introducir un password MySQL .";
  47. $n++;
  48. }
  49.  
  50. // Ha seleccionado copiar una BD, pero no han dicho cual
  51. if ($_POST['backupall'] == 'false' AND
  52. empty($_POST['backupwhichdb'])) {
  53. $errors[$n] = "Has selecciona copiar una base de datos, ".
  54. "pero no especificaste cual.";
  55. $n++;
  56. }
  57.  
  58. if ($n > 0) { // Si hubo errores en la fase de validacion...
  59. // muestra una pagina de error
  60. doHeader('Remote Database Backup');
  61.  
  62. ?><h1>Remote Database Backup</h1>
  63. <h2>No se pudo realizar la copia.</h2>
  64. <ul>
  65. // recorre los errores
  66. <?php foreach ($errors as $err) {
  67. ?><li>
  68. <?php echo $err; // y muestra su texto ?>
  69. </li><?php
  70. }
  71. ?>
  72. </ul>
  73.  
  74. <a href="<?php echo THISPAGE;?>">
  75. Volver al formulario de Backup</a>
  76. <?php
  77.  
  78. doFooter();
  79.  
  80. die(); // sale del script
  81. }
  82.  
  83. // Si estamos aqui, es que se ha acabado bien la validación
  84. // hacemos "escape shell" a los argumentos para evitar
  85. // la inyección de código
  86. // recuerda que esto es solo seguridad basica, se deberian
  87. // añadir mas capas para mayor seguridad
  88. $_POST['filename'] = escapeshellcmd($_POST['filename']);
  89. $_POST['mysqluser'] = escapeshellarg($_POST['mysqluser']);
  90. $_POST['mysqlpass'] = escapeshellcmd($_POST['mysqlpass']);
  91. $_POST['backupwhichdb']=escapeshellarg($_POST['backupwhichdb']);
  92.  
  93. // Queremos copiar todas las bases de datos?
  94. $backupall = ($_POST['backupall'] == 'false') ? false : true;
  95.  
  96. // Si queremos copiar todas, ponemos esto con -A en el comando,
  97. // sino, lo ponemos con el nombre de la base de datos a copiar
  98. $dbarg = $backupall ? '-A' : $_POST['backupwhichdb'];
  99.  
  100. // formamos el comando a ejecutar
  101. $command = "mysqldump ".$dbarg." -u ".$_POST['mysqluser'].
  102. " -p".$_POST['mysqlpass']." -r \"".BACKUPDIR.$_POST['filename'].
  103. "\" 2>&1";
  104.  
  105. // creamos una cabecera y mostramos el progreso al usuario
  106. // Podria tomar su tiempo
  107. doHeader('Remote Database Backup');
  108.  
  109. ?><h1>Ejecutando el backup, por favor espere...</h1><?php
  110.  
  111. // execute the command we just set up
  112. system($command);
  113.  
  114. // si eligieron comprimir con bzip, entonces se hace
  115. if ($_POST['bzip'] == 'true') {
  116. system('bzip2 "'.BACKUPDIR.$_POST['filename'].'"');
  117. }
  118.  
  119. // OK, terminamos. Digale al usuario lo que ha pasado.
  120. // Si ocurrio algun error, se muestran en la llamada a system()
  121. ?><h2>Comando ejecutado.
  122. Si hubo errores, Se mostrarán arriba.</h2>
  123. <a href="<?php echo THISPAGE;?>">
  124. Volver al formulario de Backup</a>
  125. <?php
  126.  
  127. // pretty footer
  128. doFooter();
  129.  
  130. // y salidos, hemos terminado!
  131. die();
  132. }
  133.  
  134. // Si el formulario no se envió, entonces se muestra al usuario
  135. // por primera vez con su cabecera
  136. doHeader('Remote Database Backup');
  137.  
  138. ?><h1>Remote Database Backup</h1>
  139. <p><em><strong>Por favor:</strong> una vez pulse Crear,
  140. la copia podría durar unos 15 seg. para que se cree.
  141. La página no se cargará inmediatamente, ten paciencia.</em></p>
  142.  
  143. <form name="dbbackup" method="post" action="<?php echo THISPAGE;?>">
  144. Nombre del fichero: <strong><?php echo BACKUPDIR;?></strong>
  145. <input type="text" name="filename"
  146. value="<?php echo date('dMY_H.i.s').'.sql';?>" /><br />
  147. <input type="checkbox" name="bzip" value="true" id="bzipTick" />
  148. <label for="bzipTick">Usar Bzip2 para compresion</label><br /><br />
  149. Nombre de usuario MySQL:
  150. <input type="text" name="mysqluser" value="" /><br />
  151. Password MySQL:
  152. <input type="password" name="mysqlpass" value="" /><br /><br />
  153. Backup ¿ de que ?<br />
  154. <input type="radio" name="backupall" value="true" id="backupallTrue" />
  155. <label for="backupallTrue">Todas las bases de datos</label><br />
  156. <input type="radio" name="backupall" value="false" id="backupallFalse" />
  157. <label for="backupallFalse">Una en especifico</label>
  158. <input type="text" name="backupwhichdb" value="" /><br />
  159. <br /><br />
  160. <input type="submit" value="Crear" />
  161. </form>
  162.  
  163. <?php
  164.  
  165. // el pie de página
  166. doFooter();
  167.  
  168. ?>

En PHP backup MySQL por admin hace on 30/1/08 | Comentarios



Función para generar cadenas para URLs

Recibe una cadena de texto, por ejemplo el título de un artículo y lo convierte a un formáto válido para utilizarlo en URLs amigables.
  1. function slug($slug)
  2. {
  3. $slug = strtolower($slug);
  4. $slug = explode(" ", $slug);
  5.  
  6. $temp = "";
  7. foreach ($slug as $token)
  8. {
  9. if (strlen($token) >= 3 || is_numeric($token))
  10. $temp .= $token." ";
  11. }
  12.  
  13. $slug = trim($temp);
  14. $slug = str_replace("á", "a", $slug);
  15. $slug = str_replace("é", "e", $slug);
  16. $slug = str_replace("í", "i", $slug);
  17. $slug = str_replace("ó", "o", $slug);
  18. $slug = str_replace("ú", "u", $slug);
  19. $slug = str_replace("ñ", "n", $slug);
  20. $slug = str_replace("ü", "u", $slug);
  21. $slug = str_replace("è", "e", $slug);
  22. $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $slug); // only take alphanumerical characters
  23. $slug = str_replace(" ", "-", $slug); // replace spaces by dashes
  24. $slug = substr($slug, 0, 90);
  25. $slug = trim($slug, '-');
  26.  
  27. return $slug;
  28.  
  29. }

En PHP url friendly rewrite por admin hace on 30/1/08 | Comentarios