Muchos desarrolladores contamos con lo que se suele denominar como, memoria atrofiada, somos capaces de recordar procedimientos y algoritmos para realizar ciertas tareas, pero a la hora de recordar sintaxis o nombre específicos de funciones, nos quedamos totalmente en blanco. Es por eso que un programador debe trabajar siempre con una conexión a Internet, para en los momentos de ayuda, poder consultar la comunidad del lenguaje en el que estemos desarrollando.
Personalmente cuento con una hoja de texto en la que guardo aquellos trozos de código que más suelo utilizar y cuya sintaxis no suelo recordar nunca. Este documento, que a la mayoría de la gente le puede parecer una tontería, ni os imagináis las veces que me ha sacado de un apuro y sobretodo, lo que me ha ayudado a optimizar tiempos.
Siempre es bueno contar con una chuleta para mejorar la productividad. Es por eso que he decidido compartir mi chuleta con todos vosotros, para que vosotros también os podáis aprovechar de ella. Como muchos ya sabéis, o habréis podido deducir, en el medio que mejor me desenvuelvo es en el ámbito web y si ahondamos más, diría que mi especialidad es PHP.
En este artículo os muestro 15 snippets de PHP que harán las delicias de todo programador web.
1. Enviar email utilizando la función mail()
$to = "[email protected]"; $subject = "Programacion"; $body = "Cuerpo del email, tambien se admite HTML"; $headers = "From: Peterrn"; $headers .= "Reply-To: [email protected]"; $headers .= "Return-Path: [email protected]"; $headers .= "X-Mailer: PHP5n"; $headers .= 'MIME-Version: 1.0' . "n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn"; mail($to,$subject,$body,$headers);
2. Codificación y decodificación en base 64
function base64url_encode($plainText) { $base64 = base64_encode($plainText); $base64url = strtr($base64, '+/=', '-_,'); return $base64url; } function base64url_decode($plainText) { $base64url = strtr($plainText, '-_,', '+/='); $base64 = base64_decode($base64url); return $base64; }
3. Obtener la IP remota en PHP.
function getRemoteIPAddress() { $ip = $_SERVER['REMOTE_ADDR']; return $ip; }
El anterior código no te funcionará si tu cliente se encuentra detrás de un servidor proxy. En ese caso, utiliza la función de a continuación para obtener la dirección IP real del cliente.
function getRealIPAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }
4. De segundos a string
function secsToStr($secs) { if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}} $r.=$secs.' second';if($secs<>1){$r.='s';} return $r; }
5. Validación de email en PHP
$email = $_POST['email']; if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) { echo 'This is a valid email.'; } else{ echo 'This is an invalid email.'; }
6. Parsear XML de forma sencilla en PHP
//this is a sample xml string
$xml_string
="<?xml version=
'1.0'
?>
<moleculedb>
<molecule name=
'Benzine'
>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name=
'Water'
>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
//load the xml string using simplexml function
$xml
= simplexml_load_string(
$xml_string
);
//loop through the each node of molecule
foreach
(
$xml
->molecule
as
$record
)
{
//attribute are accessted by
echo
$record
[
'name'
],
' '
;
//node are accessted by -> operator
echo
$record
->symbol,
' '
;
echo
$record
->code,
'<br />'
;
}
7. Conexión a base de datos
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404(); $dbHost = "localhost"; //Location Of Database usually its localhost $dbUser = "xxxx"; //Database User Name $dbPass = "xxxx"; //Database Password $dbDatabase = "xxxx"; //Database Name $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database."); mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database."); # This function will send an imitation 404 page if the user # types in this files filename into the address bar. # only files connecting with in the same directory as this # file will be able to use it as well. function send_404() { header('HTTP/1.x 404 Not Found'); print 'Not Found The requested URL '. str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']). ' was not found on this server.'."n". '."n"; exit; } # In any file you want to connect to the database, # and in this case we will name this file db.php # just add this line of php code (without the pound sign): # include"db.php";
8. Creando y parseando un JSON en PHP.
El siguiente código es para crear un fichero JSON a partir de un array de PHP.
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle")); echo json_encode($json_data);
Con el siguiente snippet, podrás parsearlo.
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} '; $obj=json_decode($json_string); //print the parsed data echo $obj->name; //displays rolf echo $obj->office[0]; //displays google
9. Tratar con MySQL Timestamp en PHP
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1"; $records = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($records)) { echo $row; }
10. Generar un password en PHP
# This particular code will generate a random string # that is 25 charicters long 25 comes from the number # that is in the for loop $string = "abcdefghijklmnopqrstuvwxyz0123456789"; for($i=0;$i<25;$i++){ $pos = rand(0,36); $str .= $string{$pos}; } echo $str; # If you have a database you can save the string in # there, and send the user an email with the code in # it they then can click a link or copy the code # and you can then verify that that is the correct email # or verify what ever you want to verify
11. Validación de formato de fecha
function checkDateFormat($date) { //match the format of the date if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) { //check weather the date is valid of not if(checkdate($parts[2],$parts[3],$parts[1])) return true; else return false; } else return false; }
12. Redirección HTTP en PHP
header('Location: http://you_stuff/url.php'); // stick your url here
13. Listar directorios en PHP
function list_files($dir) { if(is_dir($dir)) { if($handle = opendir($dir)) { while(($file = readdir($handle)) !== false) { if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/) { echo 'Dir file:'.$dir.$file.' File:'.$file.''."n"; } } closedir($handle); } } }
14. Detectar navegador
$useragent = $_SERVER ['HTTP_USER_AGENT']; echo "Your User Agent is: " . $useragent;
15. Descomprimir un fichero zip
function unzip($location,$newLocation){ if(exec("unzip $location",$arr)){ mkdir($newLocation); for($i = 1;$i< count($arr);$i++){ $file = trim(preg_replace("~inflating: ~","",$arr[$i])); copy($location.'/'.$file,$newLocation.'/'.$file); unlink($location.'/'.$file); } return TRUE; }else{ return FALSE; } } ?> //Use the code as following: <?php include 'functions.php'; if(unzip('zipedfiles/test.zip','unziped/myNewZip')) echo 'Success!'; else echo 'Error';