Entradas con la etiqueta ‘php’

Poner contrabarras en string con comillas

Jueves, 3 de Marzo de 2011

esta es la función

addslashes

Poner ceros a la izquierda de un número

Miércoles, 2 de Marzo de 2011

function number_pad($number,$n) {

return str_pad((int) $number,$n,”0″,STR_PAD_LEFT);
}

//$number es el numero a modificar
// y $n sol los dígitos que se quiere contemplar, no los ceros a poner, en mi caso es $n=2

Generar archivo csv con php

Martes, 25 de Enero de 2011

Ponemos el código para generar csv desde php, y guardarlo

<?php
include(“connect.php”); // Conexion a nuestra BD
$csv_end = ”
“;
$csv_sep = “|”;
$csv_file = “datas.csv”;
$csv=“”;
$sql=“SELECT * from table”;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$csv.=$row['field_1'].$csv_sep.$row['field_2'].$csv_end;
}
//Generamos el csv de todos los datos
if (!$handle = fopen($csv_file, “w”)) {
echo “Cannot open file”;
exit;
}
if (fwrite($handle, utf8_decode($csv)) === FALSE) {
echo “Cannot write to file”;
exit;
}
fclose($handle);
?>

ejemplos de preg_match_all php

Martes, 12 de Octubre de 2010
/ retrieve doctype of document

function get_doctype($file){
$h1tags = preg_match(‘/<!DOCTYPE (\w.*)dtd”>/is’,$file,$patterns);
$res = array();
array_push($res,$patterns[0]);
array_push($res,count($patterns[0]));
return
$res;
}

// retrieve page title
function get_doc_title($file){
$h1tags = preg_match(‘/<title> ?.* <\/title>/isx’,$file,$patterns);
$res = array();
array_push($res,$patterns[0]);
array_push($res,count($patterns[0]));
return
$res;
}

