Categoría: PHP - Webeame Snippets


Añadir snippet

Últimos snippets en PHP



Geolocalización en PHP5 usando GeoIP de Maxmind

// Procedimiento para determinar la ubicación geográfica de los visitantes de nuestra página
  1. <?php include_once('geoipcity.inc'); if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { $ip_address = $_SERVER["HTTP_X_FORWARDED_FOR"]; } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) { $ip_address = $_SERVER["HTTP_CLIENT_IP"]; } else { $ip_address = $_SERVER["REMOTE_ADDR"]; } $gi = geoip_open('GeoLiteCity.dat',GEOIP_STANDARD); $record = geoip_record_by_addr($gi,$ip_address); $pais = $record->country_code;?>

En PHP php 5 geolocalización ip snippet php 5 por dario hace on 29/7/08 | Comentarios



Evitar el cache de los css y js

Consiste en colocar en el link del css la fecha de modificación de la hoja de estilos.
  1. function version($file) {
  2. return $file.'?'.filemtime($file);
  3. }
  4.  
  5. <link href="<?php echo version('css.css'); ?>" rel="stylesheet" type="text/css" />
Visto en http://icebeat.bitacoras.com/post/283/evitar-el-cache-de-los-css-y-js

En PHP css javascript cache por alberto hace on 29/3/08 | Comentarios



Comprimir Javascript desde PHP sin mod_deflate

Si no tenemos acceso al servidor para activar el mod_deflate de php, podemos comprimir javascript desde php con gzip js.php
  1. <?php
  2. $file = $_GET['file'];
  3. $allow = array('js/jquery.js');
  4. if(in_array($file, $allow))
  5. {
  6. ob_start( 'ob_gzhandler' );
  7. echo join('',file($file));
  8. }
  9. ?>
y pasamos el nombre del js por $_GET:
  1. <script type="text/javascript" src="js.php?file=js/jquery.js">
  2. </script>
Asi por ejemplo dejamos la libreria jquery sobre 15-16kb Arreglado fallo de seguridad y es que primero habría que filtrar la entrada por get ya que de lo contrario se podría ver cualquier fichero del sistema operativo, gracias unsleep :D

En PHP compresion gzip mod_deflate javascript por ZiTAL hace on 27/2/08 | Comentarios



Twitter API PHP

// introduce aquí la descripción Aqui esta mi API PHP, para que puedas conectarla con twitter. Esta super facil de usar ademas de tener algo de documentacion interior. Tiene dependencias de XPath para PHP y libreria CURL. Saludos
  1. <?php
  2. /*
  3. Ejemplo de instancia
  4. */
  5.  
  6. require_once('class/twitter.class.php');
  7.  
  8. /* Metodo Constructor para Twitter */
  9. $twitter = new Twitter('miusuario','mipass');
  10.  
  11. // Ejemplo :)
  12. echo "<h1>Todos los mensajes de Fayerwayer</h1>";
  13. echo "<pre>";
  14. print_r($twitter->lineaTiempo('fayerwayer'));
  15. echo "</pre>";
  16.  
  17. // Quieres realmente postear este mensaje? Descomentalo
  18. //$twitter->postearMensaje('Mi mensaje de pruebas desde API PHP para Twitter por framirez');
  19.  
  20. // Todos mis seguidores
  21. echo "<h1>Todos mis seguidores</h1>";
  22. echo "<pre>";
  23. print_r($twitter->seguidores());
  24. echo "</pre>";
  25.  
  26. // Ahora quiero ver todos mis mensajes
  27. echo "<h1>Todos mis mensajes</h1>";
  28. echo "<pre>";
  29. foreach($twitter->lineaTiempo() as $mensajes):
  30. echo "<p>Mensaje: " . $mensajes['mensaje'] . " posteado a las " . $mensajes['hora'] . " desde " . $mensajes['desde'] ."</p>";
  31. endforeach;
  32. echo "</pre>";
  33.  
  34. <?php
  35. /*
  36.  
  37. @author: Fabian Ramirez Sepulveda
  38. @email : framirez(ARROB)gurunet.cl
  39. @web : http://www.gurunet.cl/framirez
  40.  
  41. @desc: Proyecto para tener una API desde PHP mas accesible y facil para usuarios no avanzados.
  42.  
  43. @metodos:
  44. lineaTiempo( $nickNameAmigo=opcional) - "Nos retorna todos los ultimos 10 mensajes que nuestro amigo o nosotros hemos posteado"
  45. tomarMensaje($idmensaje) - "Nos retorna el detalle completo del mensaje"
  46. postearMensaje($mensaje) - "Posteamos en tiempo real el mensaje desde PHP"
  47. seguidores() - "Nos retorna todos nuestros amigos que nos siguen"
  48. */
  49.  
  50. // Libreria necesaria para procesar Xpath
  51. require_once('XPath.class.php');
  52.  
  53. class Twitter {
  54.  
  55. var $usuario='';
  56. var $password='';
  57.  
  58. // Headers de nuestro cliente
  59. var $agente = 'Twitter PHP Class by framirez';
  60. var $headers = array('X-Twitter-Client: Twitter PHP by framirez',
  61. 'X-Twitter-Client-Version: 1.0',
  62. 'X-Twitter-Client-URL: http://www.gurunet.cl/framirez');
  63.  
  64. // Curl
  65. var $ch;
  66.  
  67. // Respuesta
  68. var $respuesta;
  69.  
  70. var $xml;
  71.  
  72. function Twitter($usuario=null, $password=null) {
  73. $this->usuario = $usuario;
  74. $this->password = $password;
  75.  
  76. // Metodo constructor automaticamente llama a Xpath
  77. $this->xml = new XPath();
  78. }
  79. /*
  80. @desc: Retornamos el maximo de 10 mensajes de amigos o mios
  81. */
  82. function lineaTiempo($nick = null) {
  83.  
  84. if(empty($nick)):
  85. $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml");
  86. $this->xml->importFromString($this->setearOpcionesCurl());
  87. else:
  88. $this->ch = curl_init("http://twitter.com/statuses/user_timeline/" . $nick . ".xml");
  89. $this->xml->importFromString($this->setearOpcionesCurl());
  90. endif;
  91.  
  92. // Xpath Match
  93. $id = $this->xml->match('//id');
  94. $nickname = $this->xml->match('//screen_name');
  95. $texto = $this->xml->match('//text');
  96. $hora = $this->xml->match('//created_at');
  97. $desde = $this->xml->match('//location');
  98. $deDonde = $this->xml->match('//source');
  99.  
  100. // Variables Temporales
  101. $i=0;
  102. $arregloMensajes = array();
  103.  
  104. // Recorro el arreglo
  105. for($i=0;$i<count($texto);$i++):
  106. $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]);
  107. $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]);
  108. $arregloMensajes[$i]['mensaje'] = $this->xml->getData($texto[$i]);
  109. $arregloMensajes[$i]['hora'] = $this->xml->getData($hora[$i]);
  110. $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]);
  111. $arregloMensajes[$i]['donde_proviene'] = $this->xml->getData($deDonde[$i]);
  112. $i++;
  113. endfor;
  114.  
  115. $this->xml->reset();
  116. return $arregloMensajes;
  117. }
  118.  
  119. function tomarMensaje($id) {
  120. $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml");
  121. $this->xml->importFromString($this->setearOpcionesCurl());
  122.  
  123. // Xpath Match
  124. $id = $this->xml->match('//id');
  125. $nickname = $this->xml->match('//screen_name');
  126. $texto = $this->xml->match('//text');
  127. $hora = $this->xml->match('//created_at');
  128. $desde = $this->xml->match('//location');
  129. $deDonde = $this->xml->match('//source');
  130.  
  131. // Variables Temporales
  132. $arregloMensajes = array();
  133.  
  134. // Recorro el arreglo
  135. $arregloMensajes['id'] = $this->xml->getData($id[0]);
  136. $arregloMensajes['usuario'] = $this->xml->getData($nickname[0]);
  137. $arregloMensajes['mensaje'] = $this->xml->getData($texto[0]);
  138. $arregloMensajes['hora'] = $this->xml->getData($hora[0]);
  139. $arregloMensajes['desde'] = $this->xml->getData($desde[0]);
  140. $arregloMensajes['donde_proviene'] = $this->xml->getData($deDonde[0]);
  141.  
  142. $this->xml->reset();
  143. return $arregloMensajes;
  144. }
  145.  
  146. function postearMensaje($mensaje) {
  147.  
  148. if(empty($mensaje)):
  149. die("Debes pasar como parametro el mensaje");
  150. else:
  151. $this->ch = curl_init("http://twitter.com/statuses/update.xml");
  152. $this->xml->importFromString($this->setearOpcionesCurl('status=' . urlencode($mensaje)));
  153. $this->xml->reset();
  154. endif;
  155.  
  156. return true;
  157. }
  158.  
  159. function seguidores() {
  160. $this->ch = curl_init("http://twitter.com/statuses/followers.xml");
  161. $this->xml->importFromString($this->setearOpcionesCurl());
  162. // Xpath Match
  163. $id = $this->xml->match('//id');
  164. $nickname = $this->xml->match('//screen_name');
  165. $nombre = $this->xml->match('//name');
  166. $desde = $this->xml->match('//location');
  167. $web = $this->xml->match('//url');
  168. $foto = $this->xml->match('//profile_image_url');
  169. $descripcion = $this->xml->match('//description');
  170.  
  171. // Variables Temporales
  172. $i=0;
  173. $arregloMensajes = array();
  174.  
  175. // Recorro el arreglo
  176. for($i=0;$i<count($nickname);$i++):
  177. $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]);
  178. $arregloMensajes[$i]['nombre'] = $this->xml->getData($nombre[$i]);
  179. $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]);
  180. $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]);
  181. $arregloMensajes[$i]['web'] = $this->xml->getData($web[$i]);
  182. $arregloMensajes[$i]['foto'] = $this->xml->getData($foto[$i]);
  183. $arregloMensajes[$i]['descripcion'] = $this->xml->getData($descripcion[$i]);
  184. $i++;
  185. endfor;
  186.  
  187. $this->xml->reset();
  188. return $arregloMensajes;
  189. }
  190.  
  191.  
  192. function setearOpcionesCurl($post=false) {
  193. // Autentificamos
  194. curl_setopt($this->ch, CURLOPT_USERPWD, $this->usuario.':'.$this->password);
  195.  
  196. if(!empty($post)){
  197. curl_setopt($this->ch, CURLOPT_POST, true);
  198. curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
  199. }
  200.  
  201. curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
  202. curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
  203. curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agente);
  204.  
  205. // Setamos la respuesta
  206. $respuesta = curl_exec($this->ch);
  207. curl_close($this->ch);
  208.  
  209. unset($this->ch);
  210.  
  211. return $respuesta;
  212. }
  213.  
  214. }
  215.  
  216.  
  217. ?>

En PHP twitter php componente php5 curl xpath por framirez hace on 20/2/08 | Comentarios



Clase para la manipulación de imágenes con GD

Clase realizada por Daniel Mota, http://icebeat.bitacoras.com/post/279/class-image
  1. <?php
  2.  
  3. /*
  4.  
  5. //Creamos un thumb con 200px de ancho, la altura es automatica.
  6. $thumb = new Image('directorio/imagen.jpg');
  7. $thumb->width(200);
  8. $thumb->save();
  9.  
  10. //Crear un thumb al 50%
  11. $thumb = new Image('directorio/imagen.jpg');
  12. $thumb->resize(50);
  13. $thumb->save();
  14.  
  15. //Cortar una porcion de la imegen
  16. $thumb = new Image('directorio/imagen.jpg');
  17. //indicar el punto de corte
  18. $thumb->crop(0,200);
  19. //luego puedes poner el ancho y el alto que quieras
  20. $thumb->save();
  21.  
  22. //Añadir o cambiar el nombre, no hace falta indicar la extensión
  23. $thumb = new Image('directorio/imagen.jpg');
  24. $thumb->name('imagen2'); // o tambien $thumb->name($thumb->name().'_thumb');
  25. $thumb->width(200);
  26. $thumb->save();
  27.  
  28. */
  29.  
  30. class Image {
  31.  
  32. var $file;
  33. var $image_width;
  34. var $image_height;
  35. var $width;
  36. var $height;
  37. var $ext;
  38. var $types = array('','gif','jpeg','png','swf');
  39. var $quality = 80;
  40. var $top = 0;
  41. var $left = 0;
  42. var $crop = false;
  43. var $type;
  44.  
  45. function Image($name='') {
  46. $this->file = $name;
  47. $info = getimagesize($name);
  48. $this->image_width = $info[0];
  49. $this->image_height = $info[1];
  50. $this->type = $this->types[$info[2]];
  51. $info = pathinfo($name);
  52. $this->dir = $info['dirname'];
  53. $this->name = str_replace('.'.$info['extension'], '', $info['basename']);
  54. $this->ext = $info['extension'];
  55. }
  56.  
  57. function dir($dir='') {
  58. if(!$dir) return $this->dir;
  59. $this->dir = $dir;
  60. }
  61.  
  62. function name($name='') {
  63. if(!$name) return $this->name;
  64. $this->name = $name;
  65. }
  66.  
  67. function width($width='') {
  68. $this->width = $width;
  69. }
  70.  
  71. function height($height='') {
  72. $this->height = $height;
  73. }
  74.  
  75. function resize($percentage=50) {
  76. if($this->crop) {
  77. $this->crop = false;
  78. $this->width = round($this->width*($percentage/100));
  79. $this->height = round($this->height*($percentage/100));
  80. $this->image_width = round($this->width/($percentage/100));
  81. $this->image_height = round($this->height/($percentage/100));
  82. } else {
  83. $this->width = round($this->image_width*($percentage/100));
  84. $this->height = round($this->image_height*($percentage/100));
  85. }
  86.  
  87. }
  88.  
  89. function crop($top=0, $left=0) {
  90. $this->crop = true;
  91. $this->top = $top;
  92. $this->left = $left;
  93. }
  94.  
  95. function quality($quality=80) {
  96. $this->quality = $quality;
  97. }
  98.  
  99. function show() {
  100. $this->save(true);
  101. }
  102.  
  103. function save($show=false) {
  104.  
  105. if($show) @header('Content-Type: image/'.$this->type);
  106.  
  107. if(!$this->width && !$this->height) {
  108. $this->width = $this->image_width;
  109. $this->height = $this->image_height;
  110. } elseif (is_numeric($this->width) && empty($this->height)) {
  111. $this->height = round($this->width/($this->image_width/$this->image_height));
  112. } elseif (is_numeric($this->height) && empty($this->width)) {
  113. $this->width = round($this->height/($this->image_height/$this->image_width));
  114. } else {
  115. if($this->width<=$this->height) {
  116. $height = round($this->width/($this->image_width/$this->image_height));
  117. if($height!=$this->height) {
  118. $percentage = ($this->image_height*100)/$height;
  119. $this->image_height = round($this->height*($percentage/100));
  120. }
  121. } else {
  122. $width = round($this->height/($this->image_height/$this->image_width));
  123. if($width!=$this->width) {
  124. $percentage = ($this->image_width*100)/$width;
  125. $this->image_width = round($this->width*($percentage/100));
  126. }
  127. }
  128. }
  129.  
  130. if($this->crop) {
  131. $this->image_width = $this->width;
  132. $this->image_height = $this->height;
  133. }
  134.  
  135. if($this->type=='jpeg') $image = imagecreatefromjpeg($this->file);
  136. if($this->type=='png') $image = imagecreatefrompng($this->file);
  137. if($this->type=='gif') $image = imagecreatefromgif($this->file);
  138.  
  139. $new_image = imagecreatetruecolor($this->width, $this->height);
  140. imagecopyresampled($new_image, $image, 0, 0, $this->top, $this->left, $this->width, $this->height, $this->image_width, $this->image_height);
  141.  
  142. $name = $show ? null: $this->dir.DIRECTORY_SEPARATOR.$this->name.'.'.$this->ext;
  143. if($this->type=='jpeg') imagejpeg($new_image, $name, $this->quality);
  144. if($this->type=='png') imagepng($new_image, $name);
  145. if($this->type=='gif') imagegif($new_image, $name);
  146.  
  147. imagedestroy($image);
  148. imagedestroy($new_image);
  149.  
  150. }
  151.  
  152. }
  153.  
  154. ?>
http://icebeat.bitacoras.com/descarga/class.image.phps

En PHP imagen gd por kike hace on 18/2/08 | Comentarios



Selects de fechas

Esta funcion se utiliza para generar tres selects (día, mes y año) en el cuál aparecerá seleccionada la fecha pasada por $default
  1. /**
  2. * Generar selects de fecha.
  3. *
  4. * Genera selects de fecha agrupados por el mismo nombre más su posición en la fecha hora
  5. * (Ej: $nombre = 'fecha_nacimiento' =>
  6. * <select name="fecha_nacimiento_dia">,
  7. * <select name="fecha_nacimiento_mes">,
  8. * <select name="fecha_nacimiento_ano"> )
  9. * @param texto $nombre El nombre de los selects
  10. * @param date $default La fecha que debe aparecer seleccionada
  11. * @param $atributos Un array con los atributos para cada select (pej, array('class="dia"' ,'class="mes"', 'class="año"')
  12. */
  13. function html_select_fecha($nombre, $default, $atributos=array(),$fecha_minima='2000-01-01',$fecha_maxima=false){
  14. if (ereg("[[a-z0-9_]]$",$nombre)){
  15. $start=strrpos($nombre,"[");
  16. $post=substr($nombre,$start);
  17. $nombre=substr($nombre,0,$start);
  18. }else{
  19. $post='';
  20. }
  21.  
  22. if (!$default){ $default=mktime(); }
  23.  
  24. if (!$fecha_minima){$fecha_minima='0-0-0';}
  25. if (!$fecha_maxima){$fecha_maxima='0-0-0';}
  26.  
  27. list($min_ano,$min_mes,$min_dia)=explode('-',$fecha_minima);
  28. list($max_ano,$max_mes,$max_dia)=explode('-',$fecha_maxima);
  29. if (strpos($default,'-')){
  30. if (strpos($default,' ')){
  31. list($default)=explode(' ',$default,2);
  32. }
  33. list($ano,$mes,$dia)=explode('-',$default);
  34. }else{
  35. $ano=date('Y',$default);
  36. $dia=date('j',$default);
  37. $mes=date('n',$default);
  38. }
  39. foreach(range(1,31) as $t_dia){
  40. if ($min_dia <= $t_dia && ((!$max_dia) || $max_dia >= $t_dia)){
  41. $dias[$t_dia]=str_pad($t_dia,2,'0',STR_PAD_LEFT);
  42. }
  43. }
  44. foreach(range(1,12) as $t_mes){
  45. if ($min_mes <= $t_mes && ((!$max_mes) || $max_mes >= $t_mes)){
  46. $meses[$t_mes]=ucwords(strftime("%b",mktime(1,1,1,$t_mes,1,2000)));
  47. }
  48. }
  49. foreach(range($min_ano,date('Y')+1) as $t_ano){
  50. if ($min_ano <= $t_ano && ((!$max_ano) || $max_ano >= $t_ano)){
  51. $anos[$t_ano]=$t_ano;
  52. }
  53. }
  54.  
  55. ?>
  56. <select name='<?=$nombre?>_dia<?=$post?>' <? if(isset($atributos[0])){print $atributos[0];} ?> >
  57. <? select_options($dias,$dia) ?>
  58. </select>
  59. <select name='<?=$nombre?>_mes<?=$post?>' <? if(isset($atributos[1])){print $atributos[1];} ?> >
  60. <? select_options($meses,$mes) ?>
  61. </select>
  62. <select name='<?=$nombre?>_ano<?=$post?>' <? if(isset($atributos[2])){print $atributos[2];} ?> >
  63. <? select_options($anos,$ano) ?>
  64. </select>
  65.  
  66. <?
  67.  
  68. }
