Upload an image to a folder and get its path name - php

I have a form with a file input field:
<tr align="left">
<td>Image :</td>
<td align="left">
<input type="file" name="ImageFile" size="18">
</td>
</tr>
I then do stuff with this image file on submit:
$image_tmpname = $_FILES['ImageFile']['name'];
$imgdir = "blogImages/";
$imgname = $imgdir.$image_tmpname;
$blogs = new Blogs();
move_uploaded_file($_FILES['ImageFile']['tmp_name'], $imgname);
$insert = $blogs->insertBlog($heading, $article, $date, $imgname);
The directory I want to save the images is called blogImages and is in the same directory as the above.
You may notice in the above I call on a function called insertBlog within the class Blogs'. Insert blog takes all the info and inputs the data to a mysql table. The code forinsertBlog` is:
function insertBlog($heading, $article, $date, $imgname){
$query = "INSERT INTO Blogs (BlogTitle, MainArticle, PostDate, Image) VALUES ('$heading', '$article', '$date', '$imgname')";
$oDatabase = new database;
$connection = $oDatabase->Connect();
if (!mysql_select_db($oDatabase->Name(), $connection))
$oDatabase->ShowError("Blogs.insertBlog");
if (!(# mysql_query ($query, $connection)))
$oDatabase->ShowError("Blogs.insertBlog");
return (mysql_insert_id());
}
When a user fills out a form, it stores all the other information correctly in the MySQL table apart from the image information. Also, it doesn't store the actual image in the blogImages folder. So how do I get this script to upload the image to the blogImages folder and store its path in the mysql table. At the moment it doesnt not store the image in the db and only put the value blogImages/ in the image path field in my MySQL table.

To transfer a file you must specify multipart/form-data enctype in HTML.
<form enctype="multipart/form-data" action="" method="POST">

Related

How to pass POST parameters in a url

Is it possible to upload images/files by sending the POST or REQUEST, parameters in the URL without HTML content?
I created a PHP file that gets a image from my someone, stores that file into the database, and a in a folder on my computer. It works fine but what I want to do now is remove the html content and only allow someone to send the images/files via the URL. I tried using $_GET but I received a lot of errors. I also researched this and read that only $_POST will work.
Here is my PHP source code with HTML but keep in mind, "I want the page blank and the only way for someone to send the images/files is through URL".
PHP:
if(isset($_POST['submit'])){
if(#getimagesize($_FILES['image']['tmp_name']) ==FALSE){
// Select an image
echo "Please select an image.";
}
else{
// THE PATH TO STORE THE UPLOAD IMAGE
$target = "images/".basename($_FILES['image']['name']);
//CONNECT TO DATABASE
$db = mysqli_connect("localhost", "root", "");
mysqli_select_db($db, "magicsever");
if(mysqli_connect_error()){
die ("Database connection error");
}
//GET ALL THE SUBMITTED DATA
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
//Store te submitted data to database
$sql = "INSERT INTO image_test (name, image)VALUES ('$name','$image')";
$query = mysqli_query($db, $sql);
//Now lets move the uploaded image into the folder
$nullResult = array();
$nullResult['Image'] = (move_uploaded_file($_FILES['image']['tmp_name'], $target))? "Successful": "Unsuccessful";
echo json_encode($nullResult);
}
}
HTML:
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<br></br>
<input type="submit" name="submit" value="Upload">
</form>
$_POST['']; Parameters come from the usually the form that has the method set to POST, like yours has, that input type you have (file, named image) will be returned has $_POST['image'], $_REQUEST on the other hand is the "GET" method, it works in the same way, the only difference is it's not secure and it comes in the url. I would recommend using POST to be honest. Also use PDO because your code is vulnerable to SQL injection. (mentioned by Alex Howansky)

php form upload and remane image then insert into DB

I have a already functioning form that INSERT data into a db, i also have 4x file inputs for images, the form then adds all data, uplaods images and renames images to match the next ID and adds a random end to the filename.
this all works as intented
but i now need the filename(s) to be added to the database, sometimes the form will have 1x imaghe sometimes 4x images but im not sure how to store the filenames in the db from the below code. can anyone help? i assume the array needs to be broken down to individual filenames but not sure how to do it.
<?php
if(isset($_POST['submit'])){
// Variables for date&Time logs
$dateLog = date("y-m-d"); // DATE OF ADDITION
$timeLog = date("H:i:s", time() - 3600); // TIME OF ADDITION
// INSERT QUERY
$sql="INSERT INTO $table1 (firstname, lastname, companyname, phone, email, name, make, serial, catagory, price, location, description, sold, operational, year, clear, rip, version, service, dock, loading, available, extras, dateadded, featured)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[companyname]','$dateLog','No')";
$query = mysql_query($sql) or die("Cannot query the database.<br>" . mysql_error());
// start of image upload
$insert_id = mysql_insert_id() or die("Unable to get insert id for image name.<br>" . mysql_error());
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("../images/listings/".$txtGalleryName."/".$file_name))
{
$filename=basename($file_name,$ext);
$newFileName=$insert_id."_".mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($error,"$file_name, ");
}
}
// end of image upload
echo '<p>This item was added successfully</p>';
}
?>
and my form;
1: Upload : <input type="file" name="files[]"/><br />
2: Upload : <input type="file" name="files[]"/><br />
3: Upload : <input type="file" name="files[]"/><br />
4: Upload : <input type="file" name="files[]"/><br />
appreciate any help :)
you can use $rename_var = rand('111111','999999'); and prepend it before the file name like $new_changed_name = $rename_var.$_FILES['files']['name']; and then use this name while saving the file in folder like so .. move_uploaded_file('tmp_name','path/'.$new_changed_name);
and insert this $new_changed_name new name into database.

how to upload picture and store in database

$image = file_get_contents($_FILES['image']['tmp_name']);
$image = mysql_real_escape_string($image);
mysql_query("UPDATE ngc set pic='" . $image "' WHERE username='" . $_SESSION["username"] . "'");
<form method="post" action="" enctype="multipart/form-data">
Upload Image :<input type="file" name="image" id="file">
<br><input type="submit" name="submit" value="Update!" class="btnSubmit">
</form>
i want to upload image to database..
Read this very nice example here: http://www.mysqltutorial.org/php-mysql-blob/
Also see this image gallery example here: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml
BLOBs are data types in MySql database which can help you store image files in database directly.
Although a better way would be to store the file on the disk and store the path of that variable in the database.
get the Content of the file and save in database;
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Mysql:
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
First of all if you want to save the entire image into the database , you must have the pic attribute type set to BLOB , here you have two options , either save the entire image into database , or save the name after uploading the images into a specified folder with a unique name each , so you can retrieve the images by name into this directory.

Adding photo category to php code?

I was able to develop a code in enabling users to freely upload images, while the pictures would be stored to the MySql database. But I also would like to add to the php and mysql code image categories where before uploading the image, users can select from ether category- All, People, Cities, Nature and Others then click submit. How do I add that to my php code and mysql table? See my original code below:
<?php
$dbCnn = mysql_connect('', '', '');
mysql_select_db('', $dbCnn);
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$insStr = "INSERT INTO imagedata(id, image) VALUES ('', '{$image}')";
mysql_query($insStr);
}
Don't store images in database because it's useless. Instead of this, store in database only path to file and file save on server.
So...
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<select name="category">
<option>Nature</opton>
<option>People</option
</select>
</form>
<?php
if(isset($_POST['category']) && isset($_FILES['file']['tmp_name'])){
//mysql connect etc
move_uploaded_file($_FILES['file']['tmp_name'], path/where/to/save/file);
mysql_query("INSERT INTO table VALUES('{$_FILES['file']['name']}', '{$_POST['category']}')");
}

PHP - How to add data to an exist row in database

I created a login page that when user login redirect to a pictures.php,
pictures page should contains the images of the user , I already create upload page to upload image to file directory and when the user upload an image the image link is added to a new row in the database, I need to add the image link to an exist row of the user,I already created a session for user when logged in.
So I need to add the image link to an exist row of the user.
This is the code that insert the image to a file directory and save its link to a new row of the database.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
mysql_query("INSERT INTO userid (imageid) VALUES ('.$name')");
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
And the upload form is
<html>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="Submit" value="Upload">
</form>
</html>
So how to the image link to an exist row of the user.
Use mysql_query("UPDATE $table_name SET imageid='{$name}' WHERE userid=$userid")
Of course substituting variables and columns with correct values
Use UPDATE query instead of INSERT. INSERT will add new row but UPDATE will update your existing data.
You have to update the row if the row where you want to add image link is already exist. So use UPDATE Query. and debug wether table is updated or not.
check in table or use or die(); after the query

Categories