Webserveis

Blog de desarrollo web

  • Home
  • Archivo
  • Proyectos
  • Sample Page

7

Feb

Clase para crear newsletter

Posted by admin  Published in Code Snippets, PHP Snippets
<?php
/*
* @class simplenewsletter
* @author webserveis
* @web www.webserveis.com
* @email webserveis@gmail.com
* @copyright webserveis
* @date 07/02/2012
* @license GPL
* @usage
 
$NewsLetter = new SimpleNewsLetter('localhost','user','password','database');
$NewsLetter->createtable('Newsletter');
echo '';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
echo '';
if ($NewsLetter->delEmail('prova@hotmail.com')) echo 'email eliminado'; else echo 'no se ha encotrado email';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
if ($NewsLetter->addemail('prova2@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
echo ''.$NewsLetter->listemails();
 
*/
 
class SimpleNewsLetter {
 
   private $DB_Link = '';
   private $DB;
   private $Table = '';
 
   public function __construct($host,$user,$pass,$dbname,$table='Newsletter') {
   /*
   * @call $var = new SimpleNewsLetter(@params);
   * @param string host: host del mysql server
   * @param string user: nom d'usuari del mysql server
   * @param string dbname: nom de la base de dades
   * @param string table: nom de la taula per ingresar els emails, per defecte 'newsletter'
   */
      $this->DB_Link = mysql_connect($host,$user,$pass);
      $this->DB = mysql_select_db($dbname, $this->DB_Link);
      $this->Table = $table;
   }
 
   public function __destruct() {
      mysql_close( $this->DB_Link );
   }
 
   public function createtable($table='Newsletter',$delete=false) {
   /*
   * @call $var->createtable(@params);
   * @param string table: nom de la taula, per defecte 'Newsletter'
   * @param bool delete: si es 'true' eliminara la taula existent, per defecte esta a 'false'
   */
      $this->Table = $table;
      $Sql = '';
      if ($delete) {
         $Sql = 'DROP TABLE IF EXISTS `' . $this->Table . '`;';
         $Result = mysql_query($Sql,$this->DB_Link);
      }
      $Sql = 'CREATE TABLE IF NOT EXISTS `' . $this->Table . '` (`Id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`Email` VARCHAR( 256 ) NOT NULL ,UNIQUE (`Email`)) ENGINE = MYISAM CHARACTER SET utf8';
      $Result = mysql_query($Sql,$this->DB_Link);
      return $Result;
 
   }
 
   public function listemails($bracket=';') {
   /*
   * @call $var->listemails(@params);
   * @param string bracket: caracter separador entre emails, per defecte ';'
   * @return string: llista els emails
   */
      $ret = '';
      $Sql = 'SELECT Email FROM ' . $this->Table .';';
      $Result = mysql_query($Sql,$this->DB_Link);
      if ($Result)
      while( $row = mysql_fetch_assoc( $Result ) ){
         $ret .= $row['Email'] . $bracket;
      }
      return $ret;
   }
 
   public function addemail($email) {
   /*
   * @call $var->addemial(@params);
   * @param string email: email a insertar
   * @return : 'true' si sha pogut insertar, 'false' si ja existeix
   */
      $Sql = 'INSERT INTO ' . $this->Table . "(Email) VALUES ('" . $email ."') ;";
      $Result = mysql_query($Sql,$this->DB_Link);
      if (mysql_affected_rows($this->DB_Link) >= 1) return true; else return false;
   }
 
   public function delEmail($email) {
   /*
   * @call $var->delEmail(@params);
   * @param string email: email a eliminar
   * @return: 'true' i s'ha pogut eliminar, 'false' si no s'ha trobat en el llistat
   */
      $Sql = 'DELETE FROM ' . $this->Table . " WHERE Email='" . $email . "';";
      $Result = mysql_query($Sql,$this->DB_Link);
      if (mysql_affected_rows($this->DB_Link) >= 1) return true; else return false;
   }
 
}
?>

Ejemplo de uso

$NewsLetter = new SimpleNewsLetter('localhost','user','password','database');
$NewsLetter->createtable('Newsletter');
echo '<br />';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
echo '<br />';
if ($NewsLetter->delEmail('prova@hotmail.com')) echo 'email eliminado'; else echo 'no se ha encotrado email';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
if ($NewsLetter->addemail('prova@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
if ($NewsLetter->addemail('prova2@hotmail.com')) echo 'Insert'; else echo 'alredy exist';
echo '<br />'.$NewsLetter->listemails();

Tags: php

no comment

26

Jan

Funcion br2nl en php

Posted by admin  Published in Code Snippets, PHP Snippets

PHP carece de la función inversa de nl2br, la funcion nl2br de php convierte todos los saltos de linea a salto de linea html <br />

Por eso la función siguiente br2nl, conviete los <br /> a salto de linea

Declaración de la función br2nl

function br2nl($string, $line_break=PHP_EOL) {
    $patterns = array("/(<br>|<br \/>|<br\/>)\s*/i","/(\r\n|\r|\n)/");
    $replacements = array(PHP_EOL,$line_break);
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}

Uso de la función br2nl

echo br2nl($Texto)

Tags: php, php-snippet, snippet

no comment

25

Jan

Obtener valores por $_GET en php

Posted by admin  Published in Code Snippets, PHP Snippets

Cuando tenenmos que obtener valores por la url, la menera correcta seria la siguiente

$start = (isset($_GET['num']) && is_numeric($_GET['num']))? (int)$_GET['num']:die("Hacking Attempt!");

Tags: php, php-snippet, snippet

no comment

14

Jan

Mostrar el tiempo pasado de una fecha

Posted by admin  Published in Code Snippets, PHP Snippets

Función para mostar el tiempo pasado a partir de una fecha “timeago”

Declaración de la función TimeAgoEs

function TimeAgoEs($tm,$rcs = 0) {
	/*$tm = timeint
		strtotime("2011/01/14 23:10");
	*/
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('segundo','minuto','hora','dia','semana','mes','año','decada');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
   $no = floor($no);
   if ($v == 5) $pds[$v] .='es'; elseif($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs > 0)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= TimeAgoEs($_tm, --$rcs);
   return $x;
}

Uso de la función TimeAgoEs

$tm el valor de la fecha tipo timeint, para pasar una fecha en formato YYYY/mm/dd usar la función strtotime de php.
$rcs segmentos que se mostraran por defecto 0, si se especifica 1 X tiempo x tiempo

echo TimeAgoEs(strtotime("2012-01-14 23:04:13"),0);
echo TimeAgoEs(strtotime("2012-01-14 23:04:13"),2);

Salida

1 hora
1 hora 9 minutos 3 segundos;

Tags: php, php-snippet, snippet

no comment

28

Dec

Mostrar la fecha en Español con PHP

Posted by admin  Published in Code Snippets, PHP Snippets

Función GetDateEs es para convertir una fecha aaa/mm/dd en data escrita (28 de Diciembre del 2011). La función devuelve una cadena con la data escrita

Declaración de la función

function GetDateES($Fecha) {
   $a[1] = "Enero";$a[2] = "Febrero"; $a[3] = "Marzo"; $a[4] = "Abril"; $a[5] = "Mayo"; $a[6] = "Junio";    $a[7] = "Julio"; $a[8] = "Agosto";
   $a[9] = "Septiembre"; $a[10] = "Octubre"; $a[11] = "Noviembre"; $a[12] = "Diciembre";
   return date("d",strtotime($Fecha)) ." de " . $a[date("n",strtotime($Fecha))] . " de " . date("Y",strtotime($Fecha));
}

Uso de la función

$Var_data = GetDateES(date("Y/m/d"));
echo $Var_data;

Tags: php, php-snippet, snippet

no comment

28

Dec

Sanitizar entrada prevenir inyección sql en php

Posted by admin  Published in Code Snippets, PHP Snippets

Función SanitizeInputSQL es para sanitizar variables ante un ataque de inyección SQL. La función devuelve la cadena sanitizada

Declaración de la función

function SanitizeInputSQL($dirty_input) {
	if (get_magic_quotes_gpc()) $value = stripslashes($dirty_input);
	$value = mysql_real_escape_string($dirty_input);
	return $value;
}

Uso de la función

$Var_password = SanitizeInputSQL($_POST['txt_password']);

Tags: php, php-snippet, snippet

no comment

28

Dec

Sanitizar entrada prevenir xss en php

Posted by admin  Published in Code Snippets, PHP Snippets

Función SanitizeInputXSS es para sanitizar variables ante un ataque XSS. La función devuelve la cadena sanitizada

Declaración de la función

function SanitizeInputXSS($dirty_input) {
	return htmlspecialchars(rawurldecode(trim($dirty_input)), ENT_QUOTES,'UTF-8');
}

Uso de la función

$Var_nombre = SanitizeInputXSS($_POST['txt_nombre']);

Tags: php, php-snippet, snippet

no comment

13

Dec

Función validar y comprobar email en PHP

Posted by admin  Published in Code Snippets, PHP Snippets

Función isVAlidEmailExpara validar un email y comprobar su existencia en PHP, la función devuelve true o false si el email es válido y existe

Declaración de la función

function isValidEmailEx($email, $mx = false){   
  if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))   
    if($mx){   
      list($username, $domain) = split("@", $email);   
      return getmxrr($domain, $mxrecords);   
    }else  
      return true;   
    else  
  return false;   
}

