elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  Cambiar los tipos de archivos permitidos
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Cambiar los tipos de archivos permitidos  (Leído 3,830 veces)
Antoniio

Desconectado Desconectado

Mensajes: 121



Ver Perfil
Cambiar los tipos de archivos permitidos
« en: 28 Mayo 2017, 08:12 am »

Hola, buenas. Tengo un código para subir archivos a una plataforma con extensión "jpg, rar, txt y zip" y quisiera saber cómo hago para cambiar esas extensiones permitidas por las siguientes: "mp4, mpeg, mwv", el código es el siguiente:
Código
  1.  <!-- ### FORM POST ### -->
  2.          <div class="box box-info">
  3.            <!-- form start -->
  4.            <form id="poster" class="form-horizontal">
  5.              <div class="box-body">
  6.                 <textarea id="thetextpost" name="posttext" class="form-control" rows="3"></textarea>
  7.              </div>
  8.              <!-- /.box-body -->
  9.            </form>
  10.  
  11.              <div class="box-footer">
  12.                <button class="btn btn-danger btn-sm pull-left" data-toggle="modal" data-target="#ModalDocumment"> <i class="fa fa-file-archive-o" aria-hidden="true"></i> Archivo</button>
  13.                <button class="posterbtn btn btn-info btn-sm pull-right"><i class="fa fa-pencil"></i> Publicar</button>
  14.              </div>
  15.              <!-- /.box-footer -->
  16.          </div>          
  17.          <!-- ### FORM POST ### -->
  18.  
  19.  
  20.  
  21.          <!-- ### COMMENT ### -->
  22.          <div id="timeliner">
  23.  
  24.          <?php takemylast6post(); ?>          
  25.  
  26.          </div>
  27.          <!-- ### COMMENT ### -->
  28.          <div id="loaderlinetime" class="col-sm-12 text-center">
  29.            <div class="loader-inner ball-pulse-sync"><div></div><div></div><div></div></div>
  30.          </div>
  31.  
  32.  
  33.  
  34.       </div>
  35.       <div id="sidebar" class="col-sm-3">
  36.           <?php include 'includes/adsense.html'; ?>
  37.       </div>
  38.     </div>
  39.     <!-- container -->
  40.  
  41.  
  42.     <!-- Modal -->
  43.     <div class="modal fade" id="ModalDocumment" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  44.       <div class="modal-dialog" role="document">
  45.         <div class="modal-content">
  46.           <div class="modal-header">
  47.             <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  48.             <h4 class="modal-title" id="myModalLabel"><i class="fa fa-upload" aria-hidden="true"></i> Subir Archivo</h4>
  49.           </div>
  50.           <div class="modal-body">
  51.  
  52.  
  53.              <div id="thefilattch" class="col-sm-12">
  54.                <form id="attachmentfrm">
  55.                  <label>Descripción:</label>
  56.                  <textarea class="form-control" name="descripcion" rows="3"></textarea>
  57.                  <label>Archivo:</label>
  58.                  <input type="file" name="archivo" class="form-control">
  59.                </form>
  60.  
  61.                <p></p>
  62.                <p>Solo se aceptan archivos con la extension: <?php validextlist(); ?></p>
  63.  
  64.              </div>
  65.              <!-- progress -->
  66.              <div id="loadeingarchive" class="progress active">
  67.                <div class="progress-bar progress-bar-primary progress-bar-striped" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
  68.                </div>
  69.              </div>
  70.              <!-- progress -->
  71.              <button type="button" class="uploadarchive btn btn-primary pull-right">Subir Archivo</button>
  72.  
  73.           </div>
  74.         </div>
  75.       </div>
  76.     </div>


Código
  1. // Sacamos las extensiones permitidas para los archivos que se suben
  2. function gettheextattachment(){
  3.  
  4.    // conexion de base de datos
  5.    $conexion = Conexion::singleton_conexion();
  6.  
  7.    $SQL = 'SELECT archiveextensions FROM '.SSPREFIX.'socialconfig WHERE id = 1';
  8.    $stn = $conexion -> prepare($SQL);
  9.    $stn -> execute();
  10.    $rstl = $stn -> fetchAll();
  11.    if (empty($rstl)){
  12.    }else{
  13.      foreach ($rstl as $key){
  14.        $fileext = $key['archiveextensions'];
  15.        return $fileext;
  16.      }
  17.    }
  18. }
  19.  
  20.  
  21. function validextlist(){
  22.  
  23.    // conexion de base de datos
  24.    $conexion = Conexion::singleton_conexion();
  25.  
  26.    $SQL = 'SELECT archiveextensions FROM '.SSPREFIX.'socialconfig WHERE id = 1';
  27.    $stn = $conexion -> prepare($SQL);
  28.    $stn -> execute();
  29.    $rstl = $stn -> fetchAll();
  30.    if (empty($rstl)){
  31.    }else{
  32.      foreach ($rstl as $key){
  33.         echo '<b>'.str_replace('|', ' / ', $key['archiveextensions']).'</b>';
  34.      }
  35.    }
  36.  
  37. }
  38.  
  39.  
  40. function formatSizeUnits($bytes){
  41.        if ($bytes >= 1073741824)
  42.        {
  43.            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
  44.        }
  45.        elseif ($bytes >= 1048576)
  46.        {
  47.            $bytes = number_format($bytes / 1048576, 2) . ' MB';
  48.        }
  49.        elseif ($bytes >= 1024)
  50.        {
  51.            $bytes = number_format($bytes / 1024, 2) . ' kB';
  52.        }
  53.        elseif ($bytes > 1)
  54.        {
  55.            $bytes = $bytes . ' bytes';
  56.        }
  57.        elseif ($bytes == 1)
  58.        {
  59.            $bytes = $bytes . ' byte';
  60.        }
  61.        else
  62.        {
  63.            $bytes = '0 bytes';
  64.        }
  65.  
  66.        return $bytes;
  67. }
  68.  
  69.  
  70. // Para subir un archivo
  71. function attachmentfiles($file,$description){
  72.  
  73.    // conexion de base de datos
  74.    $conexion = Conexion::singleton_conexion();
  75.  
  76.    // Primero el Año
  77.    $theyear = date('Y');
  78.  
  79.    // Ahora el Mes
  80.    $themonth = date ('m');
  81.  
  82.    // Ahora usamos la sesion del usuario para su respectiva carpeta
  83.    $theuser = $_SESSION['ssid'];
  84.  
  85.    // Creamos un alfanumerico aleatorio.
  86.    $characters = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  87.    $string = '';
  88.    for ($i = 0; $i < 60; $i++) {
  89.     $string .= $characters[rand(0, strlen($characters) - 1)];
  90.    }
  91.  
  92.    // Tomamos la fecha y hora con segundos
  93.    $fechaseconds = date('Y-m-d h:i:s');
  94.    $fechanormal =  date('Y-m-d');
  95.  
  96.    // Nuevo nombre del Archivo
  97.    $thenewname = sha1($fechaseconds.$theuser.$string);
  98.  
  99.    // Obtenemos la extension
  100.    $fileext = new SplFileInfo($file);
  101.    $getextension = $fileext->getExtension();
  102.  
  103.    // convertimos extension a minusculas
  104.    $extension = strtolower($getextension);
  105.  
  106.    //comprobamos si el archivo ha subido y lo movemos a una su respectiva ruta
  107.    if ($file && move_uploaded_file($_FILES['archivo']['tmp_name'],"../attachments/".$theuser."/".$theyear."/".$themonth."/".$thenewname.".".$extension)){
  108.    }  
  109.  
  110.    // Creamos ruta del temporal
  111.    $temporal = "../attachments/".$theuser."/".$theyear."/".$themonth."/".$thenewname.".".$extension;
  112.  
  113.  
  114.    // Creamos el permalink de la publicacion
  115.    $permalink = sha1($string.$fechaseconds);
  116.  
  117.  
  118.    // Limitamos las publicaciones a tan solo 1000 caracteres
  119.    $postparse = substr($description, 0,1000);
  120.  
  121.    // Filtramos para evitar XSS Injection
  122.    $filtro = new InputFilter();
  123.    $finalpost = $filtro->process($postparse);
  124.  
  125.    // Tamaño del archivo
  126.    $filesize = $_FILES['archivo']['size'];
  127.  
  128.    // Nombre del Archivo
  129.    $filename = $_FILES['archivo']['name'];
  130.  
  131.    // Revisamos si el resultado es vacio para no tener que postearlo
  132.    if (empty($finalpost)){
  133.       exit();
  134.    }
  135.  
  136.    if (is_null($finalpost)){
  137.       exit();
  138.    }
  139.  
  140.    // Hacemos el registro del Archivo
  141.    $FileAttch = 'INSERT INTO '.SSPREFIX.'attachment (ruta, nombre, usuario, fecha, ext, peso, permalink) VALUES (:ruta, :nombre, :usuario, :fecha, :ext, :peso, :permalink)';
  142.    $stnfile = $conexion -> prepare($FileAttch);
  143.    $stnfile -> bindParam(':ruta', $temporal ,PDO::PARAM_STR);
  144.    $stnfile -> bindParam(':usuario', $_SESSION['ssid'] ,PDO::PARAM_STR);
  145.    $stnfile -> bindParam(':nombre', $filename ,PDO::PARAM_INT);
  146.    $stnfile -> bindParam(':fecha', $fechaseconds ,PDO::PARAM_STR);
  147.    $stnfile -> bindParam(':ext', $extension ,PDO::PARAM_STR);
  148.    $stnfile -> bindParam(':peso', $filesize ,PDO::PARAM_STR);
  149.    $stnfile -> bindParam(':permalink', $thenewname ,PDO::PARAM_STR);
  150.    $stnfile -> execute();
  151.    $lastidfile = $conexion -> lastInsertId();
  152.  
  153.    // Post con archivo
  154.    $thepostpostarchive = $lastidfile.'|'.$finalpost;
  155.  
  156.    // Como es un post de archivo es 4
  157.    $tipo = 4;
  158.  
  159.    $SQL = 'INSERT INTO '.SSPREFIX.'posts (post, usuario, permalink, fecha, tipo) VALUES (:post, :usuario, :permalink, :fecha, :tipo)';
  160.    $stn = $conexion -> prepare($SQL);
  161.    $stn -> bindParam(':post', $thepostpostarchive ,PDO::PARAM_STR);
  162.    $stn -> bindParam(':usuario', $_SESSION['ssid'] ,PDO::PARAM_INT);
  163.    $stn -> bindParam(':permalink', $permalink ,PDO::PARAM_STR);
  164.    $stn -> bindParam(':fecha', $fechaseconds ,PDO::PARAM_STR);
  165.    $stn -> bindParam(':tipo', $tipo ,PDO::PARAM_INT);
  166.    $stn -> execute();
  167.    $lastid = $conexion -> lastInsertId();
  168.  
  169.    // imagen de perfil
  170.    $profileimg = userprofile($_SESSION['ssid']);
  171.  
  172.    // Fecha
  173.    $fechastronger = fechastring($fechanormal,$permalink);
  174.  
  175.    echo'
  176.        <div id="post-public'.$lastid.'" class="box box-widget">
  177.            <div class="box-header with-border">
  178.              <div class="user-block">
  179.                <img class="img-circle" src="'.$profileimg.'" alt="'.gettheusernamepost().'">
  180.                <span class="username"><a href="profile.php?leanserwebmaster">'.gettheusernamepost().'</a></span>
  181.                '.$fechastronger.'
  182.              </div>
  183.              <!-- /.user-block -->
  184.              <div class="box-tools">
  185.                <button data-post="'.$lastid.'" class="eliminarthispost btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
  186.              </div>
  187.              <!-- /.box-tools -->
  188.            </div>
  189.            <!-- /.box-header -->
  190.            <div class="box-body">
  191.              <!-- post text -->';
  192.  
  193.                $postexplode = explode('|', $thepostpostarchive);
  194.                getattachblock($postexplode[0],$postexplode[1]);
  195.  
  196.         echo'<!-- Social sharing buttons -->
  197.              <button id="liker'.$lastid.'" type="button" data-target="'.$lastid.'" onclick="thelikeloadtimeclick('.$lastid.');" class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Me gusta</button>
  198.              <span id="likecomment'.$lastid.'" class="pull-right text-muted">
  199.  
  200.              </span>
  201.            </div>
  202.  
  203.            <!-- /.box-footer -->
  204.            <div class="box-footer">
  205.              <form class="commentfrm" data-form="'.$lastid.'" id="commentfrm'.$lastid.'">
  206.                <img  id="mypiccomment" class="img-responsive img-circle img-sm" src="'.$profileimg.'">
  207.                <!-- .img-push is used to add margin to elements next to floating images -->
  208.                <div class="img-push">
  209.                  <input type="text" class="form-control input-sm" name="comentario" placeholder="Comentar...">
  210.                </div>
  211.              </form>
  212.            </div>
  213.            <!-- /.box-footer -->
  214.  
  215.            <!-- /.box-body -->
  216.            <div id="box-commets-body-'.$lastid.'" class="box-footer box-comments">
  217.  
  218.            </div>
  219.  
  220.          </div>
  221.    ';
  222.  
  223.  
  224.    $conexion = '';
  225.  
  226.  
  227.  
  228. }
  229.  
  230.  
  231.  
  232. function downloadarchive($permalink){
  233.  
  234.     // conexion de base de datos
  235.     $conexion = Conexion::singleton_conexion();
  236.  
  237.     $SQL = 'SELECT * FROM '.SSPREFIX.'attachment WHERE permalink = :permalink LIMIT 1';
  238.     $stn = $conexion -> prepare($SQL);
  239.     $stn -> bindParam(':permalink', $permalink ,PDO::PARAM_STR);
  240.     $stn -> execute();
  241.     $rstl = $stn -> fetchAll();
  242.     if (empty($rstl)){
  243.       header('Location: 404.php');
  244.     }else{
  245.       foreach ($rstl as $key){
  246.          $ruta = str_replace('../', '', $key['ruta']);
  247.          $nombre = $key['nombre'];
  248.       }
  249.     }
  250.  
  251.     header("Content-type: application/octet-stream");
  252.     header("Content-Type: application/force-download");
  253.     header("Content-Disposition: attachment; filename=\"$nombre\"\n"); readfile($ruta);
  254.  
  255.  
  256. }
  257.  
  258.  
  259.  
  260.  
  261.  
  262. // Tomamos los ultimos 6 post
  263. function takepostperpermalink($permalink){
  264.  
  265.    // conexion de base de datos
  266.    $conexion = Conexion::singleton_conexion();
  267.  
  268.  
  269.    $SQL = 'SELECT '.SSPREFIX.'usuarios.id AS userid, '.SSPREFIX.'posts.tipo AS posttipo, '.SSPREFIX.'posts.id AS postingid, '.SSPREFIX.'posts.post, '.SSPREFIX.'posts.permalink, '.SSPREFIX.'posts.fecha, '.SSPREFIX.'usuarios.nombre, '.SSPREFIX.'usuarios.apellido, '.SSPREFIX.'usuarios.permalink AS userperma FROM '.SSPREFIX.'posts INNER JOIN '.SSPREFIX.'usuarios ON '.SSPREFIX.'usuarios.id = '.SSPREFIX.'posts.usuario WHERE '.SSPREFIX.'posts.permalink = :permalink ORDER BY '.SSPREFIX.'posts.fecha DESC LIMIT 1';
  270.    $stn = $conexion -> prepare($SQL);
  271.    $stn -> bindParam(':permalink' , $permalink, PDO::PARAM_INT);
  272.    $stn -> execute();
  273.    $rstl = $stn -> fetchAll();
  274.    if (empty($rstl)){
  275.      # code...
  276.    }else{
  277.      foreach ($rstl as $key){
  278.  
  279.  
  280.        // imagen de perfil
  281.        $profileimg = userprofile($key['userid']);
  282.  
  283.        // Fecha
  284.        $fecha = fechastring($key['fecha'],$key['permalink']);
  285.  
  286.        // Imagen de perfil en el post
  287.        $perfilactual = userprofile($_SESSION['ssid']);
  288.  
  289.  
  290.        echo'
  291.  
  292.        <div id="post-public'.$key['postingid'].'" class="box box-widget">
  293.            <div class="box-header with-border">
  294.              <div class="user-block">
  295.                <img class="img-circle" src="'.$profileimg.'" alt="'.$key['nombre'].' '.$key['apellido'].'">
  296.                <span class="username"><a href="profile.php?'.$key['userperma'].'">'.$key['nombre'].' '.$key['apellido'].'</a></span>
  297.                '.$fecha.'
  298.              </div>
  299.              <!-- /.user-block -->
  300.            </div>
  301.            <!-- /.box-header -->
  302.            <div class="box-body">
  303.              <!-- post text -->';
  304.  
  305.              if ($key['posttipo'] == 1){
  306.                profileimageposttake($key['post']);
  307.              }elseif ($key['posttipo'] == 3) {
  308.                portadaimageposttake($key['post']);
  309.              }elseif ($key['posttipo'] == 4) {
  310.  
  311.                $postexplode = explode('|', $key['post']);
  312.                getattachblock($postexplode[0],$postexplode[1]);
  313.  
  314.              }else{
  315.                echo'<p>'.emoticons($key['post']).'</p>';
  316.              }
  317.  
  318.              echo'<!-- Social sharing buttons -->
  319.              ';
  320.  
  321.              checklike($key['postingid']);
  322.  
  323.              echo'
  324.  
  325.              <span id="likecomment'.$key['postingid'].'" class="pull-right text-muted">
  326.                 ';
  327.  
  328.                      checklikeandcomments($key['postingid']);
  329.  
  330.                 echo'
  331.              </span>
  332.            </div>
  333.  
  334.            <!-- /.box-footer -->
  335.            <div class="box-footer">
  336.              <form class="commentfrm" data-form="'.$key['postingid'].'" id="commentfrm'.$key['postingid'].'">
  337.                <img  id="mypiccomment" class="img-responsive img-circle img-sm" src="'.$perfilactual.'">
  338.                <!-- .img-push is used to add margin to elements next to floating images -->
  339.                <div class="img-push">
  340.                  <input type="text" class="form-control input-sm" name="comentario" placeholder="Comentar...">
  341.                </div>
  342.              </form>
  343.            </div>
  344.            <!-- /.box-footer -->
  345.  
  346.            <!-- /.box-body -->
  347.            <div id="box-commets-body-'.$key['postingid'].'" class="box-footer box-comments">';
  348.  
  349.               commentsajx($key['postingid'],$key['permalink']);
  350.  
  351.             echo'</div>
  352.          </div>
  353.  
  354.        ';
  355.  
  356.      }
  357.    }
  358.  
  359.  
  360.    $conexion = '';
  361.  
  362. }

