简体   繁体   中英

Upload file not working if checking for uploaded files is on the code

The images are uploading normally, but I want an "else if" to check if there is any file selected. This is working:

    <?php
session_start();
    include('includes/conexao.php');
    $fileinfo=PATHINFO($_FILES["image"]["name"]);
    $newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
    $location="images/perfis/" . $newFilename;

$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");

if( mysqli_num_rows($todas_fotos) > 0) {
        //$path=$location;
        //if(unlink($path)) echo "Deleted file ";
        mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}
else if( mysqli_num_rows($todas_fotos) == 0)
{
        mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
else {

};
    header('location:perfil.php');
?>

It inserts if there isn't an image, but if there is, it updates. But when I add:

else if (empty($_FILES['image']['name']))
{
header('location:perfil.php');
}

It returns me undefined index: extension on line 5. How to go?

Rewrite the code as follows. Here we are checking whether the file is not available at the beginning of the code and redirect if no file is found.

<?php
session_start();
if (empty($_FILES['image']['name']))
{
  header('location:perfil.php?error=1');
  return;
}
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;

$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE 
img_usu_codigo = '" . $_SESSION['codigo'] . "'");

if( mysqli_num_rows($todas_fotos) > 0) {
    //$path=$location;
    //if(unlink($path)) echo "Deleted file ";
    mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
 }else {
    mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
 }

and in the perfil.php you should put

window.onload = function(){ var url = new URL(window.location.href); var error = url.searchParams.get("error"); if(error==1) alert("No file uploaded");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM