Trucos de php

Iniciado por godmurdoc, Junio 27, 2011, 06:36:22 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Junio 27, 2011, 06:36:22 PM Ultima modificación: Marzo 22, 2014, 02:15:47 PM por Expermicid
Evitar la caché de los navegadores:
Código: php
<?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.

Código: php
<?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. Ahí va:

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


Forzar descarga
Forzar la descarga de un archivo desde PHP en un navegador

Código: php
header("Content-type: application/force-download");


Validar email
Una función para validar tu email (incluyendo subdominios).
Código: php
<?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:
Código: php
<?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);
?>


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

Código: php
<?php
//Ejemplo: send_mail("[email protected]","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 headers
Chequea si ya se enviaron cabeceras y en que parte.
Código: php
<?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;
}

?>


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:

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


Funcion para cortar texo o limitar, ideal para ultimas noticias y demas:
Código: php
<?
// Funcion para cortar texto
// Programado por alienmaster <[email protected]>
// 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:

Código: php
$nick="Soy Carxl";
<?=$nick?>


Esa instrucción reemplazaría: <?php echo $nick;?>

Hice una pequeña función que permite seleccionar lo que hay dentro de un string desde la palabra necesitada hasta la que finaliza...

Código: php
<?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;
}
}

?>


De esta forma ejecutas:
Código: php
<?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";
?/


Estaba realizando unas funciones propias para un sistema que estoy haciendo y quería compartirlo con ustedes si es que agún dia tienen la misma necesidad:

Código: php
<?php
$palabra = "1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950";
echo whk_recorta($palabra,10);
/* Resultado: 1234567891...4647484950 */

function whk_recorta($palabra,$limite){
if($limite < 1){
return $palabra;
}
if(strlen($palabra)>(($limite * 2) + 1)){
for($cuenta=0;$cuenta<$limite;$cuenta++){
  $palabra_final .= $palabra[$cuenta];
}
$palabra_final .= "...";
for($cuenta = (strlen($palabra) - $limite); $cuenta <= strlen($palabra); $cuenta++){
  $palabra_final .= $palabra[$cuenta];
}
return $palabra_final;
}else{
return $palabra;
}
}
?>




Transformación de Strings en múltiples formas:
Código: php
// Powered by GreenCode - WHK
function codifica_base64_gz($buffer){
$buffer = bin2hex(base64_encode(gzcompress($_POST['buffer'])));
$separador = 16; // Editable, separador de 16 bytes.
$separa = 0;
for($cuenta=0;$cuenta<strlen($buffer);$cuenta+=2){
if($separa == 0){
  $dump .= '"';
}
$dump .= '\x'.$buffer[$cuenta].$buffer[$cuenta+1];
$separa++;
if($separa == $separador){
  $dump .= '"';
  if($cuenta != (strlen($buffer))-2){
   $dump .= '.'."\n";
  }
  $separa = 0;
}
}
if($dump[strlen($dump)-1] != '"'){
$dump .= '"';
}
return
"\x3c\x3fphp\n// ...\n\n/* El retorno es tu buffer */".
"\$str = gzuncompress(base64_decode(\n$dump\n));\n\n// ...\n\x3f\x3e";
}

function ascii_a_png($buffer){
return
"\x3c\x3fphp\n// ...\n\n".
"/* El retorno es una imagen */\n".
"\$handle_img = imagecreate(".(int)(strlen($buffer) * 9).", 30);\n".
"\$fondo = imagecolorallocate(\$handle_img, 255, 255, 255);\n".
"\$color_texto = imagecolorallocate(\$handle_img, 0, 0, 255);\n".
"imagestring(\$handle_img, 5, 0, 0, base64_decode(\"".base64_encode($buffer)."\"), \$color_texto);\n".
"header(\"Content-type: image/png\");\n".
"imagepng(\$handle_img);\n\n".
"// ...\n\x3f\x3e";
}

function sqlchr($buffer){
for($cuenta=0;$cuenta<strlen($buffer);$cuenta++){
$dump .= 'char('.ord($buffer[$cuenta]).')';
if((strlen($buffer) - 1) != $cuenta){
  $dump .= ',';
}
}
return $dump;
}

function sqldword($buffer){
return 'funcion(0x'.bin2hex($buffer).')';
}

function urlencode_total($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0;$cuenta<strlen($buffer);$cuenta+=2){
$dump .= '%'.$buffer[$cuenta].$buffer[$cuenta+1];
}
return $dump;
}

function unescape_javascript($buffer){
return '<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
document.write(unescape("'.urlencode_total($buffer).'"));
</SCRIPT>';
}

