Nueve técnicas de sustitución de imágenes con CSS

1 COMENTARIO -  Publicado hace 1 mes -  Clasificado en: ,

La sustitución de imágenes mediante CSS es, a grandes rasgos, una técnica de sustitución de un elemento de terxto de una pagina por una imagen. Quizá uno de los ejemplos más clarificadores sería a la hora de incluir el logo en una web. Es posible que desees utilizar una etiqueta <h1> y texto por accesibilidad y los beneficios en cuanto a SEO, pero a la vez, y por razones estéticas, te gustaría mostrar tu logo y no el texto.

Un ejemplo:

<h1 id="logo">
	<span>Intenta
</h1>

y el css:

h1#logo {
        width: 250px;
        height: 25px;
        background-image: url(logo.gif);
}
h1#logo span {
        display: none;
}

En CSS-Tricks puedes encontrar el análisis de nueve de estas técnicas, cómo se realizan y las ventajas y desventajas de cada una.

Nine Techniques for CSS Image Replacement » »

Algunas entradas relacionadas:

 

Poner un límite de tiempo a los scripts en PHP

1 COMENTARIO -  Publicado hace 6 meses -  Clasificado en: , ,

La función set_time_limit puede resultar de gran utilidad para evitar bucles infinitos y conexiones muy prolongadas con la base de datos. set_time_limit pone un límite de tiempo en el máximo número de segundos que un script puede tardar en ejecutarse. Después de ese período de tiempo, un error fatal es lanzado. El límite predeterminado es 30 segundos o, si existe, el valor max_execution_time definido en php.ini. Si el límite en segundos se establece a cero, no se impone límite alguno.

Cuando es llamada, la función set_time_limit() restablece el contador de tiempo de espera desde cero.

Ejemplo:

<?php
set_time_limit(2);
?>

Si estamos usando Apache, también podemos cambiar el tiempo máximo de ejecución con .htaccesss añadiendo una línea similar a ésta:

php_value max_execution_time 200

Para averiguar el tiempo límite fijado puedes utilizar:

<?php
echo ini_get('max_execution_time');
?>

Algunas entradas relacionadas:

 

htaccess: configurar una imagen por defecto

0 COMENTARIOS -  Publicado hace 6 meses -  Clasificado en: ,

El siguiente código redirecciona a una imagen por defecto a cualquier archivo de imagen que no pueda ser encontrado en el servidor.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/.*\.jpg$ /images/default.jpg [L]

Se puede cambiar la extensión ".jpg" por cualquier otra que se este usando.

Visto en 10+ Mod_Rewrite Rules You Should Know » »

Algunas entradas relacionadas:

 

Convertir las URL en hipervínculos

0 COMENTARIOS -  Publicado hace 6 meses -  Clasificado en: , ,

Esta función convierte las URL y direcciones de correo electrónico dentro de una cadena en hpervículos "clikables".

<?php
function CrearLinks($texto) {
	$texto = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $texto);
	$texto = ' ' . $texto;
	$texto = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $texto);
	$texto = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $texto);
	$texto = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $texto);
	$texto = substr($texto, 1);
	return $texto;
}


$cadena ="Lorem ipsum www.google.es. Qui, webintenta@gmail.com repren.";

echo CrearLinks($cadena);
?>

Visto en How To Make Clickable Text URL Links From Text Links Change To Clicking » »

Algunas entradas relacionadas:

 

Cómo mostrar los comentarios más recientes en WordPress

1 COMENTARIO -  Publicado hace 6 meses -  Clasificado en: , ,

Simplemente se ha de pegar el siguiente código en la parte de tu tema donde los quieras mostrar. El ejemplo muestra los últimos 10 comentarios. Para variar este valor tan sólo deberemos modificarlo en: "...ORDER BY comment_date_gmt DESC LIMIT 10".

<?php
  global $wpdb;
  $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";

  $comments = $wpdb->get_results($sql);
  $output = $pre_HTML;
  $output .= "\n<ul>";
  foreach ($comments as $comment) {
    $output .= "\n<li>".strip_tags($comment->comment_author) .":" . "<a href=\"" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "\" title=\"on ".$comment->post_title . "\">" . strip_tags($comment->com_excerpt)."</a></li>";
  }
  $output .= "\n</ul>";
  $output .= $post_HTML;
  echo $output;
?>

Visto en WP Recipes » »

 

Clase para acceder a Google Weather

