I still have the error 2 days after. Help...
I have an error with picture upload in my code. The file upload works perfectly when i remove anything image related but fails once i add anything image related.
I get 2 errors
"Sorry, there was a problem uploading your file." and
"Problem uploading item". I have no idea why...
I'll post the section i have the problem with.
if((($_FILES["pic"]["type"] != "image/jpg")
|| ($_FILES["pic"]["type"] != "image/jpeg")
|| ($_FILES["pic"]["type"] != "image/png")
|| ($_FILES["pic"]["type"] != "image/pjpeg"))
&& ($_FILES["pic"]["size"] > 1000000))
{
$_SESSION['itemerror'][] = "Pic must be jpg, jpeg, png or pjpeg and must be less than 1mb";
}
//final disposition
if (count($_SESSION['itemerror']) > 0) {
die(header("Location: postitem.php"));
} else {
if(registerItem($_POST)) {
unset($_SESSION['formAttempt']);
$_SESSION['itemsuccess'][] = "Successfully Uploaded";
die(header("Location: postitem.php"));
} else {
error_log("Problem uploading item: {$_POST['name']}");
$_SESSION['itemerror'][] = "Problem uploading item";
die(header("Location: upload.php"));
}
}
function registerItem($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$target = "img/";
$target = $target . basename( $_FILES['pic']['name']);
$pic=($_FILES['pic']['name']);
$poster = htmlspecialchars($mysqli->real_escape_string($_POST['user']));
$itemcategory = htmlspecialchars($mysqli->real_escape_string($_POST['category']));
$itemname = htmlspecialchars($mysqli->real_escape_string($_POST['name']));
$itemdescription = htmlspecialchars($mysqli->real_escape_string($_POST['description']));
$itemprice = htmlspecialchars($mysqli->real_escape_string($_POST['price']));
$itemlocation = htmlspecialchars($mysqli->real_escape_string($_POST['addr']));
$itemcity = htmlspecialchars($mysqli->real_escape_string($_POST['city']));
$itemstate = htmlspecialchars($mysqli->real_escape_string($_POST['state']));
$itemphone = htmlspecialchars($mysqli->real_escape_string($_POST['phone']));
$itemnegotiate = htmlspecialchars($mysqli->real_escape_string($_POST['negotiate']));
if(move_uploaded_file($_FILES['pic']['tmp_name'],$target)){
$query = "INSERT INTO Product
(category,name,upload_date,user,
description,price,location,city,
state,phone,negotiatable,pic_link)" .
" VALUES ('{$itemcategory}','{$itemname}',NOW(),'{$poster}',
'{$itemdescription}','{$itemprice}','{$itemlocation}'" .
",'{$itemcity}','{$itemstate}','{$itemphone}','{$itemnegotiate}', '{$pic}')";
if ($mysqli->query($query)) {
$itemname = $mysqli->insert_itemname;
error_log("Inserted {$itemname} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
} else {
$_SESSION['itemerror'][] = "Sorry, there was a problem uploading your file.";
}
}
The form contains this:
<form id="userForm" method="POST" action="upload.php">
And this for the picture input:
<label for="pic">Pictures: </label>
<input class="input100" type="file" id="pic" name="pic">
Add the attribute enctype="multipart/form-data" to your <form>
Like this
<form id="userForm" method="POST" action="upload.php" enctype="multipart/form-data">
I do not know if that will solve your problem, but it will probably help you.
It seems to me that it's mandatory for an upload form.
Related
I am new to php. I made a simple upload form in php. This is my code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) )
{
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
if ($_FILES['upload']['name'] == 0 ){
echo "<br><br> New record created successfully";
}
else {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) === TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
It works fine. But if I press the submit with no files attached, it displays the error, Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\contractdb\filetest.php on line 20 .
I want uploading files to be optional because not every user has the files to attach. I also want the user to download the files after uploading without removing file_get_contents($_FILES['upload']['tmp_name']).
How do I do this?
Your check should take in place before calling file_get_content() so it does not throw an error and you only call the function if file input is not empty:
if(isset($_POST['submit']) ) {
if ($_FILES['upload']['size'] != 0 ) {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']
['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else {
echo 'error: empty file';
}
}
Try this:
if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
// Statement
}
Hi I am trying the data like title,Description and image.If i give only title and description without adding image the data should be inserted into database.But if I am trying that getting error.Here is my error and code:
error: error while uploading
my code
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0)
die("error while uploading");
else
{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
else
{
echo "failure";
}
Html Code
<form method="POST" action="blogs.php" enctype="multipart/form-data">
<div>
<label for="title">Title</label>
<input type="text" name="blog_title" value="">
</div>
<div>
<label for="image">IMAGE</label>
<input type="file" name="image">
</div>
<div>
<label for="blog_description">Description</label>
<textarea name="blog_description" class="text" style="width:50%;"> </textarea>
</div>
<input type="submit" value="Submit"/>
</form>
According to your code if you are not uploading the image, value of $error becomes 4. So your if() condition is getting executed. So remove your if condition.
if ($name = $_FILES["image"]["name"] != '') {
if ($type == "image/png" || $type == "image/jpg" || $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe") {
move_uploaded_file($temp, "upload/" . $name);
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
echo "upload complete";
}else{
echo "File type not supported.";
}
session_start();
header("Location:blogimage.php");
} else {
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
echo "upload complete";
session_start();
header("Location:blogimage.php");
}
First of all, start session at the very top of your PHP script, like this:
<?php
session_start();
?>
And now comes your issue. First use is_uploaded_file() function to check whether a file is uploaded or not, and then process your form accordingly.
So your code should be like this:
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if($error > 0){
die("error while uploading");
}else{
$permissible_extension = array("png", "jpg", "jpeg", "svg", "jpe");
if(in_array($ext, $permissible_extension)){
if(move_uploaded_file($temp,"upload/".$name)){
$sql = mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}else{
echo "File couldn't be uploaded";
}
}else{
echo "Invalid format";
}
}
}else{
$sql = mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
if($sql){
header("Location:blogimage.php");
exit();
}else{
echo "Insertion failed";
}
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
You have to use like below:
...
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
$sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$result','$description')");
} else {
$sql=mysql_query("INSERT INTO blogs(blog_title,blog_description)values('$result','$description')");
}
session_start();
header("Location:blogimage.php");
...
I am using mysqli_query with your code, because mysql_* is deprecated:
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "yourDb");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$title=$_POST['blog_title'];
$result = str_replace(" ", "-", $title);
$description=$_POST['blog_description'];
$name = "";
$failure = "";
if(isset($_FILES["image"]["name"])){
$name=$_FILES["image"]["name"];
$type=$_FILES["image"]["type"];
$size=$_FILES["image"]["size"];
$temp=$_FILES["image"]["tmp_name"];
$error=$_FILES["image"]["error"];
if($error>0){
$name = "";
}
else{
if($type == "image/png" || $type == "image/jpg"|| $type == "image/jpeg" || $type == "image/svg" || $type == "image/jpe" )
{
move_uploaded_file($temp,"upload/".$name);
}
}
}
$sql = mysqli_query($link,"INSERT INTO blogs (image,blog_title,blog_description)
values('$name','$result','$description')");
if($sql){
//echo "upload complete";
session_start();
header("Location:blogimage.php");
die();
}
else{
echo 'failure';
}
?>
Explanation:
I am checking if if $_FILES["image"]["name"] is set than execute the file upload code.
further more if $error is not equal to 0 use move_uploaded_file()
Query will run in default either file empty or not, if empty than use $name as empty else use file name.
From PHP Manual:
mysqli::query -- mysqli_query — Performs a query on the database
Note that, its a procedural structure of mysqli_* extension, ist param of mysqli_query should be your connection identifier and second param should be your MYSQL Statement.
You have to make your fields and values dynamic :
Try this :
$_POST = array('image'=>'','blog_title'=>'yes','blog_description'=>'nothing');
foreach ($_POST as $key => $value) {
if(!empty($value)){
$fields .= $key.',';
$values .= "'".$value."'".',';
}
}
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
echo "INSERT INTO blogs($fields)values($values)";
I am trying to upload a file to an images folder and also insert the directory path into a mysql db.
Here is my HTML form
<form enctype="multipart/form-data" method="post" action="newfacility.php">
<fieldset>
<legend>New Facility</legend>
...
<label for="photo">Facility Photo:</label>
<input type="file" id="facilityphoto" name="facilityphoto" /><br />
<label for="province">Photo Description:</label>
<input type="text" id="photodesc" name="photodesc" /><br />
....
<input type="submit" value="Create" name="submit" />
</fieldset>
</form>
newfacility.php
require_once('../appvars.php');
require_once('upload_image.php');
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
// Grab the user data from the POST
$facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
....
....
//This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');
//facility photo
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
$facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));
// check if the faciliy info already exists.
if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {
$query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$data = mysqli_query($dbc, $query);
//if the facility is unique insert the data into the database
if (mysqli_num_rows($data) == 0) {
//insert into facility table
$query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
. " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
. " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
. " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
. "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
. "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
mysqli_query($dbc, $query);
//query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
$getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$facilityID = mysqli_query($dbc, $getFacilityID);
//insert into photo table
$photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
. "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
mysqli_query($dbc, $photoQuery);
// Confirm success with the user
echo '<p>You have succesfully created a new facility. '
. 'Please go back to the admin panel.</p>';
//testing to see if I can view the image
echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';
//close db connection
mysqli_close($dbc);
exit();
}
And finally here is upload_image.php
if(isset($_FILES["facilityphoto"])) {
// Check if file already exists
if (file_exists($facilityPhoto)) {
echo "Sorry, facility photo already exists.";
}
if($_FILES['facilityphoto']['error'] !==0) {
echo "Error uploading facility photo image.";
} else {
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
So the error I keep hitting right now is: echo "Sorry, there was an error uploading the facility photo.";
I don't understand what I am doing wrong here that is resulting in the image not being uploaded into my images/ directory.
I am going to provide an answer that addresses only the file upload problem, all the database stuff is striped from the answer as it is not relevant.
// returns true only if the file was written to $to,
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading the facility photo.";
return false;
}
if (isset($_POST['submit'])) {
define('MM_UPLOADPATH', 'images/');
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityphoto"]["tmp_name"];
$saved = save_facility_photo($from, $facilityPhoto, $status_msg);
}
else {
// handle upload error
}
// continue with code
}
The following is an explanation of what I think is happening in your scripts.
At the top of newfacility.php, require_once('upload_image.php'); is called. Now lets step though upload_image.php noting that $facilityPhoto has not yet been defined
// this is very likely true
if(isset($_FILES["facilityphoto"])) {
// $facilityPhoto is undefined so file_exists(NULL) will return false
if (file_exists($facilityPhoto)) { }
// the image upload was probably successful, so we jump to the else branch
if($_FILES['facilityphoto']['error'] !==0) {
}
else {
// $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL)
// will return false, so we jump to the else branch
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
}
else {
// resulting in this error
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
Replace these lines:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
with these:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
i'm having a small issue in the duplicated names.
I want to auto rename any duplicated upload files, like numbering them.
or if i could make the name same with numbers, such as file1.jpg / file2.jpg
for all uploaded files
here's my code
<?php
include('connect-db.php');
if (isset($_POST['submit'])) {
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"photos/$filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo= mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename== '' ) {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
Even the echo of if(file_exists($_FILES["imgfile"]["name"])) it's not working, i don't know why
Thank you very much before replying
try this code
this code will never get same name this code will rename file like 2jh5425h44u5h45h454k5image.jpg this is how it will save file so no need to worry about duplicate file
i have added random name generator $newname = md5(rand() * time()); this will generate random name for your file
<?php
include('connect-db.php');
$newname = md5(rand() * time());
if (isset($_POST['submit'])) {
$filename = $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif") || ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)) {
if (file_exists($_FILES["imgfile"]["name"])) {
echo "File name exists.";
} else {
move_uploaded_file($_FILES["imgfile"]["tmp_name"], "photos/$newname . $filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo = mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
if you need to rename only if file is duplicate here is answer Renaming duplicate files in a folder with php
I have a problem in retrieving an image from a database. Here is the code that uploads the image to the database:
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
}
if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {
$query1=mysql_query("INSERT INTO store set image='$imgname1'");
$action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1);
die('not Uploded');
}
}
?>
Now I want to retrieve all the images in the database; for this I am using the following code:
<?php
$query1="select * from store";
$fetch=mysql_query($query1);
while ($rows=mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['image']."' />";
}
?>
You should not be using the old mysql_* functions and use PDO or mysqli instead. Here is a much cleaner and securer way of doing what you want.
<?php
/**
* A Simple class to handle your database requests
* related to your image storage ect
*/
class image_model{
private $db;
function __construct($db){
$this->db = $db;
}
function add($img_name){
$sql = "INSERT INTO store (image) VALUES (:value)";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
$stmt->execute();
}
function get_all(){
$sql = "SELECT image FROM store";
return $this->db->query($sql)->fetchAll();
}
//Perhaps use in future
function get_image($id){
$sql = "SELECT image FROM store WHERE id=:id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $result->fetchAll();
}
}
//Connect safely to your database...
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
//Create an instance of the image model above
$img_model = new image_model($db);
//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
if ($_FILES["img"]["error"] > 0){
echo "Error: ".$_FILES["img"]["error"]."<br />";
}else{
$img = getimagesize($_FILES["img"]["tmp_name"]);
$allowed = array('image/jpeg','image/gif','image/png','image/bmp');
//Width and height must be more then 0 pixles and mime must be in allowed array
if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
if(is_uploaded_file($_FILES["img"]["tmp_name"])){
//Clean image name
$img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
//move image to folder
move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
//Add image to db using a method from the image model
$img_model->add($img_name);
}
}else{
echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
}
}
}
//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" name="submit" value="Save"/>
</form>
<?php
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
echo '<img src="images/'.$row['image'].'" /><br />';
}
?>
Refer this link,
Hope this will help.
Change retrieval of image code to following,
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
try this I've tested this code and made some modifications.
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
//echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
//echo '<pre>';print_r($imageextension1);echo '</pre>';die('Call');
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
} else {
//if (($imageextension1 == "jpg") && ($imageextension1 == "jpeg") && ($imageextension1 == "gif") && ($imageextension1 == "png") && ($imageextension1 = "bmp")) {
if(move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1)) {
$query1=mysql_query("INSERT INTO fileurl(filename) VALUES('".$imgname1."')"); //fileurl is table name and filename is field name
if($query1) {
echo "Data inserted";
} else {
echo "Data not inserted";
}
} else {
echo "Error occured while trying to upload image";
}
//$action = ;
//die('not Uploded');
}
}
?>
and for fetching images try this
$query = "SELECT * FROM fileurl";
$fetch = mysql_query($query);
while($rows = mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['filename']."' />";
}
if your image format not matched it will close the program automatically otherwise it'll jump to the else condition and upload the image and then insert the name of file into the database.