简体   繁体   中英

Alert error message gets displayed multiple times

The code is shown below:

    if(isset($_FILES['hiddenfilebutton'])){
            $img_name = $_FILES['hiddenfilebutton']['name'];
            $img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
            $a = explode('.',$img_name);
            $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
            $img_extension = strtolower(end($a));
            unset($a);
            $img_size = $_FILES['hiddenfilebutton']['size'];
            if($img_size > 3000000) {
                $error = 'Image should be less than 4 MB';
            } else if(!in_array($img_extension, $allowed_ext)) {
                $error = "Unsupported image format";
            }
        }
    ?>
    <script type="text/javascript">
        if('<?php echo $error; ?>' != '' && '<?php echo $error; ?>' != undefined) {
            alert("<?php echo $error; ?>");
        }
    </script>

Problem is that whenever I upload an unsupported image type like a .tiff image, the alert box gets displayed. This works the way I want it to work. But if i reload it, then it displays the alert box once again with the same message. It doesn't show up the third time I reload. I want alert message to show up only once, not twice or thrice..

change code to:

<?php 

if(isset($_FILES['hiddenfilebutton'])){
        $img_name = $_FILES['hiddenfilebutton']['name'];
        $img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
        $a = explode('.',$img_name);
        $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
        $img_extension = strtolower(end($a));
        unset($a);
        $img_size = $_FILES['hiddenfilebutton']['size'];
        if($img_size > 3000000) {
            $error = 'Image should be less than 4 MB';
        } else if(!in_array($img_extension, $allowed_ext)) {
            $error = "Unsupported image format";
        }
    }

if(isset($error)){
?>
    <script type="text/javascript">
        alert("<?php echo $error; ?>");
    </script>
<?php
} 
?>

OR

<?php 

 if(isset($_FILES['hiddenfilebutton'])){
        $img_name = $_FILES['hiddenfilebutton']['name'];
        $img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
        $a = explode('.',$img_name);
        $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
        $img_extension = strtolower(end($a));
        unset($a);
        $img_size = $_FILES['hiddenfilebutton']['size'];
        if($img_size > 3000000) {
            $error = 'Image should be less than 4 MB';
        } else if(!in_array($img_extension, $allowed_ext)) {
            $error = "Unsupported image format";
        }
    }

if(isset($error)){
    echo "<script type='text/javascript'> alert('<?php echo $error; ?>'); </script>";
} 
?>

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