尝试制作一个简单的脚本来评论新闻文章,它正在为文本工作,但我希望用户能够提交图像以用作图标或头像。这是表单字段:
<label>Add your avatar<span>*</span></label>
<input name="image" type="file"/>
并且表单指向此脚本:
<?php
$formats = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ( $_FILES["file"]["size"] < 90000 && in_array($extension, $formats) ) {
if ($_FILES["file"]["error"] > 0) {
// something went wrong, display the error using; $_FILES["file"]["error"];
} else {
if ( !file_exists("avatars/" . $_FILES["file"]["name"] ) ) {
move_uploaded_file($_FILES["file"]["tmp_name"], "avatars/" . $_FILES["file"]["name"]);
}
}
}
$tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
$page_path = $_POST['page_path'];
$con=mysqli_connect
("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO comments (name, comment, email, storyid, entry_date)
VALUES
('$_POST[name]','$_POST[comment]','$_POST[email]','$_POST[storyid]',now())";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header('Location: http://www.website.com/' . $page_path);
mysqli_close($con);
?>
脚本运行完成但图像未保存到:
www.website.com/avatars/
所有其他表单数据插入到sql就好了。唯一的问题是图像。目标目录是chmode 0777。
答案 0 :(得分:0)
嗯,这很难。您可以使用以下代码将图像存储为头像:
$formats = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ( $_FILES["file"]["size"] < 20000 && in_array($extension, $formats) ) {
if ($_FILES["file"]["error"] != 0) {
// something went wrong, display the error using; $_FILES["file"]["error"];
} else {
if ( !file_exists("avatars/" . $_FILES["file"]["name"] ) ) {
move_uploaded_file($_FILES["file"]["tmp_name"], "avatars/" . $_FILES["file"]["name"]);
}
}
}
所有你需要做的,是通过在移动图像或已经存在时将sql查询作为请求发送到你的sql中......可以这样做;
$tempLink = "http://example.com/avatars/" . $_FILES["file"]["name"];
确保在file_exists的if语句之后添加它。 :)