PHP代码破坏HTML布局


PHP code breaking HTML layout

我有一个简单的文件上传器,这要感谢stackoverflow现在完全工作,但是当我将PHP代码复制到我的主布局时,一旦初始化上传文件,但它的格式或大小是错误的,它会发出错误,它会破坏下面的HTML。我想这和每次回声后的"exit"有关。但也可能是错的。

<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
    #there's no file name return an error
    echo "<br/><b>Please select a file to upload!'n</b>";
    exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
    #the type of the file is not in the list we want to allow
    echo "<br/><b>That file type is not allowed!'n</b>";
    exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
    #file is larger than the value of $max_filesize return an error
    echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb'n</b>";
    exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
    #one or both of the image dimensions are larger than the allowed sizes return an error
    echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size'n</b>";
    exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." 'n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
      <input type="file" name="image" style="width:300px;cursor:pointer" />
      <input type="submit" name="upload" value="Upload Image" />
</form>

的确,当你调用exit;它的意思是"立即停止所有处理;这个剧本完成了。"在它之后的任何内容——包括HTML——都不会被解释。

更好的组织方式是使这段代码成为一个函数,达到如下效果:

function uploadMyStuffPlease() {
    if($_POST['upload']) {
        if($_FILES['image']['name'] == "")
        {
            #there's no file name return an error
            echo "<br/><b>Please select a file to upload!'n</b>";
            return;
        }
        #we have a filename, continue
    // ....
}

现在您可以简单地调用uploadMyStuffPlease(),它将尽可能多地执行处理,并且可能在发生错误时提前返回。无论哪种方式,函数都将返回,因此脚本的其余部分(包括HTML)仍然可以被解释。

如果你调用exit;你的PHP脚本将无法输出任何了。这就是为什么布局被破坏了。

你应该试着把HTML部分从你的PHP代码,特别是避免打开标签,你不关闭之后(即div s或任何)。

话虽如此,最安全的做法可能是将所有内容放入一个函数中,这样在完成后不会退出脚本(参见其他帖子)。

if(isset($_POST['upload'])){

if(!empty($_POST['upload'])){

并删除exit