Snippets - Webeame Snippets


Añadir snippet

Últimos snippets



Encontrar la IP real de un visitante

Intenta conocer la IP real de un visitante aunque se encuentre tras un proxy
  1. /**
  2. * function ip (void)
  3. *
  4. * devuelve la IP de un usuario remoto
  5. *
  6. * return string
  7. */
  8. function ip () {
  9. $s_hxff = $_SERVER['HTTP_X_FORWARDED_FOR'];
  10. $s_ra = $_SERVER['REMOTE_ADDR'];
  11. $e_ra = $_ENV['REMOTE_ADDR'];
  12. $client_ip = empty($s_ra)?(empty($e_ra)?'unknown':$e_ra):$s_ra;
  13.  
  14. if ($s_hxff) {
  15. // los proxys van añadiendo al final de esta cabecera
  16. // las direcciones ip que van "ocultando". Para localizar la ip real
  17. // del usuario se comienza a mirar por el principio hasta encontrar
  18. // una dirección ip que no sea del rango privado. En caso de no
  19. // encontrarse ninguna se toma como valor el REMOTE_ADDR
  20.  
  21. $entries = split('[, ]', $s_hxff);
  22.  
  23. reset($entries);
  24.  
  25. while (list(, $entry) = each($entries)) {
  26. $entry = trim($entry);
  27.  
  28. if (preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $entry, $client_ip)) {
  29. // http://www.faqs.org/rfcs/rfc1918.html
  30. $private_ip = array(
  31. '/^(00)?0\./',
  32. '/^127\.(00)?0\.(00)?0\.(00)?1/',
  33. '/^192\.168\..*/',
  34. '/^172\.0?((1[6-9])|(2[0-9])|(3[0-1]))\..*/',
  35. '/^0?10\..*/'
  36. );
  37.  
  38. $found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
  39.  
  40. if ($client_ip != $found_ip) {
  41. $client_ip = $found_ip;
  42. break;
  43. }
  44. }
  45. }
  46. }
  47.  
  48. return addslashes($client_ip);
  49. }

En PHP ip real por Lito hace on 4/2/08 | Comentarios



Generar contraseñas aleatorias en PHP

Script para generación de contraseñas aleatorias
  1. <?php
  2. /**
  3. * function texto_aleatorio (integer $long = 5, boolean $lestras_min = true, boolean $letras_max = true, boolean $num = true))
  4. *
  5. * Permite generar contrasenhas de manera aleatoria.
  6. *
  7. * @$long: Especifica la longitud de la contrasenha
  8. * @$letras_min: Podra usar letas en minusculas
  9. * @$letras_max: Podra usar letas en mayusculas
  10. * @$num: Podra usar numeros
  11. *
  12. * return string
  13. */
  14. function texto_aleatorio ($long = 5, $letras_min = true, $letras_max = true, $num = true) {
  15. $salt = $letras_min?'abchefghknpqrstuvwxyz':'';
  16. $salt .= $letras_max?'ACDEFHKNPRSTUVWXYZ':'';
  17. $salt .= $num?(strlen($salt)?'2345679':'0123456789'):'';
  18.  
  19. if (strlen($salt) == 0) {
  20. return '';
  21. }
  22.  
  23. $i = 0;
  24. $str = '';
  25.  
  26. srand((double)microtime()*1000000);
  27.  
  28. while ($i < $long) {
  29. $num = rand(0, strlen($salt)-1);
  30. $str .= substr($salt, $num, 1);
  31. $i++;
  32. }
  33.  
  34. return $str;
  35. }
  36. ?>

En PHP contraseña aleatoria por Lito hace on 4/2/08 | Comentarios



Descargar el contenido de una URL con cURL

  1. function abrir($url)
  2. {
  3. $sesion = curl_init($url);
  4.  
  5. curl_setopt($sesion, CURLOPT_RETURNTRANSFER, 1);
  6. curl_setopt($sesion, CURLOPT_FOLLOWLOCATION, 1);
  7. curl_setopt($sesion, CURLOPT_TIMEOUT, 5);
  8. curl_setopt($sesion, CURLOPT_CONNECTTIMEOUT, 5);
  9.  
  10. // Nos hacemos pasar por el Firefox
  11. curl_setopt($sesion, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
  12.  
  13. $resultado = curl_exec($sesion);
  14.  
  15. curl_close($sesion);
  16.  
  17. return $resultado;
  18. }

En PHP curl por jape hace on 1/2/08 | Comentarios



Función para validar IPs

  1. function validarIP($ip)
  2. {
  3. if (($longip = ip2long($ip)) !== false)
  4. {
  5. if ($ip == long2ip($longip))
  6. {
  7. return true;
  8. }
  9. else
  10. {
  11. return false;
  12. }
  13. }
  14. else
  15. {
  16. return false;
  17. }
  18. }

En PHP IP por jape hace on 1/2/08 | Comentarios



PNGs en IE 6

// introduce aquí la descripción código necesario para la utilización de una imagen png en IE 6 y su modo de inclusión en el resto de los navegadores
  1. // inserta aquí el código
  2. #contenedor { transparent url(../img/bck_trans.png) repeat scroll left top }
  3.  
  4. /* estilo para IE 6 en una hoja condicional - OJO que la ruta de imagen es diferente */
  5. #contenedor { background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='img/bck_trans.png'); }

En CSS png ie6 por tanta hace on 30/1/08 | Comentarios



Contador simple de visitas

  1. function load_counter() {
  2. if (file_exists('counter.txt')){
  3. $n = file_get_contents('counter.txt');
  4. return intval($n);
  5. }
  6. return 0;
  7. }
  8.  
  9. function update_counter($i=1) {
  10.  
  11. $n = load_counter();
  12. $n += $i;
  13.  
  14. $fp = fopen('counter.txt', "w+");
  15. fwrite($fp, $n);
  16. fclose($fp);
  17.  
  18. return $n;
  19. }
Uso
  1. // count the current visit and output the count
  2. $visits = update_counter();
  3.  
  4. // just load the counter data
  5. $visits = load_counter();

En PHP contador visitas por admin hace on 30/1/08 | Comentarios



Escribir en fichero con Perl

// introduce aquí la descripción
  1. # Open file to write:
  2. open(FILEHANDLE, ">fichero.txt") or die 'cannot open file!';
  3.  
  4. # Modes:
  5. #
  6. # > = Write mode (overwrites file content)
  7. # >> = Append mode - adds the content to the file
  8. # < = read only mode
  9. # +>> = read/append mode
  10. # +> = read/write mode
  11.  
  12. # write to File
  13. print FILEHANDLE "Line 1n";
  14. print FILEHANDLE "Line 2n";
  15.  
  16. # close file handle
  17. close(FILEHANDLE);

En Perl escribir fichero por admin hace on 30/1/08 | Comentarios



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