function php_encode($buffer){
$buffer = bin2hex(base64_encode(gzcompress($_POST['buffer'])));
$separador = 16; // Editable, separador de 16 bytes.
$separa = 0;
for($cuenta=0;$cuenta<strlen($buffer);$cuenta+=2){
if($separa == 0){
  $dump .= '"';
}
$dump .= '\x'.$buffer[$cuenta].$buffer[$cuenta+1];
$separa++;
if($separa == $separador){
  $dump .= '"';
  if($cuenta != (strlen($buffer))-2){
   $dump .= '.'."\n";
  }
  $separa = 0;
}
}
if($dump[strlen($dump)-1] != '"'){
$dump .= '"';
}
return
"\x3c\x3fphp\n// ...\n".
"/*\nRecuerda que no debes anteponer '\x3c\x3f' ni terminar con '\x3f\x3e'".
"Elimina este comentario.\n*/\n".
"eval(gzuncompress(base64_decode(\n$dump\n)));\n\n// ...\n\x3f\x3e";
}

function decodifica_base64_gz($buffer){
$buffer1 = str_replace('"',' ',$buffer);
$buffer1 = str_replace('.',' ',$buffer);
$buffer1 = explode('\x',$buffer);
$buffer1[0] = '';
for($cuenta=0;$cuenta<count($buffer1);$cuenta++){
if(strlen($buffer1[$cuenta]) == '2'){
  $buffer2 .= ' '.$buffer1[$cuenta];
  $procesando = true;
}else{
  if($procesando){
   $buffer2 .= ' '.$buffer1[$cuenta][0].$buffer1[$cuenta][1];
  }
}
}
$buffer2 = explode(' ',$buffer2);
for($cuenta=0;$cuenta<count($buffer2);$cuenta++){
if(strlen($buffer2[$cuenta]) == '2'){
  $buffer3 .= $buffer2[$cuenta];
}
}
return gzuncompress(base64_decode(hexa_a_str($buffer3)));
}

function ascii_a_sha1($buffer){
return sha1($buffer);
}

function hexa_a_str($buffer){
$buffer = preg_replace("/[^a-zA-Z0-9s]/", "", str_replace('\x',' ',$buffer));
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
$dump .= chr(hexdec($buffer[$cuenta].$buffer[($cuenta+1)]));
}
return $dump;
}

function ascii_a_decimal($buffer){
for($cuenta=0;$cuenta<strlen($buffer);$cuenta++){
$dump .= ord($buffer[$cuenta]).' ';
}
return $dump;
}

function ascii_a_html_sin_s($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
$dump .= '&#'.hexdec($buffer[$cuenta].$buffer[$cuenta+1]);
}
return $dump;
}

function ascii_a_html_con_s($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
$dump .= '&#x'.$buffer[$cuenta].$buffer[$cuenta+1].';';
}
return $dump;
}

function generar_htpasswd_sha($user,$pass){
return $user.':{SHA}'.base64_encode(sha1($pass, TRUE));
}

function generar_htpasswd_md5($user,$realm,$pass){
return $user.':'.md5($user.':'.$realm.':'.$pass);
}

function hexadecimal_a_decimal($buffer){
$buffer = preg_replace("/[^a-zA-Z0-9s]/", "", str_replace('\x',' ',$buffer));
for($cuenta=0; $cuenta<strlen($buffer); $cuenta++){
if(ctype_xdigit($buffer[$cuenta].$buffer[$cuenta+1])){
  $dump .= hexdec($buffer[$cuenta].$buffer[$cuenta+1]).' ';
  $cuenta++;
}
}
return $dump;
}

function octal_a_decimal($buffer){
$buffer = preg_replace("/[^0-9 s]/", "", $buffer);
$buffer = explode(' ',$buffer);
for($cuenta=0; $cuenta<(count($buffer)-1); $cuenta++){
$dump .= octdec($buffer[$cuenta]).' ';
}
return $dump;
}

function ascii_a_hexadecimal($buffer){
return chunk_split(bin2hex($buffer),2,' ');
}

function ascii_a_octal($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
$dump .= hexdec($buffer[$cuenta].$buffer[$cuenta+1]).' ';
}
$dump3 = explode(' ',$dump);
for($cuenta=0; $cuenta<(count($dump3)-1); $cuenta++){
$dump2 .= decoct($dump3[$cuenta]).' ';
}
return $dump2;
}

function debugger(){
global $dump;
if($dump){
echo htmlspecialchars($dump,ENT_QUOTES);
}else{
if($_POST['buffer'] and $_POST['algoritmo']){
echo "No hay datos que devolver";
}
}
}


Uso:
Código: php
<?php
// .. ..
$dump = ascii_a_png('Hola Elhacker.net'); // Procesa el String.
debugger(); // Imprime en pantalla el resultado evitando un XSS.
// .. ..
?>


Debido a una incompatibilidad de SMF con carácteres HTML como & y # las dos funciones
ascii_a_html_sin_s()
ascii_a_html_con_s()
No se ven como debieran. Deben aparecer de la siguiente manera:
Código: php
function ascii_a_html_sin_s($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
  $dump .= '&#'.hexdec($buffer[$cuenta].$buffer[$cuenta+1]);
}
return $dump;
}

function ascii_a_html_con_s($buffer){
$buffer = bin2hex($buffer);
for($cuenta=0; $cuenta<strlen($buffer); $cuenta+=2){
  $dump .= '&#x'.$buffer[$cuenta].$buffer[$cuenta+1].';';
}
return $dump;
}


bye

No tienes permitido ver los links. Registrarse o Entrar a mi cuenta