Uso de la función

$Email = 'abc@dominio.com';
if (isValidEmailEx($Email)) echo 'email valido'; else echo 'email incorrecto';
if (isValidEmailEx($Email,true)) echo 'email valido y existente'; else echo 'email incorrecto o valido pero inexistente';

Tags: php, php-snippet, snippet

no comment

13

Dec

Función validar email en php

Posted by admin  Published in Code Snippets, PHP Snippets

Función para validar un email valido en PHP, la función devuelve true o false si el email es válido o no

Declaración de la función isValidEmail

function isValidEmail($email){
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

Uso de la función

$Email = 'abc@dominio.com';
if (isValidEmail($Email)) echo 'email valido'; else echo 'email incorrecto';

Tags: php, php-snippet, snippet

no comment

Categorias

  • Code Snippets (15)
    • CSS Snippets (2)
    • IOS Web Snippets (4)
    • PHP Snippets (9)
  • Maquetación web (6)
    • CSS (1)
    • WebDev Mobile (1)
    • XHTML (5)
  • Programación web (8)
    • PHP (8)

Tags

Android css css-snippet IOS javascript Mobile mobile-snippet optimizacion php php-snippet Security snippet WebApp Webkit xhtml xhtml strict XSS

Archivos

  • February 2012
  • January 2012
  • December 2011
  • November 2011

Recent Entries

  • Clase para crear newsletter
  • Comentar el codigo
  • Consejos para optimizar PHP II
  • Consejos para optimizar PHP
  • Funciones para convertir Fechas en PHP
  • Funcion br2nl en php
  • Obtener valores por $_GET en php
  • Cómo ocultar la barra de navegación en tus aplicaciones web mobile con JavaScript
  • Prevenir el ajusto de texto en rotar
  • Definición de viewport para paginas web moviles

Recent Comments

  • Weahl in Estructura de directorios para sitios web en PHP
  • Random Selection of Posts

    • Funcion br2nl en php
    • Función validar y comprobar email en PHP
    • Configurar PHP para depurar código
    • Comentar el codigo
    • Definición de viewport para paginas web moviles
    • Detectar Iphones y Ipods usando javascript
    • Consejos para optimizar PHP
© 2008 Webserveis is proudly powered by WordPress
Theme designed by Roam2Rome