Ir ao conteúdo
  • Cadastre-se

PHP O código não funciona como o esperado (upload)


Posts recomendados

Problemas, galéra...

 

O funcionamento é simples. A pessoa seleciona uma imagem para enviar, preenche os campos obrigatórios e envia.Se não preencher os campos e selecionar uma imagem, é gerado um erro. Depois de clicar em submit, a imagem é enviada para o servidor e o nome, e-mail e todas as informações inseridas são enviadas para um arquivo de texto.

 

O problema

 

Mesmo sem enviar uma imagem, os dados são enviados para o TXT. Onde eu errei?

 

 


<?php


// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$sdn = 'bizarrepeoples.txt';
$current = file_get_contents($sdn);
$current .= serialize($_POST);
$current .= serialize($_FILES);
$current .= "\n\n\n\n\n";
file_put_contents($sdn, $current);

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["submit"]["name"]);


$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {

 
error_reporting(E_ERROR | E_PARSE | E_NOTICE);

    $check = getimagesize($_FILES["submit"]["tmp_name"]);
    if($check !== false) {

        echo "File is an image - " . $check["mime"] . ".";

        $uploadOk = 1;

    }  else {
        $uploadOk = 0;

        echo "File is not an image.";
    
exit();


    }


   

    
}

if (empty($_POST["name"])) {
    $nameErr = "O nome é obrigatório";
     $uploadOk = 0;
   
  } else {
    $name = test_input($_POST["name"]);
 }

 
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Apenas letras e espaços em branco são aceitos.";
   $uploadOk = 0;
 
}

if (empty($_POST["email"])) {
    $emailErr = "O email é obrigatório";
     $uploadOk = 0;
   
  } else {
    $email = test_input($_POST["email"]);
    
 }

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Formato inválido";
   $uploadOk = 0;
 
}
 

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "URL inválida";
     $uploadOk = 0;
}

  }

  if (empty($_POST["gender"])) {
    $genderErr = "Campo obrigatório";
         $uploadOk = 0;
  } else {
    $gender = test_input($_POST["gender"]);

  }


// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["submit"]["size"] > 10300000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
    
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
 
}


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {


    if (move_uploaded_file($_FILES["submit"]["tmp_name"], $target_file)) {
        echo "Obrigado por colaborar! A imagem ". basename( $_FILES["submit"]["name"]). " foi enviada.\n\nWe are bizarre!";
    } else {

exit('Obrigado por sua contribuição!=)');
         echo "Sorry, there was an error uploading your file.";
         

    }

}

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);

  }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;

}
?>

 

Link para o comentário
Compartilhar em outros sites

  • 2 meses depois...

Lerub, boa noite!!

 

Em 07/04/2019 às 23:28, Lerub disse:

file_put_contents($sdn, $current);

 

na linha acima você escreve no arquivo antes de verificar se a imagem foi enviada.

tente fazer essa checagem aqui.

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["submit"])) {

 

Link para o comentário
Compartilhar em outros sites

Olocow! Eu nem me lembrava desse tópico.=D

 

Eu deixei a page oculta até mudar toda a minha estratégia de marketing e aprender mais programação. Testarei isso.

 

Edit:

 

Fail! Eu fiz assim:

 


<?php


// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["submit"])) {

$sdn = 'bizarrepeoples.txt';
$current = file_get_contents($sdn);
$current .= serialize($_POST);
$current .= serialize($_FILES);
$current .= "\n\n\n\n\n";
file_put_contents($sdn, $current);

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["submit"]["name"]);


$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {

 
error_reporting(E_ERROR | E_PARSE | E_NOTICE);

    $check = getimagesize($_FILES["submit"]["tmp_name"]);
    if($check !== false) {

        echo "File is an image - " . $check["mime"] . ".";

        $uploadOk = 1;

    }  else {
        $uploadOk = 0;

        echo "File is not an image.";
    
exit();


    }


   

    
}

if (empty($_POST["name"])) {
    $nameErr = "O nome é obrigatório";
     $uploadOk = 0;
   
  } else {
    $name = test_input($_POST["name"]);
 }

 
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Apenas letras e espaços em branco são aceitos.";
   $uploadOk = 0;
 
}

if (empty($_POST["email"])) {
    $emailErr = "O email é obrigatório";
     $uploadOk = 0;
   
  } else {
    $email = test_input($_POST["email"]);
    
 }

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Formato inválido";
   $uploadOk = 0;
 
}
 

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "URL inválida";
     $uploadOk = 0;
}

  }

  if (empty($_POST["gender"])) {
    $genderErr = "Campo obrigatório";
         $uploadOk = 0;
  } else {
    $gender = test_input($_POST["gender"]);

  }


// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["submit"]["size"] > 10300000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
    
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
 
}


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {


    if (move_uploaded_file($_FILES["submit"]["tmp_name"], $target_file)) {
        echo "Obrigado por colaborar! A imagem ". basename( $_FILES["submit"]["name"]). " foi enviada.\n\nWe are bizarre!";
    } else {

exit('Obrigado por sua contribuição!=)');
         echo "Sorry, there was an error uploading your file.";
         

    }

}

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);

  }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;

}
?>

 

Resultado:

Citação

a:6:{s:4:"name";s:3:"rrr";s:5:"email";s:3:"rre";s:7:"website";s:0:"";s:7:"comment";s:16:"4r4ergrt4rtggtr4";s:6:"gender";s:11:"genderfluid";s:6:"submit";s:6:"Submit";}a:1:{s:6:"submit";a:5:{s:4:"name";s:0:"";s:4:"type";s:0:"";s:8:"tmp_name";s:0:"";s:5:"error";i:4;s:4:"size";i:0;}}

 

 

Eu deixei esse código de lado um pouco, pois, eu precisei focar em outras coisas. Eu nem mexi nele até então.

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...