Categoría: PHP - Webeame Snippets


Añadir snippet

Últimos snippets en PHP



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



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