Para capturar en un solo paso el POST generado por estos selects, utilizamos la siguiente función, a la que hay que pasarle: El nombre base del POST(Ej: "fecha_nacimiento"), opcionalmente el método por el que se pasó y, si es un array de POST, la clave que se quiere transformar
  1. /**
  2. * Transforma 3 variables pasadas por post a una string fecha.
  3. *
  4. * Obtiene los valores de los posts generados en la función html_select_fecha
  5. */
  6. function agrupar_fecha($nombre, $origen = "",$key=''){ //se le pasa el nombre con el que fue generado el select fecha
  7. if(!$origen)$origen=$_REQUEST;
  8. if (isset($origen[$nombre."_ano"])){
  9. if (is_array($origen[$nombre."_ano"])){
  10. $ano=$origen[$nombre."_ano"][$key];
  11. }else{
  12. $ano=$origen[$nombre."_ano"];
  13. }
  14. }else{
  15. $ano='0000';
  16. }
  17. if (isset($origen[$nombre."_mes"])){
  18. if (is_array($origen[$nombre."_mes"])){
  19. $mes=$origen[$nombre."_mes"][$key];
  20. }else{
  21. $mes=sprintf("%02d",$origen[$nombre."_mes"]);
  22. }
  23. }else{
  24. $mes='00';
  25. }
  26. if (isset($origen[$nombre."_dia"])){
  27. if (is_array($origen[$nombre."_dia"])){
  28. $dia=$origen[$nombre."_dia"][$key];
  29. }else{
  30. $dia=$origen[$nombre."_dia"];
  31. }
  32. }else{
  33. $dia='00';
  34. }
  35.  
  36. $fecha=$ano."-".$mes."-".$dia;
  37. return $fecha;
  38. }
