Upload Change

Asked

Viewed 58 times

1

I am developing a system with Upload files in PHP and in the case of inserting files in the form by Upload, the user can also delete files and include new attachments in Upload but these two cases are not working right.

Below is the file that makes the Adm of the records and the PHP part that will make all this change.

File for changing the record.

 <? 
#incluir arquivos de conexão e funções 
include "../UTILS/conexao.php";
//include_once "../UTILS/funcoes_usr.php";
#definir o char-set da página 
setlocale(LC_ALL,"pt_BR"); 
header('Content-type: text/html; charset=windows-1252');    
set_time_limit(120); //Tempo limite de execução 
ERROR_REPORTING (E_ERROR); //Exibe somente erros fatais 

#Variáveis de Data e Hora   
$dataAt = date('d/m/Y');    
$horaAt = date('H:i:s');

$inserir = 0;   

$usuario = strtolower($_SERVER["LOGON_USER"]);
$usuario_1 = split('\\\\', $usuario);
$usuario = $usuario_1[1];

//variaveis para execução do SQL 
SQL(); 
global $sql; 

$idd = $_REQUEST["id"];//Varíavel para buscar o campo id do registro 

 //echo "O ID para alteração é o: ".$idd; 
//echo "<BR><BR>"; 

 #Cria a consulta inicial 
 $altEve = "SELECT [id],[mudanca],[tarefa]
,[descricao],[ambiente],[empresa],[reg_afet]
,[sist_afet],[hw_afet],[host_name],[serv_afet]
,[conclusao],[obs],[data_exec],[obs2],[upload]
 FROM [Passagem].[dbo].[tb_eventos_relev_tst] WHERE ID= $idd"; 

 //echo $altPas;
//echo "<BR>";

 #realiza a busca pelos dados do registro 
 $result = $sql->execute($altEve); 
   if($tbl = $result) 
    { 
        $codigo = $tbl["id"];
        $codigo = $tbl["mudanca"];
        $codigo = $tbl["tarefa"];
        $codigo = $tbl["descricao"];
        $codigo = $tbl["ambiente"];
        $codigo = $tbl["empresa"];
        $codigo = $tbl["reg_afet"];
        $codigo = $tbl["sist_afet"];
        $codigo = $tbl["hw_afet"];
        $codigo = $tbl["host_name"];
        $codigo = $tbl["serv_afet"];
        $codigo = $tbl["conclusao"];
        $codigo = $tbl["obs"];
        $codigo = $tbl["obs2"];
        $codigo = $tbl["data_exec"];
        $codigo = $tbl["upload"];
        } 
else 
    { echo "Registro não localizado"; } 

#Inicia o tratamento dos registros      
while (!$result -> EOF) { 
    $id = $result->Fields['id']->Value; 
    $mudanca = $result->Fields['mudanca']->Value;   
    $tarefa = $result->Fields['tarefa']->Value;     
    $descricao = $result->Fields['descricao']->Value;   
    $ambiente = $result->Fields['ambiente']->Value;     
    $empresa = $result->Fields['empresa']->Value;   
    $reg_afet = $result->Fields['reg_afet']->Value;     
    $sist_afet = $result->Fields['sist_afet']->Value;   
    $hw_afet = $result->Fields['hw_afet']->Value;   
    $host_name = $result->Fields['host_name']->Value;   
    $serv_afet = $result->Fields['serv_afet']->Value;   
    $conclusao = $result->Fields['conclusao']->Value;   
    $obs = $result->Fields['obs']->Value;   
    $data_exec = $result->Fields['data_exec']->Value;   
    $obs2 = $result->Fields['obs2']->Value;     
    $upload = $result->Fields['upload']->Value;     


    $dataEx = substr($data_exec, 8,2)."/".substr($data_exec,5,2)."     /".substr($data_exec, 0,4);


    //echo "<BR>";
    $uploadExi = explode(' , ',$upload); 
     //foreach($uploadExi as $valores) 
        //{ 
            //echo $valores.'<BR>'; 
        //}


    #Move para o registro seguinte
    $result->MoveNext();

  }
 ?> 
 <html> 
    <head>
       <title>Eventos relevantes - CGR</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
    <meta name="authors" content="CGR - Governança"/>
    <link rel="StyleSheet" type="text/css" href="../CSS/Paginas.css"> 
    <script type="text/javascript" charset="utf-8" src="../JS/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="../JS/jQuery-Mask-Plugin-master/dist/jquery.mask.min.js"></script>
    </head>
