Programación‎ > ‎PHP‎ > ‎

Pequeños trucos


Evitar la caché de los navegadores

A veces podemos encontrarnos el problema de que una página no nos actualiza el contenido porque está en caché. Se puede solucionar modificando las cabeceras.

<?php
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );  // disable IE caching
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-cache, must-revalidate" );
header( "Pragma: no-cache" );
?>



Contador en SQL


Puede ser que necesitemos un contador (de lecturas, por ejemplo) de una noticia guardada en SQL. Si queremos aumentar este valor, muchos habríamos leído el campo, lo hubieramos incrementado y luego hubieramos hecho el UPDATE. Pues hay una forma mucho más fácil, segura y limpia de hacerlo y con solo una SQL.

<?php
mysql_query('UPDATE trucos SET lecturas = lecturas + 1 WHERE id=12 LIMIT 1');
?>



Intercambiar colores en X filas


A la hora de hacer listados, puede darse el caso que la legibilidad de las filas no sea buena, por lo tanto sera conveniente usar dos colores diferentes de background para cada fila, de manera que se vayan intercalando y la legibilidad sea buena. Como hacemos esto? Pues una de las maneras más elegantes es usar el operador ternario.

<?php
$color = "#000000";
$i = 0;
while ($i < 10)
{
  $color = ($color == "#000000") ? "#FFFFFF" : "#000000";
  echo $color."<br>";
  $i++;
}
?>



Saber si un año es bisiesto

<?php
function Bisiesto($anyo)
{
return checkdate(02,29,$anyo);
}
?>
 

<?php
$actual = date("Y");
$sig = $actual+1;
if(Bisiesto($actual)){
echo $actual." es bisiesto<br>";
}else{
echo $actual." no es bisiesto<br>";
}
 
if(Bisiesto($sig)){
echo $sig." es bisiesto<br>";
}else{
echo $sig." no es bisiesto<br>";
}
?>



Forzar descarga

Forzar la descarga de un archivo desde PHP en un navegador

header("Content-type: application/force-download");



Validar email

Una función para validar tu email (incluyendo subdominios):
Código

<?php
function ValidaMail($v_email) {
   if (ereg("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@+([_a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]{2,200}\.[a-zA-Z]{2,6}$", $v_email )){
return true;
  }
else{
      return false;
    }
}
?>



Asegurando contra Inyección SQL

Es una función que incluye el SMF para evitar inyección SQL:

<?php
function addslashes__recursive($var){
if (!is_array($var))
return addslashes($var);
$new_var = array();
foreach ($var as $k => $v)$new_var[addslashes($k)]=addslashes__recursive($v);
return $new_var;
}
$_POST=addslashes__recursive($_POST);
$_GET=addslashes__recursive($_GET);
$_REQUEST=addslashes__recursive($_REQUEST);
$_SERVER=addslashes__recursive($_SERVER);
$_COOKIE=addslashes__recursive($_COOKIE);
?>



Redireccionar a HTTPS

Si nuestra web la tenemos normal con el 'HTTP' pero si queremos redireccionarlos automaticamente a HTTPS (necesitas un certificado) con esto lo puedes hacer:

<?php
if(!$_SERVER['HTTPS']== 'on'){
      $nueva="https://". $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
      header("Location: $nueva");
      exit();
   }
?>
 


Mandar email con PHP


Enviar email con la función mail() de PHP.

<?php
//Ejemplo: send_mail("user@mail.com","cuerpo","asunto","demi@localhost","demi");
 
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false)
{
 $eol="\r\n";
 $mime_boundary=md5(time());
 
 # Common Headers
 $headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
 $headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
 $headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol;    // these two to set reply address
 $headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
 $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
 
 # Boundry for marking the split & Multitype Headers
 $headers .= 'MIME-Version: 1.0'.$eol.$eol;
 $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;
 
 # Open the first part of the mail
 $msg = "--".$mime_boundary.$eol;
 
 $htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
 # Setup for text OR html -
 $msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;
 
 # Text Version
 $msg .= "--".$htmlalt_mime_boundary.$eol;
 $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= strip_tags(str_replace("<br>", "\n", substr($body, (strpos($body, "<body>")+6)))).$eol.$eol;
 
 # HTML Version
 $msg .= "--".$htmlalt_mime_boundary.$eol;
 $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
 $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
 $msg .= $body.$eol.$eol;
 
 //close the html/plain text alternate portion
 $msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
 
 if ($attachments !== false)
 {
   for($i=0; $i < count($attachments); $i++)
   {
     if (is_file($attachments[$i]["file"]))
     { 
       # File for Attachment
       $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
 
       $handle=fopen($attachments[$i]["file"], 'rb');
       $f_contents=fread($handle, filesize($attachments[$i]["file"]));
       $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
       $f_type=filetype($attachments[$i]["file"]);
       fclose($handle);
 
       # Attachment
       $msg .= "--".$mime_boundary.$eol;
       $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
       $msg .= "Content-Transfer-Encoding: base64".$eol;
       $msg .= "Content-Description: ".$file_name.$eol;
       $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
       $msg .= $f_contents.$eol.$eol;
     }
   }
 }
 
 # Finished
 $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
 
 # SEND THE EMAIL
 ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
 $mail_sent = mail($to, $subject, $msg, $headers);
 
 ini_restore(sendmail_from);
 
 return $mail_sent;
}
?>



Obtener la hora y fecha local desde MYSQL

<?php
function mysql_now() {
   $fecha = fecha(”Y-m-d H:i:s”);
   return $fecha;
}
?>



