Snippets - Webeame Snippets


Añadir snippet

Últimos snippets



min-height también en IE6

Código css para emular el comportamiento de la propiedad css min-height en aquellos navegadores que no la soportan
  1. #elemento {
  2. height: auto !important;
  3. height: XXXpx;
  4. min-height: XXXpx;
  5. }

En CSS css min-height por brainet hace on 7/2/08 | Comentarios



Calcular distancia entre 2 puntos

Calculamos la distancia entro 2 puntos con las coordenadas de google maps
  1. function getDistance($lat1, $long1, $lat2, $long2)
  2. {
  3. $earth = 6371; //km
  4. //$earth = 3960; //millas
  5.  
  6. //Punto 1 coordenadas
  7. $lat1 = deg2rad($lat1);
  8. $long1= deg2rad($long1);
  9.  
  10. //Punto 2 coordenadas
  11. $lat2 = deg2rad($lat2);
  12. $long2= deg2rad($long2);
  13.  
  14. $dlong=$long2-$long1;
  15. $dlat=$lat2-$lat1;
  16.  
  17. $sinlat=sin($dlat/2);
  18. $sinlong=sin($dlong/2);
  19.  
  20. $a=($sinlat*$sinlat)+cos($lat1)*cos($lat2)*($sinlong*$sinlong);
  21.  
  22. $c=2*asin(min(1,sqrt($a)));
  23.  
  24. $d=($earth*$c);
  25.  
  26. return $d;
  27. }

En PHP calcular distancias coordenadas google maps por javito hace on 5/2/08 | Comentarios



Comprobación de página inexistente

Como complemento a la función getHeaders, esta función permite revisar si una dirección web devuelve un 404 de inexistente.
  1. /**
  2. * function valida_enlace (string $url, boolean $formato = true)
  3. *
  4. * Comprueba si un enlace no devuelve un 404
  5. *
  6. * return boolean
  7. */
  8. function valida_enlace ($url, $formato = true) {
  9. $head = getHeaders($url, $formato);
  10.  
  11. return (is_array($head) && strlen($head[0]) && !stristr($head[0], '404'))?$head:false;
  12. }

En PHP 404 página inexistente por Lito hace on 4/2/08 | Comentarios



Obtener encabezados de una dirección web

Devuelve las cabeceras de una dirección web
  1. /**
  2. * function getHeaders (string $url, boolean $formato = true)
  3. *
  4. * Devuelve las cabeceras de una dirección web
  5. * Solo acepta HTTP como metodo
  6. *
  7. * Si $formato es true devuelve un array asociativo,
  8. * de lo contrario, un array de claves simples
  9. *
  10. * return array
  11. */
  12. function getHeaders ($url, $formato = true) {
  13. if (function_exists('get_headers')) {
  14. return @get_headers($url, $formato);
  15. }
  16.  
  17. $partes = @parse_url($url);
  18.  
  19. if (empty($partes['host'])) {
  20. return false;
  21. }
  22.  
  23. if (empty($partes['path'])) {
  24. $path = '/';
  25. } else {
  26. $path = $partes['path'];
  27. }
  28.  
  29. if (!empty($partes['query'])) {
  30. $path .= '?'.$partes['query'];
  31. }
  32.  
  33. $partes['port'] = isset($partes['port'])?$partes['port']:80;
  34.  
  35. $socket = fsockopen($partes['host'], $partes['port'], $errno, $errstr, 30);
  36.  
  37. if (!$socket) {
  38. return false;
  39. }
  40.  
  41. $header = 'HEAD '.$path.' HTTP/1.1'."\r\n"
  42. .'Host: '.$partes['host'].(empty($partes['port'])?'':(':'.$partes['port']))."\r\n"
  43. .'Connection: Close'."\r\n\r\n";
  44.  
  45. fwrite($socket, $header);
  46.  
  47. $datos = array();
  48. $fin = false;
  49.  
  50. while (!feof($socket) or ($fin == true)) {
  51. if ($header = fgets($socket, 1024)) {
  52. if ($header == "\r\n") {
  53. $fin = true;
  54. break;
  55. } else {
  56. $header = trim($header);
  57. }
  58.  
  59. if ($formato == 1) {
  60. $key = explode(':', $header);
  61. $key = array_shift($key);
  62.  
  63. if ($key == $header) {
  64. $datos[] = $header;
  65. } else {
  66. $datos[$key] = substr($header,strlen($key)+2);
  67. }
  68.  
  69. unset($key);
  70. } else {
  71. $datos[] = $header;
  72. }
  73. }
  74. }
  75.  
  76. fclose($socket);
  77.  
  78. return $datos;
  79. }

En PHP encabezados cabeceras url por Lito hace on 4/2/08 | Comentarios



Enviar un formulario desde PHP