<body> 
<fieldset> 

        <?
            //echo "Data".$data_exec."<BR>"; 

            //echo "Data".$dataEx."<BR>"; 

            $dataExec = $dataEx;

            //echo "Data".$dataExec."<BR>";     

        ?>

        <form name="formEventos" method="POST" action="../UTILS/registra2.php">

        <!-- ID -----Hidden --> 
        <input type="hidden" name="eveId" value="<? echo $id; ?>">  


        <!--Mudança-->
        <p>
            <label for="idMudanca">Mudança:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveMudanca" id="idMudanca" class="medio" placeholder="Nº Mudança" value="<?=$mudanca;?>"/>  
        </p><br>

        <!--Tarefa-->   
        <p> 
            <label for="idTarefa">Tarefa:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
            <input type="text" name="eveTarefa" id="idTarefa" class="medio" placeholder="Nº Tarefa" value="<?=$tarefa;?>"/> 
        </p><br>

        <!--Descrição-->                
        <p> 
            <label for="idDescricao">Descrição:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveDescricao" id="idDescricao" class="medio" placeholder="Descrição do evento" required value="<?=$descricao?>" /> 
        </p><br>

        <!--Plataforma-->
        <p> 
            <label for="idAmbiente">Ambiente:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <select name="eveAmbiente" id="idAmbiente" class="medio"> 
                <option value="<?=$ambiente;?>"><?=$ambiente;?></option>
                <option value="">Selecione ...</option>
                <option value="Backbone">Backbone</option>
                <option value="Extranet">Extranet</option>
                <option value="Rede de acesso">Rede de Acesso</option>
                <option value="Lotéricos">Lotéricos</option>
                <option value="PAE">PAE</option>
                <option value="Rede 1">Rede 1</option>
                <option value="Rede 2">Rede 2 </option>
                <option value="Rede 3">Rede 3</option>
                <option value="Rede 4">Rede 4</option>
                <option value="Rede 5">Rede 5</option>
                <option value="Rede 6">Rede 6</option>
            </select>   
        </p><br>

        <!--Empresa-->              
        <p> 
            <label for="idEmpresa">Empresa:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveEmpresa" id="idEmpresa" class="medio" placeholder="Empresa" value="<?=$empresa;?>"/> 
        </p><br>

        <!--Região afetada-->
        <p> 
            <label for="idRegAfet">Região Afetada:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveRegAfet" id="idRegAfet" class="medio" placeholder="Região Afetada" value="<?=$reg_afet;?>"/> 
        </p><br>

        <!--Sistema afetado-->
        <p> 
            <label for="idSistAfet">Sistema Afetado:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;                    
            <input type="text" name="eveSistAfet" id="idSistAfet" class="medio" placeholder="Sistema Afetado" value="<?=$sist_afet;?>"/>
        </p><br>

        <!--Hardware afetado-->
        <p> 
            <label for="idHardAfet">Hardware Afetado:</label>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveHardAfet" id="idHardAfet" class="medio" placeholder="Hardware Afetado" value="<?=$hw_afet;?>"/>                 
        </p><br> 

        <!--Hostname-->
        <p> 
            <label for="idHostname">Hostname:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
            <input type="text" name="eveHostname" id="idHostname" class="medio" placeholder="Hostname" value="<?=$host_name;?>"/>                   
        </p><br>

        <!--Serviço Afetado-->
        <p> 
            <label for="idServAfet">Serviço Afetado:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;    
            <input type="text" name="eveServAfet" id="idServAfet" class="medio" placeholder="Serviço Afetado" value="<?=$serv_afet;?>"/>                    
        </p><br>


        <p>
            <label for="idDataExec">Data de execução:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
            <input type="text" name="eveDataExec" id="idDataExec" value="<?=$dataExec; ?>" class="medio" />
            <!--<script type="text/javascript">$("#idDataExec").mask("00/00/0000");</script>-->
        </p><br>

        <p> 
            <label for="idConcluido">Concluído com Sucesso:</label>
            <select name="eveConcluido" id="idConcluido" class="medio">
                <option value="<?=$conclusao; ?>"><?=$conclusao; ?></option>
                <option value="">Selecione..</option>
                <option value="Sim">Sim</option>
                <option value="Não">Não</option>
                <option value="Parcialmente">Parcialmente</option>
                <option value="Cancelada">Cancelada</option>
                <option value="Abortada">Abortada</option>
            </select>
        </p><br> 

        <p> 
            <label for="idObservacao">Observação</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <textarea name="eveObservacao" id="idObservacao" rows="4" cols="60"><?=$obs;?></textarea>
        </p><br> 

        <p> 
            <label for="idObservacao2">Observação 2:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <textarea name="eveObservacao2" id="idObservacao2" rows="4" cols="60"><?=$obs2;?></textarea>
        </p><br> 


        <p>

            <form method="post" action="../UTILS/registra2.php">
            <label>Anexo:</label>
                <input type="hidden" name="hidId" id="idHidId" value="<?=$id;?>"/>
                <input type="hidden" name="eveArquivoAntigo" id="idArquivoAntigo" value="<? echo $upload; ?>" /> 
            <? 
                if($upload == '' || $upload == 'Sem arquivo anexo') { 
                    echo 'Não existem arquivos anexos para este registro'; 
                } else { 
                    foreach($uploadExi as $valores)   { 
                        echo '<a href="../UTILS/' . $valores . '" target="_blank" >'.$valores.'</a>&nbsp;&nbsp;
                        <input type="text" name="hidValor" value="'.$valores.'"/>
                        <input type="submit" name="ExcluirAnexo" value="Excluir Anexo" class="botaoExc"><BR>
                        '; //disabled
                } 
            ?>


            <?  
            }       
            ?>
            </form>


        </p><br>

        <p> 
            <label for="idArquivo">Incluir novo anexo:</label>
            <input type="file" name="eveArquivo[]" id="idArquivo" disabled />
        </p><br>


        <p> 
            <input type="hidden" name="eveUsr" value="<?=$usuario; ?>" />
        </p>        


        <input type="submit" name="acao" value="Alterar" name="Alterar" class="botao"/>



        </form> 

        </fieldset>     
        </body>
        </html>