1 COMENTARIO -  Publicado hace 6 meses -  Clasificado en: , , , ,

Interesante clase para acceder de un modo sencillo al servicio metereológico de Google.

Ejemplo:

<?php
class GoogleWeatherAPI {
	private $city_code = '';
	private $city = '';
	private $domain = 'www.google.com';
	private $prefix_images = '';
	private $current_conditions = array();
	private $forecast_conditions = array();
	private $is_found = true;

	/**
	* Class constructor
	* @param $city_code is the label of the city
	* @param $lang the lang of the return weather labels
	* @return ...
	*/
	 
	function __construct ($city_code,$lang='fr') {
		$this->city_code = $city_code;
		$this->prefix_images = 'http://'.$this->domain;
		$this->url = 'http://'.$this->domain.'/ig/api?weather='.urlencode($this->city_code).'&hl='.$lang;
		
		$content = utf8_encode(file_get_contents($this->url));
		
		$xml = simplexml_load_string($content);
		
		if(!isset($xml->weather->problem_cause)) {
			
			$xml = simplexml_load_string($content);

			$this->city = (string)$xml->weather->forecast_information->city->attributes()->data;

			$this->current_conditions['condition'] = (string)$xml->weather->current_conditions->condition->attributes()->data;
			$this->current_conditions['temp_f'] = (string)$xml->weather->current_conditions->temp_f->attributes()->data;
			$this->current_conditions['temp_c'] = (string)$xml->weather->current_conditions->temp_c->attributes()->data;
			$this->current_conditions['humidity'] = (string)$xml->weather->current_conditions->humidity->attributes()->data;
			$this->current_conditions['icon'] = $this->prefix_images.(string)$xml->weather->current_conditions->icon->attributes()->data;
			$this->current_conditions['wind_condition'] = (string)$xml->weather->current_conditions->wind_condition->attributes()->data;
			
			foreach($xml->weather->forecast_conditions as $this->forecast_conditions_value) {
				$this->forecast_conditions_temp = array();
				$this->forecast_conditions_temp['day_of_week'] = (string)$this->forecast_conditions_value->day_of_week->attributes()->data;
				$this->forecast_conditions_temp['low'] = (string)$this->forecast_conditions_value->low->attributes()->data;
				$this->forecast_conditions_temp['high'] = (string)$this->forecast_conditions_value->high->attributes()->data;
				$this->forecast_conditions_temp['icon'] = $this->prefix_images.(string)$this->forecast_conditions_value->icon->attributes()->data;
				$this->forecast_conditions_temp['condition'] = (string)$this->forecast_conditions_value->condition->attributes()->data;
				$this->forecast_conditions []= $this->forecast_conditions_temp;
			}
		} else {
			$this->is_found = false;
		}
	}
	function getCity() {
		return $this->city;
	}
	function getCurrent() {
		return $this->current_conditions;
	}
	function getForecast() {
		return $this->forecast_conditions;
	}
	function isFound() {
		return $this->is_found;
	}
	
}
$gweather = new GoogleWeatherAPI('valencia','es'); 
if($gweather->isFound()) {
	echo '<pre>'; print_r($gweather->getCity()); echo '</pre>';
	echo '<pre>'; print_r($gweather->getCurrent()); echo '</pre>';
	echo '<pre>'; print_r($gweather->getForecast()); echo '</pre>';
}
?>

Ver ejemplo en funcionamiento » »

Google Weather API » »

Algunas entradas relacionadas:

 

Usar PHP para comprimir ficheros CSS

0 COMENTARIOS -  Publicado hace 9 meses -  Clasificado en: , ,

Existen varias técnicas que usan PHP para optimizar los ficheros CSS y reducir el número de peticiones HTTP en el caso de que dispongamos de varios. La siguiente técnica es una variación de la de Reinhold Weber. Los CSS son incluidos pero no son eliminados los espacios en blancos, lo que facilita la depuración y el acceso al contenido mediante herramientas como Firebug.

<?php
if(extension_loaded('zlib')){
   ob_start('ob_gzhandler');
}
header ("content-type: text/css; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60;
$expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
header ($expire);
ob_start("compress");
function compress($buffer) {
   // remove comments 
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  return $buffer;
}
 // list CSS files to be included
include('baseline.css');
include('styles.css');

if(extension_loaded('zlib')){
ob_end_flush();
}
?>

Vía ethanandjamie.com » »

Algunas entradas relacionadas:

 
Páginas: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Siguiente >