I'm creating a blog with image upload basically.
Here is my add_post function:
function add_post($title, $txt_content, $img_content, $tags, $file_temp, $file_extn){
$title = mysql_real_escape_string($title);
$txt_content = mysql_real_escape_string($txt_content);
$tags = mysql_real_escape_string($tags);
$file_path = 'simpleblog/resources/images/'. substr(md5(time()), 0, 20) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
mysql_query("INSERT INTO `posts` SET
`tag_id` = '$tags',
`title` = '$title',
`txt_content` = '$txt_content',
`img_content` = '". mysql_real_escape_string($file_path) ."',
`date_posted` = NOW()");
}
Here is the php script for add_post.php
<?php
include 'resources/init.php';
if (isset($_FILES['img_content']) === true){
if(empty($_FILES['img_content']['name']) === true){
echo '<script type = "text/javascript">window.alert("Please pick a file!");</script>';
} else {
$allowed = array('jpg','jpeg','gif','png');
$file_size = $_FILES['img_content']['size'];
$file_name = $_FILES['img_content']['name'];
$file_extension= explode('.', $file_name);
$file_extn= strtolower(end($file_extension));
$file_temp = $_FILES['img_content']['tmp_name'];
$title = $_POST['title'];
$txt_content = $_POST['txt_content'];
$tags = $_POST['tags'];
if(in_array($file_extn, $allowed) === true && isset($_POST['txt_content']) === true){
add_post($title, $txt_content, $tags, $file_temp, $file_extn);
$post_id = mysql_insert_id();
header("Location: index.php?post_id=" . $post_id);
exit();
}else if (in_array($file_extn, $allowed)=== false){
echo '<script type = "text/javascript">window.alert("The only file type allowed are .jpg, .gif, .png");</script>';
}
}
}
?>
The mySQL database is updated with the image file's name. However, it is not moving the uploaded file into the simpleblog/resources/images/
what is the problem?
At the first, this check of type is not right:
$file_name = $_FILES['img_content']['name'];
$file_extension= explode('.', $file_name);
file_extn= strtolower(end($file_extension));
if I upload file with name image.php.jpg
, your check say this is an image, but I send php-file, and can request this file as php-file.
At the second, your function add_post has the parameter $img_content
, but in the function call you ignore it:
add_post($title, $txt_content, $tags, $file_temp, $file_extn);
And the file path in the move_uploaded_file function must have your site root path
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.