如何使用可选的上传文件提交表单数据

时间:2013-04-24 22:34:29

标签: php forms file upload

如何使用可选的上传文件提交表单数据。我的意思是,我可以将表单数据与上传的文件一起提交吗?但我想让上传文件可选。这是我的代码:

  <?php
define ("MAX_SIZE","5000");
 $errors=0;



if(($_SERVER["REQUEST_METHOD"] == "POST") && isset($_FILES["file"]["size"]) && ($_FILES["file"]["size"] > 0))
{

    $image =$_FILES["file"]["name"];
    $uploadedfile = $_FILES['file']['tmp_name'];


    if ($image)
    {

        $filename = stripslashes($_FILES['file']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
        {

            $change='<div class="msgdiv">Unknown Image extension </div> ';
            $errors=1;
        }
        else
        {

            $size=filesize($_FILES['file']['tmp_name']);


            if ($size > MAX_SIZE*1024)
            {
                $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
                $errors=1;
            }


            if($extension=="jpg" || $extension=="jpeg" )
            {
                $uploadedfile = $_FILES['file']['tmp_name'];
                $src = imagecreatefromjpeg($uploadedfile);

            }
            else if($extension=="png")
            {
                $uploadedfile = $_FILES['file']['tmp_name'];
                $src = imagecreatefrompng($uploadedfile);

            }
            else
            {
                $src = imagecreatefromgif($uploadedfile);
            }

            echo $scr;

            list($width,$height)=getimagesize($uploadedfile);


            $newwidth=500;
            $newheight=($height/$width)*$newwidth;
            $tmp=imagecreatetruecolor($newwidth,$newheight);


            $newwidth1=300;
            $newheight1=($height/$width)*$newwidth1;
            $tmp1=imagecreatetruecolor($newwidth1,$newheight1);
            imagealphablending($tmp1, false);
            imagesavealpha($tmp1, true);
            imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

            imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

            $image_name=time().'_'.$_FILES['file']['name'];
            $filename = "images/". $image_name;

            $filename1 = "images/small_". $image_name;
            $uid=$_SESSION['uid'];


            imagejpeg($tmp,$filename,100);

            imagejpeg($tmp1,$filename1,100);

            imagedestroy($src);
            imagedestroy($tmp);
            imagedestroy($tmp1);
        }}


}


if(isset($_POST['Submit']) && !$errors )
{
    $category_group= $_POST['category_group'];
    $title=$_POST['title'];
    $details=$_POST['details'];
    $ad_keywords=$_POST['ad_keywords'];
    $category_state=$_POST['category_state'];
    $category_city=$_POST['category_city'];
    $address=$_POST['address'];
    $telephone=$_POST['telephone'];
    $email=$_POST['email'];
    $website=$_POST['website_link'];
    $price=$_POST['price'];
    $filename= ($_FILES["file"]["size"] > 0) ? $filename : '';
    $filename1= ($_FILES["file"]["size"] > 0) ? $filename1 : '';




    $url=time().'-'. createUrl($title);
    if(!$category_group || !category_city || !$title || !$details || !$category_state ){
        echo "enter state and city name";
    }else{

        try{
        $sth = $dbh->prepare("
                           INSERT INTO
                                    advertisement(user_id,ad_image_big,ad_image_small,ad_cat_group,ad_title,ad_details,ad_state,ad_city,ad_address,ad_telephone,ad_email,ad_website,ad_price,ad_slug,ad_keywords)
                           VALUES(:field1,:field2,:field3,:field4,:field5,:field6,:field7,:field8,:field9,:field10,:field11,:field12,:field13,:field14,:field15)
                            ");
        $sth->execute(array(':field1' => $uid, ':field2' => $filename, ':field3' => $filename1, ':field4' => $category_group, ':field5' => $title, ':field6' => $details, ':field7' => $category_state,':field8'=> $category_city, ':field9' => $address, ':field10' => $telephone,':field11'=> $email,':field12'=> $website, ':field13' => $price, ':field14' => $url , ':field15'=> $ad_keywords));
        }catch (PDOException $ex){

            echo "An Error occured while inserting data to database";
            some_logging_function($ex->getMessage());
        }


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

每当我尝试提交没有上传文件的表单时,我都会收到此错误:

  

“将数据插入数据库时​​出错”

位于catch部分。如果我上传文件,我会收到一条成功的消息而没有任何错误。请帮帮我。

2 个答案:

答案 0 :(得分:1)

这是我不久前制作的代码......有同样的问题:)

表单本身:

            <form action="index.php" method="post" enctype='multipart/form-data'>
            <input class="header_input" type="text" name="header" />
            <br/><span class="input_headers"><p>Content</p></span>
            <textarea class="textarea_input" rows="10" cols="30" name="content">
            </textarea><br />
            Select File: <input type='file' name='filename' size='10' /><br />
            <input type="submit" class="submit" />
            </form>

虽然它没有检查,但有些内容被输入“标题”和“内容”部分,所以试着解决这个问题:

if (isset($_POST['header']) && isset($_POST['content'])) {


      $header = mysql_real_escape_string(htmlentities($_POST['header']));
      $content = mysql_real_escape_string(nl2br(htmlentities($_POST['content'])));

      $sql = mysqli_query($con,"INSERT INTO posts (Header, Content) VALUES 
        ('{$header}','{$content}')");
}

这会上传图片,如果有的话:

if (isset($_FILES['filename']['name'])) {

     $name = htmlentities($_FILES['filename']['name']);

      $allowedExts = array("gif", "jpeg", "jpg", "png");

      $extension = end(explode(".", $_FILES['filename']['name']));

        if ((($_FILES['filename']['type'] == "image/gif")
        || ($_FILES['filename']['type'] == "image/jpeg")
        || ($_FILES['filename']['type'] == "image/jpg")
        || ($_FILES['filename']['type'] == "image/pjpeg")
        || ($_FILES['filename']['type'] == "image/x-png")
        || ($_FILES['filename']['type'] == "image/png"))
        && ($_FILES['filename']['type'] < 20000)
        && in_array($extension, $allowedExts)) {

            $result = mysqli_query($con,"SELECT * FROM posts WHERE PID=(SELECT max(PID) FROM posts)");

            $row = mysqli_fetch_array($result);

            $id = $row['PID'];

            $new_name = $id . "_" . "000" . ".jpg"; 

            if (file_exists("images/" . $new_name)) {

                $new_name_ex = $id . "_" . "001" . ".jpg";

                move_uploaded_file($_FILES['filename']['tmp_name'],"images/" . $new_name_ex);

                 $sql = mysqli_query($con,"UPDATE posts SET Images='{$new_name_ex}' WHERE PID='{$id}'");
            } else {

      move_uploaded_file($_FILES['filename']['tmp_name'],"images/" . $new_name);

      $sql = mysqli_query($con,"UPDATE posts SET Images='{$new_name}' WHERE PID='{$id}'");
    }
}
}

希望有所帮助:)我是PHP新手,所以也许有办法让所有这些代码更简单,我希望它能回答你的问题

答案 1 :(得分:1)

从PHP文档(http://php.net/manual/en/features.file-upload.post-method.php),示例#3上传文件数组可以完成您遍历每个文件所需的内容(如果您有一个文件数组),那么 if语句检查文件是否存在。下面的代码来自PHP文档:

    foreach ($_FILES["pictures"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
          $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
          $name = $_FILES["pictures"]["name"][$key];
          move_uploaded_file($tmp_name, "data/$name");
        }
    }

如果没有文件,代码只会跳过上传并继续下一步。