Permite enviar un formulario directamente desde un array de datos en PHP.
  1. /**
  2. * function enviaPOST (string $host, string $url, array $datos, boolean $error = false)
  3. *
  4. * Envia un formulario a una url remota y obtiene el resultado
  5. *
  6. * @$host: Servidor de destino
  7. * @$url: Url del fichero que recibirá el formulario
  8. * @$datos: Datos que se enviarán, en formato $datos['clave'] = 'valor';
  9. * @$error: Enseñar el error en caso de problemas en el envío
  10. *
  11. * return string
  12. */
  13.  
  14. function enviaPOST ($host, $url, $datos, $error = false) {
  15. $da = fsockopen($host, 80, $errno, $errstr);
  16. $postdata = '';
  17.  
  18. if (!$da) {
  19. return false;
  20. }
  21.  
  22. if (is_array($datos) && (count($datos) > 0)) {
  23. foreach ($datos as $k => $v) {
  24. $postdata .= rawurlencode($k).'='.rawurlencode($v).'&';
  25. }
  26.  
  27. $postdata = substr($postdata, 0, -1);
  28. }
  29.  
  30. $respuesta = '';
  31. $salida = 'POST '.$url.' HTTP/1.1'
  32. ."\r\n".'Host: '.$host
  33. ."\r\n".'User-Agent: PHP Script'
  34. ."\r\n".'Content-Type: application/x-www-form-urlencoded'
  35. ."\r\n".'Content-Length: '.strlen($postdata)
  36. ."\r\n".'Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66'
  37. ."\r\n".'Connection: close'
  38. ."\r\n\r\n".$postdata;
  39.  
  40. fwrite($da, $salida);
  41.  
  42. while (!feof($da)) {
  43. $respuesta .= fgets($da, 1024);
  44. }
  45.  
  46. fclose($da);
  47.  
  48. $respuesta = explode("\r\n\r\n", $respuesta);
  49. $header = array_shift($respuesta);
  50. $contenido = implode('', $respuesta);
  51.  
  52. if (($error == true) || (strstr($header, 'Transfer-Encoding: chunked') == false)) {
  53. return trim($contenido);
  54. }
  55.  
  56. return false;
  57. }

En PHP post enviar formulario por Lito hace on 4/2/08 | Comentarios



Crear directorios de manera recursiva

Genera un arbol de directorios de manera recursiva.
  1. /**
  2. * function dir_recursivo (string $destino)
  3. *
  4. * Crea un arbol de directorios de manera recursiva
  5. *
  6. * return boolean
  7. */
  8. function dir_recursivo ($destino) {
  9. if (is_dir($destino)) {
  10. return true;
  11. }
  12.  
  13. $dirs = explode('/', $destino);
  14. $dir = '';
  15.  
  16. foreach ($dirs as $part) {
  17. if (empty($part) || ($part == '.')) {
  18. continue;
  19. }
  20.  
  21. $dir .= '/'.$part;
  22.  
  23. if ($part == '..') {
  24. continue;
  25. }
  26.  
  27. if (!is_dir($dir)) {
  28. $ok = @mkdir($dir, 0755);
  29.  
  30. if (!$ok) {
  31. return false;
  32. }
  33. }
  34. }
  35.  
  36.  
  37. return is_dir($destino);
  38. }

En PHP directorios recursivo por Lito hace on 4/2/08 | Comentarios



Texto simple para URL

Cambia todo tipo de carácteres extraños por letras o símbolos equivalentes para poder usarlo como complemento en las URL's
  1. /**
  2. * function palabra_simple (string $texto, boolean $min, boolean $html = false)
  3. *
  4. * Cambia las letras con tildes, eñes o caracteres raros por su concordancia natural.
  5. * En caso de que min sea true devolvera el texto en minúsculas.
  6. *
  7. * @$min: true/false para devolver el resultado en minúsculas
  8. * @$html: true/false si la cadena de texto que recibe está formateada con htmlentities
  9. *
  10. * return string
  11. */
  12. function palabra_simple ($texto, $min = true, $html = false) {
  13. if (!$html) {
  14. $texto = htmlentities($texto, ENT_QUOTES, 'ISO-8859-1')
  15. }
  16.  
  17. $texto = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/i', '$1', $texto);
  18. $texto = html_entity_decode($texto, ENT_QUOTES, 'ISO-8859-1');
  19.  
  20. $texto = preg_replace(array('/[^a-z0-9_-]/i', '/-+/', '/^-/', '/-$/',), array('-', '-', '', ''), $texto);
  21.  
  22. return $min?strtolower($texto):$texto;
  23. }

En PHP url texto simple por Lito hace on 4/2/08 | Comentarios



Cortar un texto en la longitud deseada

