I have this html form
<form action="insert.php" method="post" enctype="multipart/form-data">>
<p>
<label for="covername">Cover Artwork:</label>
<input type="file" name="file"/>
</p>
<p>
<label for="textname">Text Artwork:</label>
<input type="file" name="textname"/><br><br>
</p>
<input type="submit" name="submit" value="Upload"/>
and this is the insert.php
//Upload cover artwork
$name= $_FILES['file']['name'];
$tmp_name= $_FILES['file']['tmp_name'];
$submitbutton= $_POST['submit'];
$position= strpos($name, ".");
$fileextension= substr($name, $position + 1);
$fileextension= strtolower($fileextension);
if (isset($name)) {
$path= 'uploads/';
if (!empty($name)){
if (move_uploaded_file($tmp_name, $path.$name)) {
echo 'Uploaded!';
}
}
}
//Upload text artwork
$textname= $_FILES['file']['textname'];
$tmp_textname= $_FILES['file']['tmp_textname'];
$textsubmitbutton= $_POST['submit'];
$textposition= strpos($textname, ".");
$textfileextension= substr($textname, $textposition + 1);
$textfileextension= strtolower($textfileextension);
if (isset($textname)) {
$textpath= 'uploads/';
if (!empty($textname)){
if (move_uploaded_file($tmp_textname, $textpath.$textname)) {
echo 'Uploaded!';
}
}
}
// attempt insert query execution
$sql = "INSERT INTO table (covername, textname) VALUES ('$name', '$textname')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
The covername is saved to the database and the file is uploaded to uploads/ - this works great. But the second upload isn't working at all, textname isn't saved to the db nor is it uploaded. What am i missing?
Just change this:
//Upload text artwork
$textname= $_FILES['textname']['name'];
$tmp_textname= $_FILES['textname']['tmp_name'];
$textsubmitbutton= $_POST['submit'];
$textposition= strpos($textname, ".");
$textfileextension= substr($textname, $textposition + 1);
$textfileextension= strtolower($textfileextension);
if (isset($textname)) {
$textpath= 'uploads/';
if (!empty($textname)){
if (move_uploaded_file($tmp_textname, $textpath.$textname)) {
echo 'Uploaded!';
Related
I have created a basic car sales website. I have used the following PHP code to upload my image
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
So the file is being uploaded to the server and that is great (took me ages to get it to work), I am using phpliteadmin as my database manager and I have a field called car_image_url, this is where i paste the url to the image on the server, however I have added a page on the site where users can upload an image themselves, so my question is how can I get this to work.
I am using the following to convert the url to display an image.
echo "<td id='img'><img src=\"". $row["car_image_url"] . "\" /></td>";
However uploading the file is a different story, what code do I use on my website to get the uploaded file to link to the image url.
Here is my PHP code that makes a new car on the main site:
<?php
try {
# Connect to SQLite database
$dbh = new PDO("sqlite:../Car_Sales_Network");
$make = $_POST['Make'];
$model = $_POST['Model'];
$badge = $_POST['Badge'];
$price = $_POST['Price'];
$trans = $_POST['Transmission'];
$ppl = $_POST['P_Plate_Legal'];
$sth = $dbh->prepare('INSERT INTO Cars_On_Network
("car_make","car_model","car_badge","price","trans","P_Plate_Legal")
VALUES
(?, ?, ?, ?, ?, ?)');
$sth->execute(array($make, $model, $badge, $price, $trans, $ppl));
$id = $dbh->lastInsertId();
//header("Location: ../Carsales_Network.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>New Vehicle</title>
<link type="text/css" rel="stylesheet" href="New_Car_Form.css"/>
</head>
<body>
<div id="main">
<form action="Insert_Car.php" method="post" enctype="multipart/form-data">
Make:<br>
<input type="text" name="Make">
<br>
Model:<br>
<input type="text" name="Model">
<br><br>
Badge:<br>
<input type="text" name="Badge">
<br>
Price:<br>
<input type="text" name="Price">
<br>
Transmission: <br>
<input type="radio" name="Transmission" value="Manual" checked>Manual
<br>
<input type="radio" name="Transmission" value="Auto">Automatic
<br><br>
P Plate Legal: <br>
<select name="P_Plate_Legal">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Choose a Picture: <br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<br>
<br>
<input class="submit" type="submit" value="Submit">
<br>
Let's go back!
<br>
</div>
</body>
</html>
</form>
</body>
</html>
I am sure it is a similar process however I just can't think of how to do it.
Cheers.
it seems to me like youre having trouble with the upload script.
Here is a way that comes in handy (It creates an unique name for all images)
Crate your sql within the WRITE TO DATABASE comment i made:
if(isset($_FILES['fileToUpload'])){
$File = $_FILES['fileToUpload'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'jpeg', 'gif');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error?
if($FileError==0){
//Create new filename:
$NewName = uniqid('', true) . '.' . $FileExt;
//Destination
$UploadDestination = $_SERVER['DOCUMENT_ROOT'] . '/Cars_Photos/' . $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Filename = $NewName
//WRITE TO DATABASE:
//encode url:
$Image = urlencode($UploadDestination);
//Redirect:
header("Location: /complete.php?image=$Image&cat=Cars");
}
//File didnt upload:
else{
echo "File didnt upload...";
}
}
//An error occured
else{
echo "An error occured while uploading...";
}
}
//Filetype not allowed
else{
echo "Sorry, the file you tried to upload is not allowed.";
}
}
Complete.php:
<?php
//Your file is here:
echo urldecode($_GET['image']);
How can i store and display the images in a MySQL database. Till now i have only written the code to get the images from the user and store them in a folder, the code that i wrote till now is:
HTML FILE
<input type="file" name="imageUpload" id="imageUpload">
PHP FILE
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";}
I found the answer, For those who are looking for the same thing here is how I did it.
You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
insert image zh
-while we insert image in database using insert query
$Image = $_FILES['Image']['name'];
if(!$Image)
{
$Image="";
}
else
{
$file_path = 'upload/';
$file_path = $file_path . basename( $_FILES['Image']['name']);
if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path))
{
}
}
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> ';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>
I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".
I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php
How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>