And now the record management part

  //Variáveis que serão usadas para tratar o upload de arquivo 
  if($_FILES['eveArquivo']['size'] == 0){
   $anexado = 'Sem arquivo anexo'; 
   } else {
   $total = count($_FILES['eveArquivo']['name']);

   for($i=0; $i<$total; $i++) {

   $diretorio = 'Uploads/';//diretório onde serão armazenados os arquivos
    //echo $diretorio."(dir)<BR>"; 

    $nome = basename($_FILES['eveArquivo']['name'][$i]);
    //echo $nome."(nome)<BR>";  


    $file = preg_replace('/\\.[^.\\s]{3,4}$/','',$nome); 
   //echo $file."(file)<BR>";

   $saida = preg_replace('/[^a-z0-9]/i','',$file);
   //echo $saida."(exit)<BR>";  

   $ext = strtolower(end(explode('.',$_FILES['eveArquivo']['name'][$i])));//nome da extensao
    //echo $ext."(ext)<BR>";    

    $nomeFinal = $diretorio.$saida.'.'.$ext; 
    //echo $nomeFinal."<BR>"; 

   //$_SESSION['eveArquivo'] = $file;  

    $uploadOk = 1; 
    $fileType = array('doc', 'docx', 'xls', 'xlsx','odt', 'ods', 
    'jpeg', 'jpg', 'png', 'msg', 'pdf', 'txt','htm', 'html', 'csv');//Extensões permitidas

    $maxsize = 1024 * 1024 * 9; //Tamanho máximo do arquivo 


       if($_FILES['eveArquivo']['size'][$i] > $maxsize) { 
       echo "
       <span> 
        Arquivo muito grande. Permitido somente arquivo de até 9,40Mb)  
       </span>  
       $uploadOk = 0; 
       } 

      //echo $_FILES['eveArquivo']['size'];
     //echo "<BR>";

      #Permite os formatos 
      $extensao = strtolower(end(explode('.', $_FILES['eveArquivo']['name'][$i])));
    //echo $extensao;
   //echo "<BR>";

   if(array_search($extensao, $fileType) === false) { 
   echo "
    <span> 
        Por favor, envie arquivos com as seguintes extensões: doc, docx,              xls,
        xlsx, odt, ods, jpeg, jpg, png, msg, pdf, txt, htm, html ou csv.    
    </span>
     "; 
     $uploadOk = 0; 
     } 



    //Checa se o Upload não foi carregado por um erro 
    if($uploadOk == 0) { 
    echo "Seu arquivo não pode ser carregado."; 
    echo "<BR>"; 
    } else { 
    if(move_uploaded_file($_FILES['eveArquivo']['tmp_name'][$i], $nomeFinal)) { 
        echo "<BR>";                
        echo "O arquivo ". basename($_FILES['eveArquivo']['name'][$i]). " foi carregado."; 
        echo "<BR>";

        } else { 
        echo "Ocorreu um erro ao carregar o arquivo."; 
        echo "<BR>";    
        } 
        }

       $fileExi[] = $nomeFinal; 
      //echo $fileExi." fileExi";
      //echo "<BR><BR>"; 


     $anexado = implode(' , ',$fileExi);    
     //echo $anexado." anexado";

     } } 


     //Cria a função para escolher a ação 
     function get_post_action($name) 
      { 
       $params = func_get_args(); 

        foreach($params as $name) { 
        if(isset($_POST[$name])) { 
            return $name; 
        }   

    }

} 

        /*Aqui vai a parte de Incluir que está OK ae tirei do código, deixei só o alterar e a exclusão de um arquivo de Upload */

         //Alterar registro
         case 'Alterar': 
        $id = $_REQUEST["eveId"]; //Campo hidden que será utilizado para atualização do registro 
        //$dataE = $_REQUEST["eveDataExec"];
    //echo $dataE; echo "<BR>";
    //$dataExec = date('Y-m-d',strtotime($dataE));



     //Incluir novo anexo 
     if($_REQUEST["eveDataExec"] == '') 
        {  
            $dataExec == ''; } else 
        {   
            $dataExec = $_REQUEST["eveDataExec"];
            $dataExec = substr($dataExec, 6,4)."-".substr($dataExec, 3,2)."-".substr($dataExec, 0,2);
        }

        //Procedimento interno para qualquer tipo de alteração dos arquivos anexos 
        $anexoAntigo = "SELECT [upload] FROM [dbo].[tb_eventos_relev_tst] WHERE [id] ='".$id."'"; //AnexoAntigo

        //Executa a consulta 
        $res = $sql->execute($anexoAntigo); 
        $aneOld = $res->Fields['upload']->Value; 

        echo $anexado."<BR>";   

        $newAnexo = $aneOld.' , '.$anexado; 
        echo $newAnexo."<BR>"; 

         $dataExec = $_REQUEST["eveDataExec"];
         $dataExec = substr($dataExec, 6,4)."-".substr($dataExec,   3,2)."-".substr($dataExec, 0,2);


          $updateEvento = "UPDATE [dbo].[tb_eventos_relev_tst] SET"; 
         $updateEvento .= "[mudanca] =    '".$_REQUEST["eveMudanca"]."',";  
          $updateEvento .= "[tarefa] = '".$_REQUEST["eveTarefa"]."',";  
          $updateEvento .= "[descricao] = '".$_REQUEST["eveDescricao"]."',";    
          $updateEvento .= "[ambiente] = '".$_REQUEST["eveAmbiente"]."',";  
          $updateEvento .= "[empresa] = '".$_REQUEST["eveEmpresa"]."',";    
          $updateEvento .= "[reg_afet] = '".$_REQUEST["eveRegAfet"]."',";   
          $updateEvento .= "[sist_afet] = '".$_REQUEST["eveSistAfet"]."',";     
          $updateEvento .= "[hw_afet] = '".$_REQUEST["eveHardAfet"]."',";   
          $updateEvento .= "[host_name] = '".$_REQUEST["eveHostname"]."',";     
          $updateEvento .= "[serv_afet] = '".$_REQUEST["eveServAfet"]."',";     
          $updateEvento .= "[conclusao] = '".$_REQUEST["eveConcluido"]."',";    
          $updateEvento .= "[obs] = '".$_REQUEST["eveObservacao"]."',";     
          $updateEvento .= "[obs2] = '".$_REQUEST["eveObservacao2"]."',"; 
          $updateEvento .="[upload] ='".$newAnexo."',";     
          $updateEvento .= "[usr_alt] = '".$_REQUEST["eveUsr"]."',";
          $updateEvento .= "[data_exec] = '".$dataExec."'";
          $updateEvento .= " WHERE [id] = '".$id."'"; 

          echo $updateEvento; 
          echo "<BR>";
          $result = $sql->execute($updateEvento);

          echo "
          <p style='font-size: 15px; color: #000080;'>Registro alterado           com sucesso!!!!</p>
          <br><p><a href='../FILES/alterar_even_tst.php?id=$id'>Clique aqui para alterar o registro</a></p>
           <br>";   

           break;

        //Exclusão de Anexo 
          case 'ExcluirAnexo':  
            $idPag = $_REQUEST['eveId'];//Id da página
            $id = $_REQUEST['hidId']; //Busca campo ID na página 
            echo $id."<BR>";
            $excAnexo = $_REQUEST["hidValor"];
            echo $encAnexo."<BR>";
            //Efetua a consulta no banco 
            $consulta = "SELECT [upload] FROM [dbo].[tb_eventos_relev_tst] REPLACE ('$encAnexo','$encAnexo','') WHERE [id]=$id";
            echo $consulta."<BR>";  
            //Executa a consulta
            //$result = $sql->execute($consulta); 
            //Exibe o resultado 
            echo "O arquivo $encAnexo foi excluído com sucesso<BR>"; 
            echo "<br><p><a href='../FILES/alterar_even_tst.php?id=$idPag'>Clique aqui para voltar a tela de alteração</a></p>";
        break;

Good in case is not working removing files and also not working while placing a new upload...


In case in the file change, I have the two buttons to change and to delete attachment... when I click change, all fields is carried out the Update less in the upload file getting as No file attachment.

For the code to delete the attached file I used a replica, replacing the text part in SQL to empty, but it’s also not working...it recognizes everything as empty.

  • Just so I understand your question better, you’re putting all the validation on the server side?

  • Explain the "they’re not working right".

  • When I want to place a new Upload, it always returns as empty by neither uploading the file nor placing the path String in the database. And remove it, it always brings the variable as empty not removing part of the String in the database.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.