我有一个文件上传表单,它没有问题。 当我希望在文件上传完成后返回表单时出现问题。表格不会显示。我在这里读了另一篇文章说我需要使用
header("Location: upload.php?message=" . $message . "");
等等,但是仍未显示。我该怎么做才能使这项工作?
upload.php的:
<?php
session_start();
$servername = "localhost";
$username = "***********";
$password = "*********";
$dbname = "**********";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div class="container">
<div class="nav">
</div>
<div class="main">
<div class="content update">
<?php
if($_SESSION["logedin"] == "true"){
$sql = "SELECT * FROM content WHERE ID=" . $_POST["ID"];
//echo $sql;
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$title=$row["title"];
$body=$row["body"];
$id=$row["ID"];
}
}
$breaks = array("<br />","<br>","<br/>","<br />","<br />","<br/>","<br>");
//$title = str_ireplace($breaks, "\n", $title);
//$body = str_ireplace($breaks, "\n", $body);
//echo $body;
echo $_GET['message'];
?>
<form action="doupload.php" method="post" enctype="multipart/form-data">
Name file:
<input type"text" name="title">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" name="doload" value="doload">
<input type="submit" value="Upload" name="submit">
</form>
</div>
<div class="row2">
<h2></h2>
</div>
<div class="row2">
<div class="contentbubble">
<h2 id="demo"></h2>
<p id="demo2"></p>
</div>
</div>
</div>
</body>
</html>
doupload.php
<?php
session_start();
$message="";
$filename = 'forms/';
if (file_exists($filename)) {
//echo "The file $filename exists";
} else {
//echo "The file $filename does not exist";
}
$servername = "localhost";
$username = "**********";
$password = "**********";
$dbname = "***********";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_POST["doload"]=="doload"){
$target_dir = "forms/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//echo "File Name:" . $target_file . "<br>";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
$message="Sorry, file already exists.<br>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$message="Sorry, your file is too large. <br>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" ) {
$message= "Sorry, only JPG, JPEG, PNG & GIF files are allowed.<br>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message= $message . "Sorry, your file was not uploaded.<br>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$message = "The file " . basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. <br>";
//echo $message;
$title=$_POST['title'];
$sql = "INSERT INTO forms (Name, Path)
VALUES ('" . $title . "', '" . $target_file . "')";
if ($conn->query($sql) === TRUE) {
//echo "New record created successfully";
} else {
//echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location: upload.php?message=" . $message . "demo_form_get");
} else {
$message = "Sorry, there was an error uploading your file. <br>";
header("Location: upload.php?message=" . $message . "");
}
}
}
?>
答案 0 :(得分:1)
你可以做重定向,但它没有魔力。为什么不上传一个函数(一个类会更好)并在upload.php
页面上包含该函数?:
<强>功能/ function.Database.php 强>
// Making a database class makes more sense but, here a function is better
// than what you are doing currently with your connection because you can call
// it as a contained element
function Database($servername = "localhost",$username = "**********",$password = "**********",$dbname = "***********")
{
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error)
die("Connection failed: " . $con->connect_error);
else
return $con;
}
<强>功能/ function.UploadFile.php 强>
// Create your upload function
// You could feed the database in as an argument
// then you don't have to recreate the database connection
function UploadFile($settings = false)
{
$target_dir = (!empty($settings['target_dir']))? $settings['target_dir'] : "forms/";
$iName = (!empty($settings['input']))? $settings['input'] : "fileToUpload";
$filter = (!empty($settings['filter']) && is_array($settings['filter']))? $settings['filter'] : array("jpg","jpeg","gif","png");
if(!is_dir($target_dir))
mkdir($target_dir,0755,true);
$filename = trim(basename($_FILES[$iName]["name"]));
$target_file = str_replace("//","/",$target_dir.$filename);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if(file_exists($target_file))
$error[] = array("error"=>true,"details"=>"Sorry, file already exists.");
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000)
$error[] = array("error"=>true,"details"=>"Sorry, your file is too large.");
// Allow certain file formats
if(!in_array($imageFileType,$filter))
$error[] = array("error"=>true,"details"=>"Sorry, only JPG, JPEG, PNG & GIF files are allowed.<br>");
if(!empty($error))
return $error;
// if everything is ok, try to upload file
if(move_uploaded_file($_FILES[$iName]["tmp_name"], $target_file)) {
$error[] = array("details"=>"The file " . basename($filename). " has been uploaded.");
//echo $message;
$title = trim(preg_replace('/[^0-9A-Za-z\-\_]/','',$_POST['title']));
$title = (!empty($title))? $title : date("YmdHis").uniqid();
// Create database connection
$conn = Database();
// You should escape or use bind parameters
// I am just converting for ease...
$sql = "INSERT INTO forms (Name, Path)
VALUES ('".htmlspecialchars($title,ENT_QUOTES) . "','".htmlspecialchars($target_file,ENT_QUOTES)."')";
$error[] = ($conn->query($sql))? array("details"=>"New record created successfully") : array("error"=>true,"details"=>"Error: " . $sql . "<br>" . $conn->error);
}
else
$error[] = array("error"=>true,"details"=>"The file " . basename( $_FILES[$iName]["name"]). "failed to upload.");
// Just return the error message(s)
return $error;
}
<强> upload.php的强>
session_start();
// Include the database connection
include_once("functions/function.Database.php");
// Process file upload
if(!empty($_POST['doload'])) {
// Include the upload function
include_once("functions/function.UploadFile.php");
// Get the result back so you can show results to user
$errors = UploadFile();
}
// Use your database function here
$conn = Database(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="main">
<div class="content update">
<?php
if(isset($_SESSION["logedin"]) && $_SESSION["logedin"] == "true") {
$pID = (is_numeric($_POST["ID"]))? $_POST["ID"]:false;
if($pID != false) {
$sql = "SELECT * FROM content WHERE ID=".$pID;
//echo $sql;
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$title = $row["title"];
$body = $row["body"];
$id = $row["ID"];
}
}
$breaks = array("<br />","<br>","<br/>","<br />","<br />","<br/>","<br>");
//$title = str_ireplace($breaks, "\n", $title);
//$body = str_ireplace($breaks, "\n", $body);
//echo $body;
echo strip_tags(htmlspecialchars($_GET['message'],ENT_QUOTES));
}
// Run through errors
// You can change the upload function to report differently
// I just did a simple error return method
if(!empty($errors)) {
foreach($errors as $errArray) { ?>
<div style="background-color: <?php echo (isset($errArray['error']))? "red":"green"; ?>" />
<?php echo $errArray['details']; ?>
</div>
<?php
$errArray = array();
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
Name file:
<!-- You are missing an "=" here -->
<input type="text" name="title">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" name="doload" value="doload">
<input type="submit" value="Upload" name="submit">
</form>
</div>
<div class="row2">
<h2></h2>
</div>
<div class="row2">
<div class="contentbubble">
<h2 id="demo"></h2>
<p id="demo2"></p>
</div>
</div>
</div>
</body>
</html>