| |
Páginas: [1]
|
 |
|
Autor
|
Tema: Pequeños trucos en PHP (Leído 4417 veces)
|
|
Ertai
|
Pues eso, quería crear este post para ir poniendo pequeños truquillos, aunque sean tonterias, pero que nos pueden ayudar en ciertos momentos cuando programamos. Este post es para que le vayais hechando un ojo de vez en cuando, y que, si algun día os encontreís un problema podais acudir aquí para ver como se hacía. Los trucos escritos aquí seran reescritos por mí en el primer post, para mantener un poco el orden. Gracias. Evitar la caché de los navegadoresA 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 SQLPuede 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'); ?> Hacer funcionar la función mail()En local, la función mail() nos devolverá un error porque no tenemos configurado un cliente SMTP. Aquí teneis la forma más fácil y rápida de solucionar este problema. http://www.forosdelweb.com/showpost.php?p=662241&postcount=115 Intercambiar colores en X filasA 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. Ahí va: <?php $color = "#000000"; $i = 0; while ($i < 10) { $color = ($color == "#000000") ? "#FFFFFF" : "#000000"; echo $color."<br>"; $i++; } ?> Fechas en MySQLUna lista de funciones muy útiles para trabajar con fechas en nuestra base de datos MySQL http://www.xlwebmasters.com/modules.php?d=doc&f=doc2&id=1057 Saber si un año es bisiestoPues eso  (por Azielito) <?php function Bisiesto($anyo) { return checkdate(02,29,$anyo); } ?> ... y asi funciona ... <?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 descargaForzar la descarga de un archivo desde PHP en un navegador header("Content-type: application/force-download");
|
|
|
|
« Última modificación: 20 Septiembre 2007, 21:13 por Ing_Amc »
|
En línea
|
Si la felicidad se comprara, entonces el dinero sería noble.
|
|
|
|
дٳŦ٭
|
Aquí dejo una función muy sencilla pero útil  <?php function conectar($host, $user, $pass, $database){ $conectar = mysql_connect($host, $user, $pass) or die(mysql_error()); mysql_select_db($database,$conectar); return $conectar; } $conexion=conectar("tuhost","user","password","basededatos"); ?> Por ejemplo, en cada desarrollo creo un archivo llamado db.php y lo incluyo (include()) en mis php que usan MySQL. Ya solo utilizamos la variable $conexion como identificador de conexión. Validar emailUna función para validar tu email (incluyendo subdominios). <?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 SQLEs 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 HTTPSSi 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 PHPEnviar 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; } ?> Checar headersChequea si ya se enviaron cabeceras y en que parte. <?php // Si no se han enviado cabeceras, enviar una if (!headers_sent()) { header('Location: http://www.example.com/'); exit; } // Un ejemplo del uso de las parametros opcionales archivo y linea, a // partir de PHP 4.3.0. // Note que $nombre_archivo y $num_linea son pasados para su uso posterior. // No les asigne valores con anterioridad. if (!headers_sent($nombre_archivo, $num_linea)) { header('Location: http://www.example.com/'); exit; // Probablemente quiera producir un error aqui. } else { echo "Las cabeceras ya fueron enviadas en $nombre_archivo en la linea " . "$num_linea\nNo es posible redireccionar, por ahora por favor " . "pulse este <a href=\"http://www.example.com\">enlace</a> en su " . "lugar\n"; exit; } ?> Otros más: Glosario de funcioneshttp://foro.elhacker.net/index.php/topic,65126.0.html
|
|
|
|
« Última modificación: 20 Febrero 2008, 17:50 por Ing_Amc »
|
En línea
|
La gente sueña por la noche con volar, nosotros salimos por la noche y volamos. JMF.
|
|
|
|
born2kill
|
Aqui algunas funciones simples y utiles  <?php function mysql_now() { $fecha = fecha(”Y-m-d H:i:s”); return $fecha; } ?> Con la función MySqlNow, podemos obtener la hora y fecha local desde MYSQL.
<?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); ?> Con esta función nos conectamos a un servidor FTP, y luego nos desconectamos, esto es util para si tenemos algun script y tenemos que renombrar archivos, etc. B0rn2kill
|
|
|
|
« Última modificación: 16 Julio 2007, 00:27 por born2kill »
|
En línea
|
|
|
|
Red Mx
Rojito
Colaborador
Desconectado
Mensajes: 2.946
Sube tu avatar a www.TuIMG.net
|
Ps ay les voy con unas //------ 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)"; } ?>
|
|
|
|
|
En línea
|
|
|
|
|
coolfrog
|
aqui les paso mi clase: hola que tal, bueno hice una clase para evitar tener que cambiar la sintaxis con diferentes bases de datos, todo ese proceso de queries y connects es muy engorroso y bueno aqui esta mi clase hecha en php5 (la hice en php4 pero la actualize). Deben nombrar a este archivo "DBALL.php" (nota: no significa Dragon Ball, significa data bases all - todas las bases de datos)  <?php /** * Creador: Coolfrog from Bolivia * Correo: jm.neutron@gmail.com * Blog: http://mundocoolf.blogspot.com * Web Page: ***En progreso*** * Version:1.1 * * Clase para php5 que permite ejecutar MYSQL, POSTGRESQL E ISIS * en versiones siquientes se aumentara para oracle y otras que sean necesarias. * Ultima Acualización 6/8/07 * * Es cogigo libre y puede ser distribuido a cualquier persona, solo una condicion ,para usar esta clase deben dejar mis datos ;) es lo unico que les agradeceria que hicieran */ include("iniDB.php"); //archivo que inicia las variables estaticas, SIRVE PARA TRABAJAR CON UN SOLO MOTOR DE BASE DATOS class DBALL{ public static $host; public static $usr; public static $pass; public static $dbname; public static $motor; private $conex; private $result; public static $showErrors; /*#######DESCOMENTAR EL CONSTRUCTOR SI SE QUIERE TRABAJAR CON DOS O MAS MOTORES DE BASES DE DATOS AL MISMO TIEMPO, Y HACER LA CONEXCION CON EL CONSTRUCTOR PARA CADA MOTOR#######*/ /** * constructor que inicia las variables * * @param str $host * @param str $usr * @param str $pass * @param str $dbname * @param str $motor */ /*function __construct($host,$usr,$pass,$dbname,$motor){ self::$host=$host; self::$usr=$usr; self::$pass=$pass; self::$dbname=$dbname; self::$motor=$motor; }*/ /*#####CONSTRUCTOR: DESCOMENTAR HASTA AQUI#####*/ /** * metodo que conecta a una base de datos dependiendo del parameto $motor * @return boolean */ public function dbConnect(){ self::$motor=strtoupper(self::$motor); $v=false; if(self::$motor=="MYSQL"){ $this->conex=mysql_connect(self::$host,self::$usr,self::$pass); $var=mysql_select_db(self::$dbname,$this->conex); if($var){ $v=true; } } else if(self::$motor=="PSQL"){ $this->conex=@pg_connect("host=".self::$host." dbname=".self::$dbname." user=".self::$usr." password=".self::$pass); if($this->conex){ $v=true; } } else if(self::$motor=="ISIS"){ $this->conex=isis_open(self::$dbname,"-v error -format aligned -encoding ISO8859_1"); if($this->conex){ $v=true; } } //devuelve true si se conecto y false si hay error return $v; } /** * selecciona registros SELECTS * * @param string $consulta * @return array */ public function dbSelect($consulta){ $res=array(); if(self::$motor=="MYSQL"){ $this->result = mysql_query($consulta); if(self::$showErrors){ if(mysql_errno($this->conex)!=0) echo "Error ".mysql_errno($this->conex)." : ".mysql_error($this->conex); } $fila= mysql_num_rows($this->result); $i=0; while ($row = mysql_fetch_object($this->result)){ $res[$i]=$row; $i++; } mysql_free_result($this->result); }else if(self::$motor=="PSQL"){ $this->result = @pg_query($this->conex,$consulta); $fila=@pg_numrows($this->result); for($i=0;$i<$fila;$i++){ $res[$i]=@pg_fetch_object($this->result,$i); } @pg_free_result($this->result); }else if (self::$motor=="ISIS"){ $this->result = isis_query($consulta,$this->conex); $i=0; if ($this->result!=null && $this->result!='') { while($record = isis_fetch_flat_array($this->result)){ $res[$i]=$record; $i++; } } } return $res; } /**; * realiza consultas como:UPDATE,INSERT AND DELETE * retorna true si la consulta se ejecuto correctamente caso contrario false * * @param string $consulta * @return boolean */ public function dbABM($consulta){ $r=false; if(self::$motor=="MYSQL"){ $this->result = mysql_query($consulta); if(self::$showErrors){ if(mysql_errno($this->conex)!=0) echo "Error ".mysql_errno($this->conex)." : ".mysql_error($this->conex | | | | |