Conectarse a un servidor FTP, y luego desconectarse

<?php
// Abrimos la conexion FTP
$conn_id = ftp_connect($ftp_server);
 
// Entramos con nuestro user & pass
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
 
// Chequeamos la conexion
if ((!$conn_id) || (!$login_result)) {
       echo "Fallo conexion";
       exit;
   } else {
       echo "Conectado a $ftp_server, for user $ftp_user_name";
   }
 
// Cerramos la conexion
ftp_close($conn_id);
?>  



Funciones de abstraccion de consultas SQL


//-INSERT- $columns=get_commas(...)   $values=get_commas(...)
function get_insert($table, $columns, $values){
return "INSERT INTO $table ($columns) VALUES ($values)";
}
 
//-UPDATE- $values=get_mult_set(...)   $where=get_mult_set(...) o get_simp_set(...)
function get_update($table, $values, $where){
return "UPDATE $table SET $values WHERE $where";
}
 
//-UPDATE- actualiza una tabla con valores de otra (sólo MySQL >4.xx)
function get_update_join($table_a, $table_b, $id_a, $id_b, $values, $where=''){
if($where!='') $where="AND ($where)";
return "UPDATE $table_a a, $table_b b SET $values WHERE a.$id_a=b.$id_b $where";
}
 
//-SELECT- $columns=get_commas(...) o '*'   $where=get_mult_set(...) o get_simp_set(...)
function get_select($table, $columns, $where='', $order=''){
$tmp = "SELECT $columns FROM $table";
if($where!=''){
$tmp.=" WHERE $where";
}
if($order!=''){
$tmp.=" ORDER BY $where";
}
return $tmp;
}
 
//-SELECT- entre 2 tablas por 2 indices comunes
function get_select_join($table_a, $table_b, $id_a, $id_b, $columns, $where='', $order=''){
$table ="$table_a a, $table_b b";
$w="a.$id_a=b.$id_b ";
if($where!='') $w.="AND ($where)";
return get_select($table, $columns, $w, $order);
}
 
 
//-DELETE-  $where=get_mult_set(...) o get_simp_set(...)
function get_delete($table, $where=''){
$tmp = "DELETE FROM $table";
if($where!=''){
$tmp.=" WHERE $where";
}
return $tmp;
}
//- get_commas(true|false, 1, 2, 4...) true pone comillas  => '1','2','4'...
function get_commas(){
$a=func_get_args();
$com = $a[0];
return get_commasA(array_slice($a, 1, count($a)-1), $com);
}
//- como la anterior pero devuelve entre comas el array pasado
function get_commasA($arr_in, $comillas=true){
$temp='';
$coma="'";
if(!$comillas) $coma=''; //-el 1er param==true, metemos comas
 
foreach($arr_in as $arg){
  if($temp!='')  $temp.=",";
  if(substr($arg,0,2)=='!!'){ //- Si empieza por !! no le pongo comas...
$temp.=substr($arg,2); continue;
  }
  $temp.="$coma".$arg."$coma";
}
return $temp;
}
 
//- Devuelve una asignacion (por defecto) simple entre comillas  X='1'
function get_simp_set($col, $val, $sign='=', $comillas=true){
$cm="'";
if(!$comillas) $cm='';
if(substr($val,0,2)=='!!'){ //- Si empieza por !! no le pongo comas...
$val=substr($val,2); $cm='';
}
return $col."$sign $cm".$val."$cm";
}
 
//-Mezcla cada valor de $a_cols, con uno de $a_vals   "X='1', T='2'...
//- ej:  con $simb='or'  X='1' or T='2'...
//- ej:  con $sign='>'   X>'1' or T>'2'...
function get_mult_set($a_cols, $a_vals, $simb=',', $sign='=', $comillas=true){
$temp='';
for($x=0;$x<count($a_cols);$x++){
if($temp!='')  $temp.=" $simb ";
  $temp.= get_simp_set($a_cols[$x],$a_vals[$x], $sign, $comillas);
}
return $temp;
}
 
function get_between($col, $min, $max){
return "($col BETWEEN $min AND $max)";
}
 
 
?>



Funcion para cortar texo o limitar, ideal para ultimas noticias y demas


<?
// Funcion para cortar texto
// Programado por alienmaster <efnworkz@hotmail.com>
// http://4cosas.com
function cortar($text0, $limite){
   $comp = strlen($text0);
   if($comp > $limite){
       return = substr($text0, 0, $limite)."...";
   }
   else{
       return "$text0";
   }
}
?>



Forma abreviada para imprimir en pantalla


$nick="Soy Carxl";
<?=$nick?>



Seleccionar lo que hay dentro de un string desde la palabra necesitada hasta la que finaliza

<?php
 
function desde_hasta($desde, $hasta, $contenido){
if(eregi($desde ,$contenido)){
 $retorno = explode($desde, $contenido);
 $retorno = $retorno[1];
 $retorno = explode($hasta, $retorno);
 $retorno = $retorno[0];
 return $retorno;
} else {
 return FALSE;
}
}
 
?>


Se ejecuta:


<?php
$contenido = 'tienes <a href="http://foro.elhacker.net/pm.html">111 mensajes</a>';
$cantidad_mensajes = desde_hasta('tienes <a href="http://foro.elhacker.net/pm.html">', 'mensajes</a>', $contenido);
echo "Cantidad de mensajes: $cantidad_mensajes\n";
?>





Fuente original:
http://foro.elhacker.net/php/pequenos_trucos_en_php-t152467.0.html
Comments