Gracias de antemano, saludos !!


En línea

Alej

Desconectado Desconectado

Mensajes: 14



Ver Perfil
Re: Cambiar los tipos de archivos permitidos
« Respuesta #1 en: 28 Mayo 2017, 09:17 am »

Citar
Hola, buenas. Tengo un código para subir archivos a una plataforma con extensión "jpg, rar, txt y zip" y quisiera saber cómo hago para cambiar esas extensiones permitidas por las siguientes: "mp4, mpeg, mwv", el código es el siguiente

En la funcion:

Código:
validextlist()

Indica que dichas extensiones permitidas se ubican en "SELECT archiveextensions FROM '.SSPREFIX"

En "archiveextensions" edita las extensiones que quieres,y listo.


En línea

Antoniio

Desconectado Desconectado

Mensajes: 121



Ver Perfil
Re: Cambiar los tipos de archivos permitidos
« Respuesta #2 en: 28 Mayo 2017, 17:53 pm »

Ya lo encontré:
Código
  1.  
  2.    // Incluimos las funciones del sistema
  3.    require_once '../administrator/ss-functions.php';
  4.  
  5.  
  6.    // Revisamos si existe la sesion o si es valida
  7.    isuserajax();
  8.  
  9.    // Si el posttext es vacio
  10.    if (empty($_POST['descripcion'])){exit();}
  11.  
  12.  
  13.    // Si es un espacio
  14.    if (ctype_space($_POST['descripcion'])){exit();}
  15.  
  16.    // Primero el Año
  17.    $theyear = date('Y');
  18.  
  19.    // Ahora el Mes
  20.    $themonth = date ('m');
  21.  
  22.    // creamos directorio para el usuario el año
  23.    if(!is_dir("../attachments/".$_SESSION['ssid']))
  24.        mkdir("../attachments/".$_SESSION['ssid'], 0777);
  25.  
  26.    // creamos directorio para el usuario
  27.    if(!is_dir("../attachments/".$_SESSION['ssid']."/".$theyear))
  28.        mkdir("../attachments/".$_SESSION['ssid']."/".$theyear, 0777);    
  29.  
  30.  
  31.    // creamos directorio para el usuario el mes
  32.    if(!is_dir("../attachments/".$_SESSION['ssid']."/".$theyear."/".$themonth))
  33.        mkdir("../attachments/".$_SESSION['ssid']."/".$theyear."/".$themonth, 0777);
  34.  
  35.  
  36.    //obtenemos el archivo a subir
  37.    $file = $_FILES['archivo']['name'];
  38.  
  39.    // Obtenemos la extension
  40.    $fileext = new SplFileInfo($file);
  41.    $getextension = $fileext->getExtension();
  42.  
  43.    // convertimos extension a minusculas
  44.    $extension = strtolower($getextension);
  45.  
  46.    // Aqui sacamos la lista de extensiones
  47.    $extensionlst = gettheextattachment();
  48.  
  49.    // Aqui hacemos un explode para cada uno
  50.    $extexplode = explode("|", $extensionlst);
  51.  
  52.    // Contamos el total de extensiones
  53.    $exttotal = count($extexplode);
  54.  
  55.  
  56.    for ($i=0; $i < $exttotal; $i++) {
  57.  
  58.       if($extension === $extexplode[$i]){
  59.           attachmentfiles($file,$_POST['descripcion']);
  60.           exit();
  61.       }
  62.  
  63.    }
  64.  

