Hi I am calling a function to upload an image to a MySQL database
but it keeps saying unidentified index image
I am uploading the image using this button
<input type="file" name="image" size="25" />
<input type ="submit" name = "Register_Btn" value ="Register">
which calls this
if(isset($_POST['Register_Btn'])){
uploadImage($link);
register($link);
}
then in pictureupload.php I have this function
<?php
function UploadImage($link){
if ($_FILES['image']['error'] == UPLOAD_ERR_OK){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `authentication` ( `image_name`,`image`) VALUES ('{$image_name}','{$image}')";
mysqli_query($link,$sql);
}else{
echo'No File Chosen';
}
}
?>
Every time ['image'] is used it is returning the
Undefined index: image error and also
also on line 4 of the pictureupload it is also saying
file_get_contents(): Filename cannot be empty
How do I ensure that it is receiving the uploaded image data?
Try to check your image is really uploaded or not
<?php
function UploadImage($link){
if(isset($_FILES['image']) &&!empty($_FILES['image'])){// check file is uploaded or not
if ($_FILES['image']['error'] == UPLOAD_ERR_OK){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `authentication` ( `image_name`,`image`) VALUES ('{$image_name}','{$image}')";
mysqli_query($link,$sql);
}
}else{
echo'No File Chosen';
}
}
ahha
forgot to include
enctype="multipart/form-data"
Related
This question already has an answer here:
How to upload multiple image with rename in php mysql?
(1 answer)
Closed 1 year ago.
I wanted to upload multiple pictures at once using PHP but I am new to PHP so I don't understand how to do it. I want to upload a lot of pictures for one model. Like the picture below:
Here is my PHP code:
<?php
include_once('inc/header.php');
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
$image_file = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"]; //file name "txt_file"
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$path="../img/model_images/".$image_file; //set upload folder path
if (empty($name)) {
$errorMsg="Please Enter Name";
} elseif (empty($image_file)) {
$errorMsg="Please Select Image";
} elseif ($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif') { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "../img/model_images/" .$image_file); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
}
if (!isset($errorMsg)) {
$insert_stmt=$connect->prepare('INSERT INTO tbl_model(model_name,model_category,model_image,model_age,model_height,model_haircolor,model_eyecolor,model_bust,model_waist,model_description) VALUES(:name,:category,:image,:txt_age,:height,:haircolor,:eyecolor,:bust,:waist,:about)'); //sql insert query
$insert_stmt->bindParam(':name', $name);
$insert_stmt->bindParam(':category', $category);
$insert_stmt->bindParam(':image', $image_file);
$insert_stmt->bindParam(':txt_age', $age);
$insert_stmt->bindParam(':height', $height);
$insert_stmt->bindParam(':haircolor', $haircolor);
$insert_stmt->bindParam(':eyecolor', $eyecolor);
$insert_stmt->bindParam(':bust', $bust);
$insert_stmt->bindParam(':waist', $waist);
$insert_stmt->bindParam(':about', $about);
if ($insert_stmt->execute()) {
echo $insertMsg="Model Added Successfully!"; //execute query success message
}
} else {
echo $errorMsg;
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
But with this code I can only upload one picture but I want to upload many pictures.
This is my html code
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image" class="dropify" multiple>
</div>
In html you miss '[]' after name as you have to send array when you upload images and also make sure you write enctype in form tag as shown below
The form tag must contain the following attributes.
method="post"
enctype="multipart/form-data"
The input tag must contain type="file[]" and multiple attributes.
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image[]" class="dropify" multiple>
</div>
</form>
after this just you have to write for loop or foreach loop in php file as shown below in your code you use single column to store multiple image so apply this loop after you $about
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
//$path="../img/model_images/".$image_file; //set upload folder path
$path = '';
if (empty($name)) {
$errorMsg="Please Enter Name";
exit;
}
foreach($_FILES["image"]["name"] as $key => $value){
$image_file = implode(',', $_FILES["image"]["name"]);
$image_name = $_FILES["image"]["name"][$key];
$type = $_FILES["image"]["type"][$key]; //file name "txt_file"
$size = $_FILES["image"]["size"][$key];
$temp = $_FILES["image"]["tmp_name"][$key];
if (empty($image_file)) {
$errorMsg="Please Select Image";
exit;
} else if (
($type=="image/jpg" ||
$type=='image/jpeg' ||
$type=='image/png' ||
$type=='image/gif')
) { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "images/" .$image_name); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
exit;
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
exit;
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
exit;
}
}
echo $name.$category.$age.$height.$haircolor.$eyecolor.$bust.$waist.$about.$image_file;
exit;
after this just bind above $image_file in your query
when you want to fetch display image use explode
$explode_images = explode(",", $images_file);
its gives you array then use foreach loop and key to access image name url or whatever you store in that column.
Hope this help .
if you need explanation of implode and explode check this out Implode Explode
I have a table named images. It has two columns id and image (varchar300). I have this code upload.php :
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM images ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$actualpath = "/home/kinanday/public_html/$path";
$sql = "INSERT INTO images (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
this is upload.html :
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
</body>
The problem is: it saves into my database but the image in my file manager in Cpanel is 0kb
I am using this code to integration to my android app which need an image with varchar type. So in my app does not show image anything because the image is 0KB.
Can anybody with your advance to fix my php. every answer is very helpful for me. Thanks in advance.
You need to use the $_FILES superglobal, as #Fred-ii- said.
but $image = $_FILES['image'] is a array, see the options for it here: http://php.net/manual/en/features.file-upload.post-method.php
Examples:
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_tmpname = $_FILES['image']['tmp_name']; // this is a temporary name that php uses on every upload he does.
$image_type = $_FILES['image']['type'];
$image_error = $_FILES['image']['error'];
if(isset($_POST["imageuploader"])){ //Is submitted
if ($_FILES['image']['tmp_name']){ //LINE 3
$data = file_get_contents($_FILES['image']['tmp_name']);
$base64 = base64_encode($data);
$item = inputSanitize($_POST['item']);
$updateImage = $odb->prepare("UPDATE `items` SET `image` = ? WHERE `id` = ?;");
$updateImage->BindValue(1, $base64);
$updateImage->BindValue(2, $item);
$success = true;
}else{
$errors[] = "Please add an image.";
}
}
The problem I'm getting is that $_FILES['image']['tmp_name'] is apparently an undefined index:
Notice: Undefined index: image in /var/www/html/staff/imageupdater.php on line 3
However, I have this in my form:
<input type="file" name="image" accept="image/*">
file_uploads = On in my php.ini & the file I'm uploading is gif.
Likely you are missing the enctype in your form tag.,
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
Without that no file is uploaded and the $_FILES is not populated, hence the undefined image index.
Ok so i uploaded images with code below but i dont know how to display it, i want to make gallery so all i want is to display all images on one page, if you could explain that would be helpfull too!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phplogin";
$connect = mysqli_connect($servername,$username,$password,$dbname);
$file = $_FILES['image']['tmp_name'];
$ime = $_POST['ime'];
if(!isset($file))
{
echo "Izaberite sliku";
}
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
{
echo "Niste izabrali dobru sliku";
}
else
{
if(!$insert = mysqli_query($connect,"INSERT INTO store VALUES ('','$image_name','$image','$ime')"))
{
echo "Problem sa postavljanjem slike";
}
else
{
//$lastid = mysqli_insert_id($connect);
// I WANT TO DISPLAY IMAGES HERE
//echo "Image uploaded.<p />Slika:<p /><img src=get.php>";
}
}
}
?>
This code is to get image but it only display last ID and i dont know how to make it display all images
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("databaseimage") or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
Save images as files instead of blobs. Store url to image in db as varchar
The html
<form role="form" class="form-inline" enctype="multipart/form-data" method="post" action="">
<div class="form-group">
<input type="file" class="form-control" name="image"/>
</div>
<input type="submit" name="upload" class="btn btn-success" value="Upload" />
</form>
php
define('UPLOAD_PATH','images/');
This is the constant for the path of the images. In this case its a folder named images in the same directory as the script you are working on
$errors = array();
function output_errors($errors){
$output=array();
foreach($errors as $error){
$output[]='<li>'.$error.'</li>';
}
return '<ul>'.implode('',$output).'</ul>';
}
if(isset($_POST['upload'])){
if(!empty($_FILES['image']['name'])){
$image=$_FILES['image']['name'];
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];
if((($image_type=='image/gif') || ($image_type=='image/jpeg') || ($image_type=='image/png') || ($image_type=='image/pjpeg')) &&
($image_size>0) /*&& ($image_size<=MAX_FILE_SIZE)*/){
if($_FILES['image']['error']==0){
/*give each image a unique name*/
$image=microtime().$image;
/*move uploaded file to permanent folder*/
$target=UPLOAD_PATH.$image;
if(move_uploaded_file($_FILES['image']['tmp_name'],$target)){
if(mysqli_query($connect,"INSERT INTO images(`image`) VALUES ('$image')") ){
$message="Image was uploaded sucessfully";
}else{
$errors[]="Error,image was not uploaded successfully";
/*delete permanent file from server*/
#unlink(UPLOAD_PATH.$image);
}
}/*end of move uploaded file*/
}
}else{
$errors[]="File uploaded must be of type png, jpeg or gif";
/*delete temporary image file*/
#unlink($_FILES['image']['tmp_name']);
}/*end of image validation*/
}else{
$errors[]="Please select an image file";
}/*empty*/
}
if(!empty($errors))echo output_errors($errors);
if(!empty($message)) echo $message;
Your images table could appear like this
CREATE TABLE IF NOT EXISTS `images` (
`image_id` int(11) NOT NULL,
`image` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;
To get an image from db, you could have a query that selects image from table images. To display image in html do
$queryImage=mysqli_query($connect,"SELECT `image` FROM images");
while($rowImage=mysqli_fetch_assoc($queryImage)){?>
<img src="<?php echo UPLOAD_PATH.$rowImage['image'] ;?>" style="width:250px; height:200px"/>
<?php
}/*end of while loop getting images*/?>
I need to do a web page for a client to upload images to a data base and display them.
I am achieve to upload the images into a database, but I'm having trouble displaying them, but I can't work out why
Here is my code:
<!DOCTYPE html>
<head>
<body>
<form action="form.php" method="post" enctype="multipart/form-data">
File:
<input type="file" name="image" /> <input type="submit" value="Upload" />
</form>
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test" ) or die(mysql_error());
$file = $_FILES['image'] ['tmp_name'];
if (!isset($file)) {
echo "<br>Please select an image.";
}
else {
$image = addslashes(file_get_contents($_FILES['image'] ['tmp_name']));
$imageName = addslashes($_FILES['image']['name']);
$imageSize = getimagesize($_FILES['image']['tmp_name']);
if ($imageSize == FALSE)
echo "<br><br>Thats not an image. <br><br>";
else{
if (!$insert = mysql_query("INSERT INTO imgup VALUES ('','$imageName','$image')"))
echo "Problem uploading the image.";
else{
$lastId = mysql_insert_id();
echo "Article uploaded.<p /> Your image:<p /> <img src=get.php?id=$lastId>";
}
}
}
?>
</body>
</html>
This is my file who turn the image blob into an image:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test" ) or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM blog WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
And at the end the image does not display and this is what i get: http://goo.gl/gi1Uuc
And if i go and check my database, the image has ben successfully uploaded...
Depending on the file use inline base64 encoding. This is done with:
echo '<img src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
Font: base64_encode
OR
Put the T upperCase (Type), because can giving error in IE. Try printing with the function file_get_contents.
header('Content-Type: image/jpeg');
echo readfile($image);
I wouldn't store any image in a database. You should save it as file, and store the file's name in the database. You can then configure which directory an image gets served from without worrying about the full path to the image, or storing binary data in your db (yuck).
Try changing:
$image = mysql_query("SELECT * FROM blog WHERE id=$id");
to:
$image = mysql_query("SELECT * FROM blog WHERE id = '$id'");
Escaping an image file with addslashes will probably corrupt it, the imagesize test should be sufficient