我有一个图片上传脚本,最初我将它保存在名为“upload.php”的文件中,该文件必须包含PHP上传脚本和简单的文件浏览器和提交按钮。这样工作正常,图像上传没有任何问题,并进入“images / uploads”目录。
但是,当我尝试将其实现到另一个页面时,它会变得很糟糕并且不会上传。我尝试了各种不同的东西,但我开始达到我的PHP知识的程度,所以我想我会在这里问。
这是index.php页面的代码(我正在尝试实现图像脚本的页面):
<?php
error_reporting(E_ALL);
session_start();
if(session_is_registered("username")) {
include("includes/config.php");
mysql_connect($host, $dbusername, $dbpassword) or die("Could not connect to database" . mysql_error());
mysql_select_db($database);
if(isset($_POST['update'])) {
$result = mysql_query("UPDATE items SET name='" . $_POST['name'] . "', price='" . $_POST['price'] . "', description='" . $_POST['description'] . "', hidden='" . $_POST['hidden'] . "' WHERE id='" . $_POST['id'] . "'") or die("Could not update" . mysql_error());
}
if(isset($_POST['delete'])) {
$result = mysql_query("DELETE FROM items WHERE id='" . $_POST['id'] . "'") or die(mysql_error());
header("Location: index.php?p=edit&c=" . $c);
}
if(isset($_POST['add'])) {
$result = mysql_query("INSERT INTO items (name, price, description, category, hidden) VALUES('" . $_POST['name'] . "', '" . $_POST['price'] . "', '" . $_POST['description'] . "', '" . $_POST['category'] . "', '" . $_POST['hidden'] . "')") or die(mysql_error());
}
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","100");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['submit'])) {
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image) {
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="../images/uploads/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
<!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 profile="http://gmpg.org/xfn/11">
<title>Silverdale Buxton Ltd | Admin CP</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/admin.css" />
<link rel="stylesheet" href="css/formalize.css" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<div id="container">
<div id="header">
<a href="index.php"><img src="../images/elements/sd-logo.jpg" alt="Silverdale Buxton Ltd" border="0" /></a>
<ul>
<li class="title">Admin CP</li>
<li><a href="../">View website</a></li>
<li><a href="login.php?do=logout">Log-out <pre><?php echo $_SESSION['username']; ?></pre>?</a></li>
<li class="spacer"><a href="index.php?p=add">Add New Item</a></li>
<li><a href="index.php?p=edit">View/Edit Items</a></li>
</ul>
</div>
<div id="content">
<?php if(!isset($p)) { // DEFAULT PAGE VIEWED AT INDEX.PHP ?>
<h1>Welcome to the Admin Control Panel</h1>
<p>This control panel enables you to manage (add/modify/delete) items for sale from the Silverdale database.</p>
<p>It's simple enough to use; just click one of the buttons in the top right of the page.</p>
<p>If you have any problems please contact me on <span>01782 269494</span> (ask for Chrish) or e-mail me at <span><a href="mailto:chrish@albionmedia.biz">chrish [at] albionmedia [dot] biz</a></span>.</p>
<?php } else if($p == "add") { // ADD NEW ITEMS PAGE ?>
<h1>Add New Item</h1>
<?php
$result = mysql_query("SELECT * FROM categories");
?>
<form method="post" name="editor" action="">
<label for="name">Product Name</label>
<input type="text" name="name" maxlength="100" />
<label for="price">Price £GBP</label>
<input type="text" name="price" maxlength="9" />
<label for="category">Category</label>
<select name="category">
<?php
while($row = mysql_fetch_array($result)) {
echo "<option value=\"" . $row['catname'] . "\">" . $row['catname'] . "</option>\n ";
}
echo "\n";
?>
</select>
<label for="description">Product Description</label>
<textarea name="description" cols="70" rows="20" maxlength="2000"></textarea>
<label for="image">Image Upload</label>
<input type="file" name="image" />
<label for="hidden">Hide this item from market page?</label>
<div class="visibility">
<span class="show">
Show
<input type="radio" name="hidden" value="0" />
</span>
<span class="hide">
Hide
<input type="radio" name="hidden" value="1" />
</span>
</div>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<input type="submit" name="submit" value="Add New Product" />
</form>
<p><a href="index.php?p=edit&c=<?php echo $row['category']; ?>">← Go Back</a></p>
<?php } else if($p == "edit") { // VIEW/EDIT ITEMS PAGE ?>
<h1>View/Edit Items</h1>
<?php if(!isset($c)) { ?>
<p>Please select a category.</p>
<ul>
<?php
$result = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($result)) {
echo "<li><a href=\"index.php?p=edit&c=" . $row['catname'] . "\">" . $row['catname'] . "</a></li>\n";
}
?>
</ul>
<?php } else if(isset($c) && !isset($id)) { ?>
<p>Items in category: <strong><?php echo $c; ?></strong></p>
<ul>
<?php
$result = mysql_query("SELECT * FROM items WHERE category='" . $c . "'");
while($row = mysql_fetch_array($result)) {
echo "<li><a href=\"index.php?p=edit&c=" . $row['category'] . "&id=" . $row['id'] . "\">" . $row['name'] . "</a></li>\n";
}
?>
</ul>
<p><a href="index.php?p=edit">← Go Back</a></p>
<?php
} else if(isset($id)) {
$result = mysql_query("SELECT * FROM items WHERE category='" . $c . "' AND id='" . $id . "'");
$row = mysql_fetch_array($result);
if($row['hidden'] == 1) {
$vis = "hidden";
} else {
$vis = "visible";
}
?>
<form method="post" enctype="multipart/form-data" name="editor" action="<?php echo $_SERVER['PHP_SELF'] . "?p=edit&c=" . $row['category'] . "&id=" . $row['id']; ?>">
<label for="name">Product Name</label>
<input type="text" name="name" maxlength="100" value="<?php echo $row['name']; ?>" />
<label for="price">Price £GBP</label>
<input type="text" name="price" maxlength="9" value="<?php echo $row['price']; ?>" />
<label for="description">Product Description</label>
<textarea name="description" cols="70" rows="20" maxlength="2000"><?php echo $row['description']; ?></textarea>
<label for="hidden">Hide this item from market page? <strong style="<?php if($vis == "hidden") { echo "color: #de4949"; } else { echo "color: #62a443"; } ?>">Item is currently <u><?php echo $vis; ?></u>.</strong></label>
<div class="visibility">
<span class="show">
Show
<input type="radio" name="hidden" value="0"<?php if($vis == "visible") { echo "checked=\"yes\""; } ?> />
</span>
<span class="hide">
Hide
<input type="radio" name="hidden" value="1"<?php if($vis == "hidden") { echo "checked=\"yes\""; } ?> />
</span>
</div>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<input type="submit" name="update" value="Update Product" />
<input type="submit" name="delete" value="Delete Product" class="delete" />
</form>
<p><a href="index.php?p=edit&c=<?php echo $row['category']; ?>">← Go Back</a></p>
<? } ?>
<?php } else { // IF SOMEONE MESSES WITH ?P= OR SOMETHING ELSE GOES WRONG ?>
<h1>Error 404:</h1>
<p>Page URL not recognised. Please <a href="index.php">click here</a>.</p>
<?php } ?>
</div>
</div>
<div id="footer">
<p>Copyright © 2010 Albion Media. All Rights Reserved.</p>
<p><a href="http://www.albionmedia.biz/" target="_blank">albionmedia.biz</a></p>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.css3finalize-latest.min.js"></script>
<script src="assets/javascripts/jquery.formalize.js"></script>
<?php if($p == "edit") { ?><script type="text/javascript">
$(document).ready(function() {
$('.delete').click(function() {
if(confirm("Are you sure you want to delete this item? This will delete all information and images associated with it and CAN NOT be un-done!")) {
return true;
} else {
return false;
}
});
});
</script><?php } ?>
</body>
</html>
<?php
} else {
header("Location: login.php");
}
?>
这是可以正常工作的upload.php脚本:
<?php
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","100");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['submit'])) {
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image) {
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="../images/uploads/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
<!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 profile="http://gmpg.org/xfn/11">
<title>Image Upload | Admin CP</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image"></td></tr>
<tr><td><input name="submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
</body>
</html>
我可能还应该注意,即使我提交此页面,我也不会在此页面上出现任何错误。
答案 0 :(得分:0)
你错过了
enctype="multipart/form-data"
在您的实施中,将表单更改为:
<form method="post" name="editor" enctype="multipart/form-data" action="">
...
<label for="image">Image Upload</label>
<input type="file" name="image" />
通过指定的enctype值 “multipart / form-data”,每个文件 内容将打包 提交在一个单独的部分 多部分文件。
答案 1 :(得分:0)
添加,enctype =“ multipart / form-data” 在提交表单以上传图片时