警报错误消息多次显示

时间:2014-05-05 14:46:41

标签: javascript 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";
            }
        }
    ?>
    <script type="text/javascript">
        if('<?php echo $error; ?>' != '' && '<?php echo $error; ?>' != undefined) {
            alert("<?php echo $error; ?>");
        }
    </script>

问题是,每当我上传不支持的图像类型(如.tiff图像)时,都会显示警告框。这是我希望它工作的方式。但是如果我重新加载它,它会再次显示警告框并显示相同的消息。我第三次重装并没有显示出来。我希望警报信息只显示一次,而不是两次或三次..

1 个答案:

答案 0 :(得分:1)

将代码更改为:

<?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
} 
?>

<?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>";
} 
?>