Pero no entiendo cómo modificar las extensiones de ahí...

Saludos.
« Última modificación: 28 Mayo 2017, 17:56 pm por Antoniio » En línea

Antoniio

Desconectado Desconectado

Mensajes: 121



Ver Perfil
Re: Cambiar los tipos de archivos permitidos
« Respuesta #3 en: 29 Mayo 2017, 17:26 pm »

 :-(
En línea

Antoniio

Desconectado Desconectado

Mensajes: 121



Ver Perfil
Re: Cambiar los tipos de archivos permitidos
« Respuesta #4 en: 30 Mayo 2017, 20:10 pm »

Ya lo resolví, saludos !!
« Última modificación: 12 Junio 2017, 06:32 am por Antoniio » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Dudas sobre tipos de archivos .bat
Scripting
Decarkaim 4 4,058 Último mensaje 11 Agosto 2010, 16:07 pm
por Decarkaim
[AutoIt] Buscador de textos en varios tipos de archivos.
Scripting
Chefito 0 4,176 Último mensaje 24 Agosto 2011, 03:49 am
por Chefito
aguien ya save los 2 tipos de archivos que maneja java
Java
miguelsora 0 1,670 Último mensaje 15 Mayo 2013, 01:34 am
por miguelsora
Agregar ejecutable a lista de permitidos del AV « 1 2 3 »
Análisis y Diseño de Malware
Vaagish 22 13,378 Último mensaje 2 Diciembre 2013, 16:44 pm
por Vaagish
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines