Últimos snippets en PHP
Geolocalización en PHP5 usando GeoIP de Maxmind
<?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
Visto en http://icebeat.bitacoras.com/post/283/evitar-el-cache-de-los-css-y-js
function version($file) { } <link href="<?php echo version('css.css'); ?>" rel="stylesheet" type="text/css" />
En PHP css javascript cache por alberto hace on 29/3/08 | Comentarios
Comprimir Javascript desde PHP sin mod_deflate
y pasamos el nombre del js por $_GET:
<?php $file = $_GET['file']; { } ?>
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
<script type="text/javascript" src="js.php?file=js/jquery.js"> </script>
En PHP compresion gzip mod_deflate javascript por ZiTAL hace on 27/2/08 | Comentarios
Twitter API PHP
<?php /* Ejemplo de instancia */ require_once('class/twitter.class.php'); /* Metodo Constructor para Twitter */ $twitter = new Twitter('miusuario','mipass'); // Ejemplo :) echo "<h1>Todos los mensajes de Fayerwayer</h1>"; echo "<pre>"; echo "</pre>"; // Quieres realmente postear este mensaje? Descomentalo //$twitter->postearMensaje('Mi mensaje de pruebas desde API PHP para Twitter por framirez'); // Todos mis seguidores echo "<h1>Todos mis seguidores</h1>"; echo "<pre>"; echo "</pre>"; // Ahora quiero ver todos mis mensajes echo "<h1>Todos mis mensajes</h1>"; echo "<pre>"; foreach($twitter->lineaTiempo() as $mensajes): echo "<p>Mensaje: " . $mensajes['mensaje'] . " posteado a las " . $mensajes['hora'] . " desde " . $mensajes['desde'] ."</p>"; endforeach; echo "</pre>"; <?php /* @author: Fabian Ramirez Sepulveda @email : framirez(ARROB)gurunet.cl @web : http://www.gurunet.cl/framirez @desc: Proyecto para tener una API desde PHP mas accesible y facil para usuarios no avanzados. @metodos: lineaTiempo( $nickNameAmigo=opcional) - "Nos retorna todos los ultimos 10 mensajes que nuestro amigo o nosotros hemos posteado" tomarMensaje($idmensaje) - "Nos retorna el detalle completo del mensaje" postearMensaje($mensaje) - "Posteamos en tiempo real el mensaje desde PHP" seguidores() - "Nos retorna todos nuestros amigos que nos siguen" */ // Libreria necesaria para procesar Xpath require_once('XPath.class.php'); class Twitter { var $usuario=''; var $password=''; // Headers de nuestro cliente var $agente = 'Twitter PHP Class by framirez'; 'X-Twitter-Client-Version: 1.0', 'X-Twitter-Client-URL: http://www.gurunet.cl/framirez'); // Curl var $ch; // Respuesta var $respuesta; var $xml; function Twitter($usuario=null, $password=null) { $this->usuario = $usuario; $this->password = $password; // Metodo constructor automaticamente llama a Xpath $this->xml = new XPath(); } /* @desc: Retornamos el maximo de 10 mensajes de amigos o mios */ function lineaTiempo($nick = null) { $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml"); $this->xml->importFromString($this->setearOpcionesCurl()); else: $this->ch = curl_init("http://twitter.com/statuses/user_timeline/" . $nick . ".xml"); $this->xml->importFromString($this->setearOpcionesCurl()); endif; // Xpath Match $id = $this->xml->match('//id'); $nickname = $this->xml->match('//screen_name'); $texto = $this->xml->match('//text'); $hora = $this->xml->match('//created_at'); $desde = $this->xml->match('//location'); $deDonde = $this->xml->match('//source'); // Variables Temporales $i=0; // Recorro el arreglo for($i=0;$i<count($texto);$i++): $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]); $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]); $arregloMensajes[$i]['mensaje'] = $this->xml->getData($texto[$i]); $arregloMensajes[$i]['hora'] = $this->xml->getData($hora[$i]); $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]); $arregloMensajes[$i]['donde_proviene'] = $this->xml->getData($deDonde[$i]); $i++; endfor; $this->xml->reset(); return $arregloMensajes; } function tomarMensaje($id) { $this->ch = curl_init("http://twitter.com/statuses/user_timeline.xml"); $this->xml->importFromString($this->setearOpcionesCurl()); // Xpath Match $id = $this->xml->match('//id'); $nickname = $this->xml->match('//screen_name'); $texto = $this->xml->match('//text'); $hora = $this->xml->match('//created_at'); $desde = $this->xml->match('//location'); $deDonde = $this->xml->match('//source'); // Variables Temporales // Recorro el arreglo $arregloMensajes['id'] = $this->xml->getData($id[0]); $arregloMensajes['usuario'] = $this->xml->getData($nickname[0]); $arregloMensajes['mensaje'] = $this->xml->getData($texto[0]); $arregloMensajes['hora'] = $this->xml->getData($hora[0]); $arregloMensajes['desde'] = $this->xml->getData($desde[0]); $arregloMensajes['donde_proviene'] = $this->xml->getData($deDonde[0]); $this->xml->reset(); return $arregloMensajes; } function postearMensaje($mensaje) { else: $this->ch = curl_init("http://twitter.com/statuses/update.xml"); $this->xml->reset(); endif; return true; } function seguidores() { $this->ch = curl_init("http://twitter.com/statuses/followers.xml"); $this->xml->importFromString($this->setearOpcionesCurl()); // Xpath Match $id = $this->xml->match('//id'); $nickname = $this->xml->match('//screen_name'); $nombre = $this->xml->match('//name'); $desde = $this->xml->match('//location'); $web = $this->xml->match('//url'); $foto = $this->xml->match('//profile_image_url'); $descripcion = $this->xml->match('//description'); // Variables Temporales $i=0; // Recorro el arreglo for($i=0;$i<count($nickname);$i++): $arregloMensajes[$i]['id'] = $this->xml->getData($id[$i]); $arregloMensajes[$i]['nombre'] = $this->xml->getData($nombre[$i]); $arregloMensajes[$i]['desde'] = $this->xml->getData($desde[$i]); $arregloMensajes[$i]['usuario'] = $this->xml->getData($nickname[$i]); $arregloMensajes[$i]['web'] = $this->xml->getData($web[$i]); $arregloMensajes[$i]['foto'] = $this->xml->getData($foto[$i]); $arregloMensajes[$i]['descripcion'] = $this->xml->getData($descripcion[$i]); $i++; endfor; $this->xml->reset(); return $arregloMensajes; } function setearOpcionesCurl($post=false) { // Autentificamos curl_setopt($this->ch, CURLOPT_USERPWD, $this->usuario.':'.$this->password); curl_setopt($this->ch, CURLOPT_POST, true); curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post); } curl_setopt($this->ch, CURLOPT_VERBOSE, 1); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agente); // Setamos la respuesta $respuesta = curl_exec($this->ch); curl_close($this->ch); return $respuesta; } } ?>
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
http://icebeat.bitacoras.com/descarga/class.image.phps
<?php /* //Creamos un thumb con 200px de ancho, la altura es automatica. $thumb = new Image('directorio/imagen.jpg'); $thumb->width(200); $thumb->save(); //Crear un thumb al 50% $thumb = new Image('directorio/imagen.jpg'); $thumb->resize(50); $thumb->save(); //Cortar una porcion de la imegen $thumb = new Image('directorio/imagen.jpg'); //indicar el punto de corte $thumb->crop(0,200); //luego puedes poner el ancho y el alto que quieras $thumb->save(); //Añadir o cambiar el nombre, no hace falta indicar la extensión $thumb = new Image('directorio/imagen.jpg'); $thumb->name('imagen2'); // o tambien $thumb->name($thumb->name().'_thumb'); $thumb->width(200); $thumb->save(); */ class Image { var $file; var $image_width; var $image_height; var $width; var $height; var $ext; var $quality = 80; var $top = 0; var $left = 0; var $crop = false; var $type; function Image($name='') { $this->file = $name; $this->image_width = $info[0]; $this->image_height = $info[1]; $this->type = $this->types[$info[2]]; $this->dir = $info['dirname']; $this->ext = $info['extension']; } if(!$dir) return $this->dir; $this->dir = $dir; } function name($name='') { if(!$name) return $this->name; $this->name = $name; } function width($width='') { $this->width = $width; } function height($height='') { $this->height = $height; } function resize($percentage=50) { if($this->crop) { $this->crop = false; } else { } } function crop($top=0, $left=0) { $this->crop = true; $this->top = $top; $this->left = $left; } function quality($quality=80) { $this->quality = $quality; } function show() { $this->save(true); } function save($show=false) { if(!$this->width && !$this->height) { $this->width = $this->image_width; $this->height = $this->image_height; } else { if($this->width<=$this->height) { if($height!=$this->height) { $percentage = ($this->image_height*100)/$height; } } else { if($width!=$this->width) { $percentage = ($this->image_width*100)/$width; } } } if($this->crop) { $this->image_width = $this->width; $this->image_height = $this->height; } if($this->type=='jpeg') $image = imagecreatefromjpeg($this->file); if($this->type=='png') $image = imagecreatefrompng($this->file); if($this->type=='gif') $image = imagecreatefromgif($this->file); $new_image = imagecreatetruecolor($this->width, $this->height); imagecopyresampled($new_image, $image, 0, 0, $this->top, $this->left, $this->width, $this->height, $this->image_width, $this->image_height); $name = $show ? null: $this->dir.DIRECTORY_SEPARATOR.$this->name.'.'.$this->ext; if($this->type=='jpeg') imagejpeg($new_image, $name, $this->quality); if($this->type=='png') imagepng($new_image, $name); if($this->type=='gif') imagegif($new_image, $name); imagedestroy($image); imagedestroy($new_image); } } ?>
En PHP imagen gd por kike hace on 18/2/08 | Comentarios
Selects de fechas
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
/** * Generar selects de fecha. * * Genera selects de fecha agrupados por el mismo nombre más su posición en la fecha hora * (Ej: $nombre = 'fecha_nacimiento' => * <select name="fecha_nacimiento_dia">, * <select name="fecha_nacimiento_mes">, * <select name="fecha_nacimiento_ano"> ) * @param texto $nombre El nombre de los selects * @param date $default La fecha que debe aparecer seleccionada * @param $atributos Un array con los atributos para cada select (pej, array('class="dia"' ,'class="mes"', 'class="año"') */ function html_select_fecha($nombre, $default, $atributos=array(),$fecha_minima='2000-01-01',$fecha_maxima=false){ }else{ $post=''; } if (!$fecha_minima){$fecha_minima='0-0-0';} if (!$fecha_maxima){$fecha_maxima='0-0-0';} } }else{ } if ($min_dia <= $t_dia && ((!$max_dia) || $max_dia >= $t_dia)){ } } if ($min_mes <= $t_mes && ((!$max_mes) || $max_mes >= $t_mes)){ } } if ($min_ano <= $t_ano && ((!$max_ano) || $max_ano >= $t_ano)){ $anos[$t_ano]=$t_ano; } } ?> <? select_options($dias,$dia) ?> </select> <? select_options($meses,$mes) ?> </select> <? select_options($anos,$ano) ?> </select> <? }
El resultado de aplicar la funcion "agrupar_fecha" a un POST armado por
/** * Transforma 3 variables pasadas por post a una string fecha. * * Obtiene los valores de los posts generados en la función html_select_fecha */ function agrupar_fecha($nombre, $origen = "",$key=''){ //se le pasa el nombre con el que fue generado el select fecha if(!$origen)$origen=$_REQUEST; $ano=$origen[$nombre."_ano"][$key]; }else{ $ano=$origen[$nombre."_ano"]; } }else{ $ano='0000'; } $mes=$origen[$nombre."_mes"][$key]; }else{ } }else{ $mes='00'; } $dia=$origen[$nombre."_dia"][$key]; }else{ $dia=$origen[$nombre."_dia"]; } }else{ $dia='00'; } $fecha=$ano."-".$mes."-".$dia; return $fecha; }
En PHP selects fecha html por haboc hace on 10/2/08 | Comentarios
Lista de opciones para select o list
// string get_select_options(array $q, string $selected="", bool $nk=false) // $q Array de origen // $selected Clave del elemento seleccionado. Puede ser un arreglo. // $nk Si es true se utilizará como valor de las opciones el valor del elemento del arreglo y no las claves. function get_select_options($q,$selected="",$nk=false) { $res = ""; foreach($q as $k=>$v) { $k=$nk?$v:$k; $e=""; if($sarr) { } else { $e=($selected==$k)?" selected=\"selected\"":""; } $res.="<option value=\"$k\"$e>$v</option> n"; } return $res; } /* Ejemplo: $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"); $options = get_select_options($elems); echo "Mes de cumpleaños: <select name=\"mes\">$options</select>"; Otro ejemplo: $elems = array(); $dia = 5; for($i=1;$i<=31;$i++) $elems[]=$i; $options = get_select_options($elems,$dia,true); echo "Dia de cumpleaños: <select name=\"dia\">$options</select>"; */ // 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
function getDistance($lat1, $long1, $lat2, $long2) { $earth = 6371; //km //$earth = 3960; //millas //Punto 1 coordenadas //Punto 2 coordenadas $dlong=$long2-$long1; $dlat=$lat2-$lat1; $d=($earth*$c); return $d; }
En PHP calcular distancias coordenadas google maps por javito hace on 5/2/08 | Comentarios
Comprobación de página inexistente
/** * function valida_enlace (string $url, boolean $formato = true) * * Comprueba si un enlace no devuelve un 404 * * return boolean */ function valida_enlace ($url, $formato = true) { $head = getHeaders($url, $formato); }
En PHP 404 página inexistente por Lito hace on 4/2/08 | Comentarios
Obtener encabezados de una dirección web
/** * function getHeaders (string $url, boolean $formato = true) * * Devuelve las cabeceras de una dirección web * Solo acepta HTTP como metodo * * Si $formato es true devuelve un array asociativo, * de lo contrario, un array de claves simples * * return array */ function getHeaders ($url, $formato = true) { return @get_headers($url, $formato); } return false; } $path = '/'; } else { $path = $partes['path']; } $path .= '?'.$partes['query']; } if (!$socket) { return false; } $header = 'HEAD '.$path.' HTTP/1.1'."\r\n" .'Connection: Close'."\r\n\r\n"; $fin = false; if ($header == "\r\n") { $fin = true; break; } else { } if ($formato == 1) { if ($key == $header) { $datos[] = $header; } else { } } else { $datos[] = $header; } } } return $datos; }
En PHP encabezados cabeceras url por Lito hace on 4/2/08 | Comentarios