// retrieve keywords
function get_keywords($file){
$h1tags = preg_match(‘/(<meta name=”keywords” content=”(.*)” \/>)/i’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// get rel links in header of the site
function get_link_rel($file){
$h1tags = preg_match_all(‘/(rel=)(”.*”) href=(”.*”)/im’,$file,$patterns);
$res = array();
array_push($res,$patterns);
array_push($res,count($patterns[2]));
return
$res;
}

function get_external_css($file){
$h1tags = preg_match_all(‘/(href=”)(\w.*\.css)”/i’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h1 tags
function get_h1($file){
$h1tags = preg_match_all(“/(<h1.*>)(\w.*)(<\/h1>)/isxmU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h2 tags
function get_h2($file){
$h1tags = preg_match_all(“/(<h2.*>)(\w.*)(<\/h2>)/isxmU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h3 tags
function get_h3($file){
$h1tags = preg_match_all(“/(<h3.*>)(\w.*)(<\/h3>)/ismU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h4 tags
function get_h4($file){
$h1tags = preg_match_all(“/(<h4.*>)(\w.*)(<\/h4>)/ismU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h5 tags
function get_h5($file){
$h1tags = preg_match_all(“/(<h5.*>)(\w.*)(<\/h5>)/ismU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all h5 tags
function get_h6($file){
$h1tags = preg_match_all(“/(<h6.*>)(\w.*)(<\/h6>)/ismU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve p tag contents
function get_p($file){
$h1tags = preg_match_all(“/(<p.*>)(\w.*)(<\/p>)/ismU”,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve names of links
function get_a_content($file){
$h1count = preg_match_all(“/(<a.*>)(\w.*)(<.*>)/ismU”,$file,$patterns);
return
$patterns[2];
}

// retrieve link destinations
function get_a_href($file){
$h1count = preg_match_all(‘/(href=”)(.*?)(”)/i’,$file,$patterns);
return
$patterns[2];
}

// get count of href’s
function get_a_href_count($file){
$h1count = preg_match_all(‘/<(a.*) href=\”(.*?)\”(.*)<\/a>/’,$file,$patterns);
return
count($patterns[0]);
}

//get all additional tags inside a link tag
function get_a_additionaltags($file){
$h1count = preg_match_all(‘/<(a.*) href=”(.*?)”(.*)>(.*)(<\/a>)/’,$file,$patterns);
return
$patterns[3];
}

// retrieve span’s
function get_span($file){
$h1count = preg_match_all(‘/(<span .*>)(.*)(<\/span>)/’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve spans on the site
function get_script($file){
$h1count = preg_match_all(‘/(<script.*>)(.*)(<\/script>)/imxsU’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve content of ul’s
function get_ul($file){
$h1count = preg_match_all(‘/(<ul \w*>)(.*)(<\/ul>)/ismxU’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

//retrieve li contents
function get_li($file){
$h1count = preg_match_all(‘/(<li \w*>)(.*)(<\/li>)/ismxU’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve page comments
function get_comments($file){
$h1count = preg_match_all(‘/(<!–).(.*)(–>)/isU’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all used id’s on the page
function get_ids($file){
$h1count = preg_match_all(‘/(id=”(\w*)”)/is’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve all used classes ( inline ) of the document
function get_classes($file){
$h1count = preg_match_all(‘/(class=”(\w*)”)/is’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// get the meta tag contents
function get_meta_content($file){
$h1count = preg_match_all(‘/(<meta)(.*=”(.*)”).\/>/ix’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// get inline styles
function get_styles($file){
$h1count = preg_match_all(‘/(style=”)(.*?)(”)/is’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// get titles of tags
function get_tag_titles($file){
$h1count = preg_match_all(‘/(title=)”(.*)”(.*)/’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// get image alt descriptions
function get_image_alt($file){
$h1count = preg_match_all(‘/(alt=.)([a-zA-Z0-9\s]{1,})/’,$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return
$res;
}

// retrieve images on the site
function get_images($file){
$h1count = preg_match_all(‘/(<img)\s (src=”([a-zA-Z0-9\.;:\/\?&=_|\r|\n]{1,})”)/isxmU’,$file,$patterns);
$res = array();
array_push($res,$patterns[3]);
array_push($res,count($patterns[3]));
return
$res;
}

// retrieve email address of the mailto tag if any
function get_mailto($file){
$h1count = preg_match_all(‘/(<a\shref=”)(mailto:)([a-zA-Z@0-9\.]{1,})”/ims’,$file,$patterns);
$res = array();
array_push($res,$patterns[3]);
array_push($res,count($patterns[3]));
return
$res;
}

// retrieve any email
function get_emails($file){
$h1count = preg_match_all(‘/[a-zA-Z0-9_-]{1,}@[a-zA-Z0-9-_]{1,}\.[a-zA-Z]{1,4}/’,$file,$patterns);
$res = array();
array_push($res,$patterns[0]);
array_push($res,count($patterns[0]));
return
$res;
}

// count used keywords
function countkeyword($word,$file){
$x = preg_match_all(“/(.*)($word)(.*)/”,$file,$patterns);
return
count($patterns);
}

// retrieve internal site links
function get_internal_links($array){
$result = array();
$count = count($array);
for(
$i=0;$i<$count;$i++){
if(!empty(
$array[$i])){
if(
strpos($array[$i],“www”,0) === false){
if(
strpos($array[$i],“http”,0) === false){
array_push($result,$array[$i]);
}
}
}
}
return
$result;
}

// retrieve external links
function get_external_links($array){
$result = array();
$count = count($array);
for(
$i=0;$i<$count;$i++){
if(!empty(
$array[$i])){
if(
strpos($array[$i],“www”,0) !== false){
if(
strpos($array[$i],“http”,0) !== false){
array_push($result,$array[$i]);
}
}
}
}
return
$result;
}

// retrieve the main url of the site
function get_main_url($url){
$parts = parse_url($url);
$url = $parts["scheme"] .“://”.$parts["host"];
return
$url;
}

// retrieve just the name without www and com/eu/de etc
function get_domain_name_only($url){
$match = preg_match(“/(.*:\/\/)\w{0,}(.*)\.(.*)/”,$url,$patterns);
$patterns[2] = str_replace(“.”,“”,$patterns[2]);
return
$patterns[2];
}
?>

Usage Example

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
<style type=”text/css”>
<!–
body {
font: 11px Arial, Helvetica, sans-serif;
}
.info {
color: #99CC00;
font-weight: bold;
}
.notice {
color: #FF66CC;
}
.error {
color: #990000;
font-weight: bold;
}
–>
</style>
</head>

<body><form action=”" method=”post” enctype=”application/x-www-form-urlencoded” name=”form1″>
<input name=”url” type=”text” /><input name=”submit” type=”submit” value=”submit” /></form>

<?php if(isset($_POST['submit']) && $_POST['submit'] == “submit”){
$resultArray = array();
$url = htmlentities(strip_tags($_POST['url']));
include(
“tagretrieval.php”);

if(strpos($url,“http”,0) === false){
$url = “http://$url”;
}

echo “<img src=\”http://www.artviper.net/screenshots/screener.php?url=$url&amp;h=180&amp;w=240&amp;sdx=1024&amp;sdy=768\” alt=\”$url\” style=\”margin:20px\” />”;

$file = file_get_contents($url);
$doctype = get_doctype($file);
$keywords = get_keywords($file);
$css = get_external_css($file);
$h1 = get_h1($file);
$h2 = get_h2($file);
$h3 = get_h3($file);
$p = get_p($file);
$title = get_doc_title($file);
$links = get_a_href($file);
$href_add = get_a_additionaltags($file);
$images = get_images($file);
$styles = get_styles($file);
$ids = get_ids($file);
$classes = get_classes($file);

echo“<h1>Document properties</h1>”;
// get doctype
if(!empty($doctype[0])){
$doctype = preg_replace(“/</”,‘&lt;’,$doctype[0]);
echo
“<br/>Valid doctype: $doctype”;
}else{
$doctype = “<br/>No doctype specified<br/>”;
echo
$doctype;
}

// get doc title
if(!empty($title[0])){
$title[0] = preg_replace(“/</”,“&lt;”,$title[0]);
echo
“<br/>Title found: $title[0]<”;
}else{
echo
“<br/><div class=\”error\”>Page does not have a title</div><br/>”;
}

// get external references CSS files
// get h1 tags
if($css[1] != 0){
echo
“<br/>external CSS found: $css[1]<ul>”;
foreach(
$css[0] as $key => $val){
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No external CSS found</div><br/>”;
}

// get keywords
if(!empty($keywords[0])){
echo
“<br/>Keywords found: $keywords[0]“;
}else{
echo
“<br/><div class=\”error\”>No keywords specified</div><br/>”;
}

echo“<h1>Content properties</h1>”;
// get h1 tags
if($h1[1] != 0){
echo
“<br/>H1 Tags found: $h1[1]<ul>”;
foreach(
$h1[0] as $key => $val){
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No H1 Tags found</div><br/>”;
}
// get h2 tags
if($h2[1] != 0){
echo
“<br/>H2 Tags found: $h2[1]<ul>”;
foreach(
$h2[0] as $key => $val){
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No H2 Tags found</div><br/>”;
}

// get h3 tags
if($h3[1] != 0){
echo
“<br/>H3 Tags found: $h3[1]<ul>”;
foreach(
$h3[0] as $key => $val){
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No H3 Tags found</div><br/>”;
}
// get p tags
if($p[1] != 0){
echo
“<br/>p Tags found: $p[1]<ul>”;
foreach(
$p[0] as $key => $val){
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No p Tags found</div><br/>”;
}

echo “<h1>Link structure</h1>”;

if(!empty($links[0])){
echo
“<br/>Links found:<ul>”;
foreach(
$links as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No Links found</div><br/>”;
}

if(!empty($href_add[0])){
echo
“<br/>href additional tags:<ul>”;
foreach(
$href_add as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/><div class=\”error\”>No additional styles for href found</div><br/>”;
}

echo “<h1>Images</h1>”;

if(!empty($images[0])){
echo
“<br/>images:<ul>”;
foreach(
$images[0] as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/>No images found”;
}

echo “<h1>Styles, ID’s &amp; Classes</h1>”;

if(!empty($ids[0])){
echo
“<br/>ID’s:<ul>”;
foreach(
$ids[0] as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/>No ID’s found<br/>”;
}

if(!empty($classes[0])){
echo
“<br/>classes:<ul>”;
foreach(
$classes[0] as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“</ul>”;
}else{
echo
“<br/>No classes found<br/>”;
}

if(!empty($styles[0])){
echo
“<br/>inline styles:<ul>”;
foreach(
$styles[0] as $key => $val){
$val = preg_replace(“/</”,“&lt;”,$val);
echo
“<li>” . htmlentities($val) . “</li>”;
}
echo
“<div class=\”notice\”>Your document uses inline styles. If applicable, try to put them into a separate CSS file and restyle them to ID’s or CLASSES.</div></ul>”;
}else{
echo
“<br/>No inline styles used”;
}
}
?>
</body>
</html>

Headers php

Viernes, 17 de Septiembre de 2010

// See related links for more status codes

// Use this header instruction to fix 404 headers

// produced by url rewriting…

header(’HTTP/1.1 200 OK’);

// Page was not found:

header(’HTTP/1.1 404 Not Found’);

// Access forbidden:

header(’HTTP/1.1 403 Forbidden’);

// The page moved permanently should be used for

// all redrictions, because search engines know

// what’s going on and can easily update their urls.

header(’HTTP/1.1 301 Moved Permanently’);

// Server error

header(’HTTP/1.1 500 Internal Server Error’);

// Redirect to a new location:

header(’Location: http://www.example.org/’);

// Redriect with a delay:

header(’Refresh: 10; url=http://www.example.org/’);

print ‘You will be redirected in 10 seconds’;

// you can also use the HTML syntax:

// <meta http-equiv=”refresh” content=”10;http://www.example.org/ />

// override X-Powered-By value

header(’X-Powered-By: PHP/4.4.0′);

header(’X-Powered-By: Brain/0.6b’);

// content language (en = English)

header(’Content-language: en’);

// last modified (good for caching)

$time = time() - 60; // or filemtime($fn), etc

header(’Last-Modified: ‘.gmdate(’D, d M Y H:i:s’, $time).’ GMT’);

// header for telling the browser that the content

// did not get changed

header(’HTTP/1.1 304 Not Modified’);

// set content length (good for caching):

header(’Content-Length: 1234′);

// Headers for an download:

header(’Content-Type: application/octet-stream’);

header(’Content-Disposition: attachment; filename=”example.zip”‘);

header(’Content-Transfer-Encoding: binary’);

// load the file to send:

readfile(’example.zip’);

// Disable caching of the current document:

header(’Cache-Control: no-cache, no-store, max-age=0, must-revalidate’);

header(’Expires: Mon, 26 Jul 1997 05:00:00 GMT’); // Date in the past

header(’Pragma: no-cache’);

// set content type:

header(’Content-Type: text/html; charset=iso-8859-1′);

header(’Content-Type: text/html; charset=utf-8′);

header(’Content-Type: text/plain’); // plain text file

header(’Content-Type: image/jpeg’); // JPG picture

header(’Content-Type: application/zip’); // ZIP file

header(’Content-Type: application/pdf’); // PDF file

header(’Content-Type: audio/mpeg’); // Audio MPEG (MP3,…) file

header(’Content-Type: application/x-shockwave-flash’); // Flash animation

// show sign in box

header(’HTTP/1.1 401 Unauthorized’);

header(’WWW-Authenticate: Basic realm=”Top Secret”‘);

print ‘Text that will be displayed if the user hits cancel or ‘;

print ‘enters wrong login data’;

Eliminar espacios delante y detrás de las cadenas con PHP

Jueves, 22 de Abril de 2010

Disponemos de distintas formas de eliminar estos espacios.

trim ()
Con está función eliminamos los espacios en blanco del inicio y del final de la cadena.


$txt=” Cadena con espacios en blanco al inicio y final “;
echo trim ($txt);

Y el resultado seria


Cadena con espacios en blanco al inicio y final

chop ()
Elimina espacios sobrantes al final

ltrim ()
Elimina el espacio en blanco del principio de una cadena

Paginación automática con php

Martes, 9 de Marzo de 2010

Vamos a ver una forma de poner paginación automática, gracias a PAGINATOR

Bajarse el script: aquí

¿Cómo se utiliza?

  • Conectarse a la Base de datos.
  • Definir una sentencia sql (cadena) válida (para MySql) y almacenarla en la variable $_pagi_sql. Esta variable no debe contener la cláusula “LIMIT”, pues será agregada automáticamente por el script. La definición de esta variable es OBLIGATORIA.
  • OPCIONALMENTE también podemos definir las siguientes variables:
    1. $_pagi_cuantos: Entero. Número de resultados que queremos obtener por cada página. Si no se define esta segunda variable, será por defecto 20.Disponible desde la versión 1.0
    2. $_pagi_nav_num_enlaces: Entero. Cantidad de enlaces a los números de página que se mostrarán como máximo en la barra de navegación. Por defecto se muestran todos. Disponible desde la versión 1.3
    3. $_pagi_mostrar_errores: Booleano. Define si se muestran o no los errores de MySQL que se puedan producir. Por defecto está en “true”. Disponible desde la versión 1.3
    4. $_pagi_propagar: Array de cadenas. Contiene los nombres de las variables que se quiere propagar por el url. Por defecto se propagarán todas las que ya vengan por el url (GET). Disponible desde la versión 1.4
    5. $_pagi_conteo_alternativo: Booleano. Booleano. Define si se cuentan los registros desde PHP con mysql_num_rows() (true) o desde MySQL como se venía haciendo hasta ahora con COUNT(*) (false). Por defecto está en false. Recomendable mantener en false a menos que dé errores de conteo o resultados no esperados. Disponible desde la versión 1.5
    6. $_pagi_nav_estilo: Cadena. Contiene el nombre del estilo CSS para los enlaces de paginación. Por defecto no se especifica estilo.
    7. $_pagi_nav_anterior: Cadena. Contiene lo que debe ir en el enlace a la página anterior. Puede ser un tag <img>. Por defecto se utiliza la cadena “&laquo; Anterior”.
    8. $_pagi_nav_siguiente: Cadena. Contiene lo que debe ir en el enlace a la página siguiente. Puede ser un tag <img>. Por defecto se utiliza la cadena “&raquo; Siguiente”.
  • Incluir el Paginator. A partir de aquí, quedan disponibles las siguientes variables:
    1. $_pagi_result : Que contiene el id del resultado de la consulta para los registros de la página actual, listo para pasarlo por alguna función tipo mysql_fetch_array().
    2. $_pagi_navegacion : Que contiene la “barra de navegación” para poder acceder a las diferentes páginas.
    3. $_pagi_info : Cadena que contiene información sobre los registros de la página actual. Ejemplo: “desde el 16 hasta el 30 de un total de 123″;
  • Mostrar los resultados, la barra de navegación y la info en el lugar que mejor nos parezca haciendo uso de las variables mencionadas en el apartado anterior.

Ejemplo


//Conexión a la base de datos
$con = mysql_connect("localhost","tu_username","tu_password") or die (mysql_error());
mysql_select_db("tu_base",$con) or die (mysql_error());

//Sentencia sql (sin limit)
$_pagi_sql = "SELECT * FROM clientes WHERE sexo='m' ORDER BY edad";

//cantidad de resultados por página (opcional, por defecto 20)
$_pagi_cuantos = 10;

//Incluimos el script de paginación. Éste ya ejecuta la consulta automáticamente
include("paginator.inc.php");

//Leemos y escribimos los registros de la página actual
while($row = mysql_fetch_array($_pagi_result)){
    echo $row['nombre']."<br />";
}

//Incluimos la barra de navegación
echo"<p>".$_pagi_navegacion."</p>";

Fuente: http://jpinedo.webcindario.com/scripts/paginator/


Interpretar saltos de linea con php

Miércoles, 16 de Diciembre de 2009

Esta función sirve para interpretar los saltos de linea creados por el usuario a la hora de rellenar formularios.

nl2br($tring);

Compartir variables de sesión entre subdominios en php

Jueves, 10 de Diciembre de 2009

Con este código al principio de todo es el código, ya no se perderán las variables de sesión.

Muy útil si tienes áreas privadas con acceso con contraseña y diversos subdominios

ini_set(’session.cookie_domain’, ‘.dominio.com’ );

Donde solo se tiene que substituir ‘.dominio.com’, por el que sea vuestro.

clases crear imágenes thumbs php

Martes, 13 de Octubre de 2009

Código
//añadir la clase
include(“./class_imagenes.php”);

//imagen origen (1280px)
$imagen = “./fondo.jpg”;

//crear objeto
$thumbnails = new Imagenes();

//indicar la imagen origen
$thumbnails->setImagen($imagen);

//indicar el formato de la imagen origen
$thumbnails->setFormato(“jpg”);

//indicar el nivel de compresión. Segun este nivel la imagen
//tendra mayor o menos calidad.
$thumbnails->setCompresion(90);

//indicar donde se creará y con que nombre el thumbnails
$thumbnails->setNombre(“./thumb_fondo.jpg”);

//indicar el tamaño del thumbnails (250)
$thumbnails->reducir(250);
La clase (class_imagenes.php):
<?php
/**
* Creación de thumbnails ( creación de imágenes en miniatura )
*
*/

class Imagenes
{
//Propiedades de la clase
private $_imagen;
private $_formato = ‘jpg’;
private $_nuevaImagen;
private $_compresion = 90;
private $_nombre;

/**
* Verificar si la libreria GD esta instalada.
*/

public function __construct()
{
$gd=gd_info();

foreach ($gd as $key => $valor)
{
if(!$valor) {
return ‘La libreria GD no esta disponible.’;
}
}
}

/**
* Indicar a la clase con que imagen vamos a trabajar, es decir, a que
* imagen le vamos a crear un thumbnails.
*/

public function setImagen($urlImagen)
{
$this->_imagen = $urlImagen;
}

/*
* Indicar el formato de que tiene la imagen. La indicada en el
* método “setImagen”.
*/

public function setFormato($ext)
{
switch($ext)
{
case “jpeg”:
$this->_imagen = imagecreatefromjpeg($this->_imagen);
$this->_formato = $ext;
break;

case “jpg”:
$this->_imagen = imagecreatefromjpeg($this->_imagen);
$this->_formato = $ext;
break;

case “png”:
$this->_imagen = imagecreatefrompng($this->_imagen);
$this->_formato = $ext;
break;

default : return “Formato de imagen NO soportado.[jpeg|jpg|png]“;
}
}

/**
* Obtener el ancho (width) de la imagen.
*/

public function getImagenX()
{
return imagesx($this->_imagen);
}

/**
* Obtener el alto (height) de la imagen.
*/

public function getImagenY()
{
return imagesy($this->_imagen);
}

/**
* Nivel de compresión de la nueva imagen.
* Máximo 100.
* Cuanto mayor sea este valor mejor sera la calidad,
* pero tambien aumentara el tamaño.
*/

public function setCompresion($compresion)
{
$this->_compresion = $compresion;
}

/**
* Idicar nombre y ruta para la nueva imagen.
*/

public function setNombre($nombre)
{
$this->_nombre = $nombre;
}

/**
* Redimensionar imagen.
* Este método recibe el ancho (x) y el alto (y) que tendra
* la nueva imagen.
* Si $y no se indica, este se añadira con un ancho proporcinal.
*/

public function reducir($x, $y = 0)
{
if($y == 0) {
//Obtener el alto proporcionalmente.
$y = imagesy($this->_imagen) * $x;
$y = $y / imagesx($this->_imagen);
}

$this->_nuevaImagen = imagecreatetruecolor($x, $y);

imagecopyresampled($this->_nuevaImagen,
$this->_imagen,
0,
0,
0,
0,
$x,
$y,
imagesx($this->_imagen),
imagesy($this->_imagen));

switch($this->_formato)
{
case “jpeg”: imagejpeg($this->_nuevaImagen,$this->_nombre,$this->_compresion);
break;

case “jpg”: imagejpeg($this->_nuevaImagen,$this->_nombre,$this->_compresion);
break;

case “png”: imagepng($this->_nuevaImagen,$this->_nombre,$this->_compresion);
break;

default : return “Formato de imagen NO soportado.[jpeg|jpg|png]“;
break;
}
}
}
?>