Corta un texto por el limite seleccionado y devuelve el resultado. Esta función es útil para crear el texto de entradillas ya que no incluye las etiquetas HTML como enlaces, strong y demás y para sistemas que usen entidades HTML para los acentos, comprueba que no corte ninguna de estas entidades.
  1. /**
  2. * function corta_texto (string $txt, integer $limite = 150, string $fin = '...', string $encontrar = ' ')
  3. *
  4. * Corta un texto por el limite seleccionado y devuelve el resultado.
  5. *
  6. * @$txt: Texto a cortar
  7. * @$limite: Límite máximo de caractere que se permiten al texto
  8. * @$fin: Cadena para finalizar el texto cortado
  9. * @$encontrar: Busca la última posición de esta cadena en dentro del límite de texto y lo corta en esa posición. Por defecto un espacio.
  10. *
  11. * return string
  12. */
  13. function corta_texto ($txt, $limite = 150, $fin = '...', $encontrar = ' ') {
  14. // Primero elimino todas las etiquetas de HTML
  15. $txt = preg_replace('/<[^>]+>/', '', $txt);
  16.  
  17. // Si la cadena es más corta que el límite
  18. if (strlen($txt) <= $limite) {
  19. // Quito los saltos de linea y los paso a HTML
  20. return preg_replace("/\n/s",'<br />', preg_replace("/(\r\n|\r)/s","\n", $txt));
  21. }
  22.  
  23. // Si no encuentra ninguna entidad HTML corta el texto y devuelve el resultado
  24. if (strstr($txt, '&') === false) {
  25. return substr($txt, 0, $limite).$fin;
  26. }
  27.  
  28. $caracteres = preg_split('/(&[^;\s]+;)|/', $txt, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
  29. $longitud = count($caracteres);
  30.  
  31. if ($longitud === 0) {
  32. return '';
  33. }
  34.  
  35. $inicio = max(0, -$longitud);
  36. $inicio_real = $caracteres[$longitud + $inicio][1];
  37.  
  38. if (($inicio + $limite) >= $longitud) {
  39. $txt = substr($txt, $inicio_real).$fin;
  40. } else {
  41. $remate = $caracteres[max($inicio, 0) + $limite][1] - $inicio_real;
  42.  
  43. while (($remate >= 0) && (!preg_match('/[ ,\.\;]/', $txt[$remate]))) {
  44. $remate--;
  45. }
  46.  
  47. $txt = substr($txt, $inicio_real, $remate).$fin;
  48. }
  49.  
  50. // Si no se define una cadena de texto a encontrar.
  51. if (empty($encontrar)) {
  52. return preg_replace("/\n/s",'<br />', preg_replace("/(\r\n|\r)/s","\n", $txt)).$fin;
  53. }
  54.  
  55. $pos = strrpos($txt, $encontrar);
  56.  
  57. if ($pos === false) {
  58. return preg_replace("/\n/s",'<br />', preg_replace("/(\r\n|\r)/s","\n", $txt)).$fin;
  59. } else {
  60. return preg_replace("/\n/s",'<br />', preg_replace("/(\r\n|\r)/s","\n", substr($txt, 0, $pos))).$fin;
  61. }
  62. }

En PHP cortar texto por Lito hace on 4/2/08 | Comentarios



Codificar correos electrónicos

Codifica los correos electrónicos encontrados en un texto para evitar el spam
  1. /**
  2. * function codifica_email (string $txt)
  3. *
  4. * Codifica los correos electrónicos encontrados en un texto para evitar el spam
  5. *
  6. * return string
  7. */
  8. function codifica_email ($txt) {
  9. if (strstr($txt, '@')) {
  10. '/([a-z0-9\._-]+@[^"\s\',\$\;]+)/ie',
  11. '$encontrado',
  12. '
  13. $long = strlen($encontrado[1]);
  14. $correo = "";
  15.  
  16. for ($i = 0; $i < $long; $i++) {
  17. $correo .= "&#".ord($encontrado[1][$i]).";";
  18. }
  19.  
  20. return $correo;
  21. '
  22. ),
  23. $txt
  24. );
  25.  
  26. $txt = str_replace('mailto:', '&#109;&#097;&#105;&#108;&#116;&#111;&#058;', $txt);
  27. }
  28.  
  29. return $txt;
  30. }

En PHP email codificar por Lito hace on 4/2/08 | Comentarios



Array ordenado aleatoriamente

Función que recoge un array y lo devuelve ordenado aleatoriamente
  1. /**
  2. * function array2rand (array $array)
  3. *
  4. * Devuelve un array ordenado aleatoriamente
  5. *
  6. * return array
  7. */
  8. function array2rand ($array) {
  9. if (!is_array($array)) {
  10. return array();
  11. }
  12.  
  13. srand((float) microtime() * 10000000);
  14.  
  15. $claves = array_rand($array, count($array));
  16. $resultado = array();
  17.  
  18. foreach ($claves as $v) {
  19. $resultado[$v] = $array[$v];
  20. }
  21.  
  22. return $resultado;
  23. }

En PHP array aleatorio por Lito hace on 4/2/08 | Comentarios