I am new to php and trying to upload an image file in mysql database using php.I tried various tutorial but it didnot work for me.
Code Snippet:-
<?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "root", "");
//Select database, database_name needs to be changed
mysql_select_db("yelldb");
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>
<?php
}else{
//if the form hasn't been submitted then:
//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved
//into the database. The image is named after the persons IP address until it gets moved into the database
//get users IP
$ip=$_SERVER['REMOTE_ADDR'];
//don't continue if an image hasn't been uploaded
if (!empty($image)){
//copy the image to directory
copy($image, "./temporary/".$ip."");
//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR'];
$fp1 = fopen($filename1, "r");
//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));
//close the file
fclose($fp1);
//encode the image into text
$encoded = chunk_split(base64_encode($contents1));
//insert information into the database
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')");
//delete the temporary file we made
//unlink($filename1);
}
}
?>
We don't save out the whole image in our database usually. We go through inserting the permanent of picture in our database. Use this php function
move_uploaded_file(file,newloc)
This will move from your temporary directory to permanent directory. Then, get path from there and insert that to the database.
Typically, you wouldn't save an entire image into an SQL database. Instead, you store the on disk path or some other 'pointer' to the actual file.
Change your code to read something like the following:
//don't continue if an image hasn't been uploaded
if (isset($_POST['image'])){
$image = $_POST['image'];
//copy the image to directory
$path = "/some/path";
move_uploaded_file($image,$path);
//store the name and path. PS: you will want to validate your input, and look
//at using prepared statements.
//Concentating values like this is NOT safe, or ideal
$location = $path . "/" . $image
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")");
}
If however, you still wish to store the image in the SQL database, look into the blob storage type, not encoded text.
PHP move_uploaded_file
Related
I'm creating a site that displays news uploaded on it's admin panel.
Each post has an image and a title (and description, but i haven't implemented it yet).
My problem is, that when i try to post (and upload image with it) the post is created, but the image doesn't exist.
uploader (php):
if (isset($_FILES['image'])) {
//this script
//connects to mysql database
//declares an array that contains table names (array name is db)
require_once("db.php");
//move file to the img folder
move_uploaded_file($_FILES['image']['tmp_name'], "img/" . $_FILES['image']['tmp_name']);
//upload the post to the database
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('img/{$_FILES['image']['tmp_name']}', '{$_POST["text"]}')";
if (!mysql_query($sql)) {
//display error message
}
}
form (html):
<form action="post.php" method="POST" enctype="multipart/form-data">
<label>Image: </label><input type="file" name="image" />
<br />
<label>Text: </label><input type="text" name="text" />
<input type="submit" />
</form>
I check the files via ftp after posting, the image doesn't exist.
$_FILES['image']['tmp_name'] is an absolute pathname like /var/tmp/something. When you concatenate it to img/, you get a pathname that points into a subdirectory, img//var/tmp/something. Since the subdirectory doesn't exist, move_uploaded_file() fails.
You should use basename() to get just the filename portion.
$filename = 'img/' . basename($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES['image']['tmp_name'], $filename);
$text = mysql_real_escape_string($_POST['text']);
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('$filename', '$text')";
I'm not really sure how safe using the name of the temp file this way is, though. I don't think there's any guarantee that it will never repeat the same name for different uploads.
Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end
I'm trying to upload a image in PHP but the image is not getting saved in the directory on the server. However I'm able to save the path of the image in the database. Please help. Here is the piece of code. I'm not getting any error in the web page.
<?php
error_reporting(E_ALL);ini_set('display_errors', 'On');
session_start();
$logged_user_name = $_SESSION['user_name'];
$logged_user_type = $_SESSION['user_type'];
$logged_user_team_id = $_SESSION['team_id'];
$logged_user_team_name = $_SESSION['team_name'];
$uploaded_profile_image = $_POST['propic'];
//$uploaded_profile_image = $_FILES['propic']['name'];
include_once("classes/doEverything_framework.php");
function upload_image()
{
$db_connection_obj = new database_connection;
$db_connection = ($db_connection_obj -> open_database_connection());
global $logged_user_name;
global $uploaded_profile_image;
$profile_image_upload_dir = 'images/uploaded_profile_pics/';
if ($uploaded_profile_image != null || $uploaded_profile_image != "")
{
//file_put_contents($uploaded_profile_image);
move_uploaded_file($uploaded_profile_image, $profile_image_upload_dir);
//file_put_contents($uploaded_profile_image,$profile_image_upload_dir);
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image;
$sql = "UPDATE user_login_table SET user_profile_image = '$uploaded_profile_image_link' WHERE user_name = '$logged_user_name'";
mysql_query($sql, $db_connection);
}
$db_connection_obj -> close_database_connection($db_connection);
}
?>
HTML Code:
<form enctype="multipart/form-data" name="uploadprofileimage" onsubmit="" action="" method="post">
<input type="file" name="propic" id="propic" onclick="" >
<input type="submit" value="Upload" name="upload" id="submit" >
<br>
<label for="propic" id="picerrorlabel"></label>
</form>
<?php
if(isset($_POST['upload'])) //This ensures the function runs only when the submit button is clicked.
{
upload_image();
}
The correct way to access selected File is as follows
$uploaded_profile_image = $_FILES['propic']['name'];
Make sure you are uploading file within limit of configured file size in php.ini (upload_max_filesize). rest all should work.
Correction 1:-
Your are passing only directory name in move_uploaded_dir. I think you should pass complete image path. and $uploaded_profile_image should be your image tmp_name.
move_uploaded_file($_FILES['propic']['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image);
Correction 2:- You can't get image name in $_POST. so it should be
$uploaded_profile_image = $_FILES['propic']['name'];
You cannot get image or any file in $_POST['propic']; the correct way to access file or image is by using $_FILES
so you should use $uploaded_profile_image = $_FILES['propic']['name'] in move_uploaded_file function. Make sure to check upload_max_filesize limit in php.ini.
To upload a file in php use move_uploaded_file()
$path="upload/".$_FILES["file"]["name"]; // This specifies the path to save file
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
First You cant get file value in POST method so you need to user $_FILE to get file. So you need to replace line no 5 with this :
$uploaded_profile_image = $_FILES['propic'];
Another mistake in your code is while moving uploaded file where source params is expected to be temporary location of file :
move_uploaded_file($uploaded_profile_image['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image['name']);
Now in line no 27 you can get file name to store in database this way :
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image['name'];
I am trying to upload a file onto the server using php but I need some help.
I have a html form to submit a book name and a book image. The book name will be stored in the database (see below) and the image will be stored on the server.
The id, book name, and date are being stored in the database however the image is not uploading. Please help me to sort it out.
Thanks.
Database table "books"
id int(11), book_name varchar(255), date_added date
add_book.php
<?php
$book_name = $_POST['book'];
// insert fields to database
$sql_query = mysql_query("INSERT INTO books (book_name, date_added) VALUES ('$book_name', now()");
// get id for that row
$id = mysql_insert_id();
// rename the book to that id followed by the format .jpg
$new_book_name = "$id.jpg";
// define upload path
$upload_path = "../book_images/";
// move the uploaded file to the upload path with the new name
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_path . $new_book_name);
?>
<form action="add_book.php" method="post" enctype="multipart/form-data" name="bookform" id="bookform">
Book name: <input name="book" type="text" id="book" value=""/> <br />
Book image: <input type="file" name="upload" id="upload" />
<input name="submit" type="submit" value="Add book" />
</form>
Before any PHP developer begins to debug anything I always suggest in every question that do set error_reporting(E_ALL); and ini_set("display_errors", 1); at the very top of your script. This will tell you what went wrong on what line with respect to what statement/variable/constant
Anyways, you should check for validities whether the file uploads or not, its type and other such parameters. You should also store it by adding relative path with respect to your current working directory
if(isset($_FILES["upload"])&&$_SERVER["REQUEST_METHOD"]=="POST")
{
$name=$_FILES["upload"]["name"];
$tempName=$_FILES["upload"]["tmp_name"];
$size=$_FILES["upload"]["size"];
$type=$_FILES["upload"]["type"];
$realPath="bookName/Imagename/".$name;
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/png"))
{
if(is_dir($fullDirectory)) //if directory exists, then simply move it
{
move_uploaded_file($tempName, $realPath);
}
else //if directory doesn't exist then make one and then move the file
{
mkdir($fullDirectory,0777,true);
move_uploaded_file($tempName, $realPath);
}
}
else
{
print $_FILES["upload"]["error"];
}
}
Spme thing is wrong here:
$new_book_name = "$id.jpg";
You should take file name from POST here $_FILES["upload"]["name"]. and add $id with this file name:
$new_book_name = $id."-".$_FILES["upload"]["name"];
Also check permission in your upload directory "../book_images/".
For some reason my PDF upload form is failing consistently, I have this code:
<?php
if($_POST["submit"] == "Add PDF to Comm and Special Projects")
{
$addsubp = $_POST["addsubp"];
$addsubp_name = $_POST["addsubp_name"];
$commuploadedfile = $_FILES['uploadedfile']['name'];
$sqldoc = "INSERT INTO projects_links (pid, display_name, link) VALUES ('".$addsubp."','".$addsubp_name."','".$commuploadedfile."')";
mysql_query($sqldoc) or die(mysql_error());
echo "<BR>";
$target_path = "D:\\Hosting\\69903\\html\\pdfs\\comm\\";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<br>The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded<br>";
} else{
echo "<br>There was an error uploading the file, please try again.<br>";
}
}
?>
<form method="post">
Add PDF to Project for Committees and Special Projects <br>Choose Project<select name="addsubp"><?php
$query = "SELECT
projects.*
FROM
projects";
$showresult = mysql_query($query);
$csp_c = 1;
while($buyarray = mysql_fetch_assoc($showresult))
{
echo "<option value=".$buyarray['id'].">".$buyarray["pname"]."</option>";
}
?></select><br>
Choose Display Name for PDF <input type="text" name="addsubp_name" /> <Br>
Choose PDF: <input name="uploadedfile" type="file" /> <Br>
<input type="submit" value="Add PDF to Comm and Special Projects" name="submit" />
</form>
I have made sure that the application has write privileges to the "comm" directory. I have godaddy and used the file manager to make sure of that. I have had problems with permissions in this project before, so I know this isn't case. It keeps printing
There was an error uploading the file, please try again.
It doesn't attempt to upload any PDF at all, what am I doing wrong?
thanks!
You may have permissions issues, but for file uploads your form tag should contain the proper enctype attribute.
<form enctype="multipart/form-data" method="POST">
and defining a file size limit is also a good idea:
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
try checking the Upload error message: http://php.net/manual/en/features.file-upload.errors.php
Your code is blindly assuming the file upload succeeded. At bare minimum you should have something like
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
... handle the upload
}
Your code is vulnerable to SQL injection. You do not escape any of the 3 values you're inserting into the database
You're creating the database record before making sure the file was successfully moved into the target directory. What happens if the file can't be written for any reason (as it is now with your problem)? The database will say it's there, file system will say it isn't
You're not checking for file collisions. If two seperate uploads send "file.txt", the second upload will overwrite the first one.
You're storing the files with the user-supplied name, which is under user control. If this file is web-accessible, anyone with access to your upload form can upload anything they want (e.g. a php file) and the server will happily execute it for them.