El resultado de aplicar la funcion "agrupar_fecha" a un POST armado por "html_select_fecha" sería: 1972-05-04 (Listo para ser guardado en un campo DATE)

En PHP selects fecha html por haboc hace on 10/2/08 | Comentarios



Lista de opciones para select o list

Crea y devuelve como cadena la lista de opciones (elementos) para una lista <select> o <list> a partir de un arreglo.
  1. // string get_select_options(array $q, string $selected="", bool $nk=false)
  2. // $q Array de origen
  3. // $selected Clave del elemento seleccionado. Puede ser un arreglo.
  4. // $nk Si es true se utilizará como valor de las opciones el valor del elemento del arreglo y no las claves.
  5. function get_select_options($q,$selected="",$nk=false) {
  6. $res = "";
  7. $sarr=is_array($selected);
  8. foreach($q as $k=>$v) {
  9. $k=$nk?$v:$k;
  10. $e="";
  11. if($sarr) {
  12. $e=in_array($k,$selected)?" selected=\"selected\"":"";
  13. } else {
  14. $e=($selected==$k)?" selected=\"selected\"":"";
  15. }
  16. $res.="<option value=\"$k\"$e>$v</option> n";
  17. }
  18. return $res;
  19. }
  20.  
  21. /* Ejemplo:
  22. $elems = array(1=>"Enero",2=>"Febrero",3=>"Marzo",4=>"Abril",5=>"Mayo",6=>"Junio",7=>"Julio",8=>"Agosto",9=>"Septiembre",10=>"Octubre",11=>"Noviembre",12=>"Diciembre");
  23. $options = get_select_options($elems);
  24. echo "Mes de cumpleaños: <select name=\"mes\">$options</select>";
  25.  
  26. Otro ejemplo:
  27. $elems = array();
  28. $dia = 5;
  29. for($i=1;$i<=31;$i++) $elems[]=$i;
  30. $options = get_select_options($elems,$dia,true);
  31. echo "Dia de cumpleaños: <select name=\"dia\">$options</select>";
  32. */
  33.  
  34. // http://www.cqsoft.com.ar

En PHP select list option lista opciones array arreglo por geq hace on 8/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