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 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.
  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. ob_start( 'ob_gzhandler' );
  3. echo join('',file($_GET['file']));
  4. ?>
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

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