Ú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
<?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 3 semanas | 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.
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
Si no tenemos acceso al servidor para activar el mod_deflate de php, podemos comprimir javascript desde php con gzip
js.php
y pasamos el nombre del js por $_GET:
<?php ?>
Asi por ejemplo dejamos la libreria jquery sobre 15-16kb
<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
// 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
<?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
Clase realizada por Daniel Mota, http://icebeat.bitacoras.com/post/279/class-image
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