i'm currently making a website for my final year university project, which requires a photo upload function. Currently when a user uploads a photo, the photo is stored in a folder in the remote server. I need the images to go into a database and so I was wondering if anyone had any advice as to how to do this and where to place the code to send the uploaded content to the database within the following code, also I need for it to work where when each individual user uploads an image, they are all displayed for all to see, and not as it is currently, where only one image is displayed at a time and when the page is refreshed, the image disappears. Hope that all made sense, any help would be greatly appreciated. Thank you.
<?php include_once("home_start.php"); ?>
<h1>Upload your images here:</h1>
<div id="fileselect" style="border-bottom:thin #000000 solid; border- collapse:collapse">
<form id="frmSimple" action="home.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" id="filename" name="filename" size="10" /><br />
<input type="submit" id="submit" name="submit" value=" Upload " />
</form>
</div>
<div id="feedback">
<?php
// Determine whether a file was uploaded
if ($_FILES) {
// Put file properties into variables
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
// Determine whether file is png, jpg or other
switch($_FILES['filename']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
//default: ext = ''; break;
}
//validate against file type
// if $ext is empty string (therefore null or false) image is not a jpg or png
if($ext){
// validate against file size
if($size < 1000000){
// Create a safe name for the file and store in a safe location
$n = "$name"; // Could add .$ext to enforce file type
$n = ereg_replace("[^A-Za-z0-9.]","",$n); // Remove all except alphanumeric characters and
$n = strtolower($n); // Convert to lower case (platform independence)
$n = "uploaded_images/$n"; // Add folder to force safe location
move_uploaded_file($tmp_name, $n); // Move to the safe location and give it the safe
echo "<p>Uploaded image '$name' as '$n': </p>";
echo "<img src='$n' />";
}
else echo "<p>'$name' is too big - 50KB max (50000 bytes).</p>";
}
else echo "<p>'$name' is an invalid file - only jpg and png accepted.</p>";
}
else echo "<p>No image has been uploaded.</p>";
?>
</div>
<?php include_once("home_end.php"); ?>
I would highly recommend against it. Instead, stored the photos in a folder and reference their location from the database (i.e. a string pointing to their location on the filesystem).
However, if you're so inclined to store it in the database, you need to:
Get the file contents after upload
Ensure that the contents don't have any characters that would conflict with your SQL (easy solution is to encode it somehow; base64 perhaps?)
Perform your SQL insert
Again - this is a bad idea. Don't do it - save it to the filesystem.
Also, the following line:
move_uploaded_file($tmp_name, $n);
without any checks of file type, or file integrity, makes it trivial to upload a shell to your box.
Once after the file uploaded successfully get the uploaded image path.
$file_type='jpg'; //if you are using more than one type write a switch case
$file_size = filesize($file);
$fp = fopen($file,'r');
$content = fread($fp,$file_size);
$content = addslashes($content); //content is a binary data of the image
fclose($fp);
To save the image in database. Write a insert query with whatever fields you want $file_name, $file_type, $file_size and content. I am assuming you are able to connect to database successfully.
mysql_query("INSERT INTO Images (id,file_name,file_type,file_size,content)
VALUES ('bird', 'jpg',340kb,'binarydata')");
Related
<body>
<form action="#" enctype="multipart/form-data" method="post">
<input multiple="" name="img[]" type="file" />
<input name="submit" type="submit" />
</form>
<?php
mmysql_connect("localhost","root","");
mysql_select_db("multiple");
if(isset($_POST['submit'])){
$filename = $_FILES['img']['name']);
$tmpname = $_FILES['img']['tmp_name']
$filetype = $_FILES['img']['type'];
for($i=0; $i<=count($tmpname)-1; $i++){
$name =addslashes(filename[$i]);
$tmp = addslashes(file_get_contents($tmpname[$i]));
mysql_query("INSERT into img(name,image) values('$name','$tmp')");
echo "uploaded";
}
}
?>
</body>
</html>
I am trying to upload a simple image to my database So I can work on this user hosted site. So far nothing has worked. I'm dyin here. I've looked through so many tutorials.
From hitting an issue with file uploads before, it's much easier on the DB and your coding to upload your file to the server using 'move_uploaded_file()' and then provide a reference in your DB. In the above example, you are storing your file in a temporary folder ['tmp_name'], saving that file name, but then not transferring the file somewhere that won't delete it.
So for something generic to help:
$fileName $_FILES['img']['name'];
$fileType = $_FILES['img']['type'];
$fileLocation = $_FILES['img']['tmp_name'];
$newFileName = "newFileName.jpg";
$img = "folder/".$newFileName;
move_uploaded_file($fileLocation, "../folder/".$newFileName);
The reason for this is that when you save to the 'tmp' folder (which you must for a bit), the file is also renamed to a seemingly random set of characters. So you need to get that file location, move it to the folder of your choice, and also name it something findable. Then you can save the $img path in your DB and call it from anywhere (with some modification). It will take some playing with, but this should help.
To upload an image to the database directly from an uploaded file, you need to upload the base64 encoded version of the image. And also make sure that the field type of the image in your database is actually blog or LongBlog.
Here is the code to do that
$file = $_FILES['file'];
$filename = $file['name'];
$convert_to_base64 = base64_encode(file_get_contents($file['tmp_name']));
$base64_image = "data:image/jpeg;base64,".$convert_to_base64;
$query = mysqli_query($con, "INSERT INTO 'table'(image)VALUES('$base64_image')")
I'm trying to figure out how to allow image upload with the image showing up after it is uploaded. I have found this tutorial on uploading images but I'm not sure how to display them afterwards. Would I have to save it in the database then pull it up afterwards somehow?
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I think you would benefit from an uploading class or function that returns information for your uploaded image. This will help you store the results or display as you are looking to do. Here is one loosely based on what you provided with notation:
Form:
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Script:
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'];
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
To use:
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
RAW Feedback:
// This is what the array would look like on return of successful upload:
Array
(
[filename] => animal.png
[fullpath] => /data/19/2/133/150/2948313/user/2524254/htdocs/mydomain/uploads/animal.png
[localpath] => /uploads/animal.png
[filesize] => 35702
)
yes,you would have to save the path to the file in the database and fetch it but for your use case,you can save the path to a $_SESSION variable and then echo the path immediately the script is done.
But you first have to complete the file transfer with the move_uploaded_file function as without that,you would not be able to retrieve the file path as they are stored as temporary files and deleted once the script is interpreted
http://php.net/manual/en/function.move-uploaded-file.php
After this is done,you are to get the path to the file and use the normal img HTML tag
create <img src="" widht="" height="" /> forever u must move the image to directory path and now i get the image name from table after submit the form.. and given the url to img..example.. ur directory name uploads/img . now your file name save in database table as image01.jpg . sample
$img= 'select imagename from table name ';
if(count($img))
{
<img src="<?php echo 'uploads/img/'.$img" widht="10px" height="20px" /></div>
}
if you upload image on data base , data loading will be slow because image siz too large. better method is upload image in folder & save image file path in data base .when you retrieve image call image web root on image tag
example
Saving Filepath Of Uploaded Image To MySQL Database
GET image path
name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:
$check = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I only allow certain filetypes on upload in php?
How can I make the script below only allow .jpg images or .png images?
It uploads an image directory to a mysql table based on a session username match. Is it possible to restrict the file types? Because I only need .jpg or .png
if ($_POST['submit']) {
//get file attributes
$Name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
error_reporting(E_ERROR | E_PARSE);
if ($Name) {
$location = "avatars/$Name";
move_uploaded_file($tmp_name, $location ) or die('Failed to upload picture');
$query = mysql_query("UPDATE fgusers3 SET imagelocation='$location' WHERE name='$name'") or die("Your profile image has been uploaded!");
}}
echo "Upload your image below:
<form action='profilepic.php' method='POST' enctype='multipart/form-data'>
Profile Picture: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload'>
</form>";
if($_FILES){
$allowedExtensions = array("jpg","png");
foreach($_FILES as $key=>$val){
if(!empty($val['tmp_name'])){
$ext = end(explode(".",strtolower(basename($val['name']))));
if(in_array($ext,$allowedExtensions)){
$file = 'PATH_TO_UPLOAD'.basename($val['name']);
if(move_uploaded_file($val['tmp_name'],$file)){
//SUCCESS_MESSAGE
}
}else{
//FAIL_MESSAGE
}
}
}
}
You can use exif_imagetype($tmp_name) to check the actual type of the file based on its header. This checks the type based on the contents of the file, so it is the most reliable (e.g. it will give you the right information even if somebody gives you a JPG with a ".png" extension).
There is also the type property ($_FILES['myfile']['type']), which will give you the MIME type that the browser claims the file is. However, this cannot be trusted if someone maliciously forges the request.
You can try using pathinfo & exif_imagetype
if(pathinfo($Name,PATHINFO_EXTENSION) != "jpg" || exif_imagetype($Name) != IMAGETYPE_JPEG)
{
// throw error
}
See More Info to detect Fake Images
$imageType = getimagesize($tmp_name);
switch ($imageType['mime'] != "image/jpg" OR $imageType['mim'] != "image/png") {
//error code here.
}
It is a bit safer than checking the extension, as the extension can be changed easily. The mime type can be changed as well but requires more knowledge xD
Of course, you can limit by file extension, but it's not safe. You can try rename a gif-file and upload it. A little bit safer is using mime-type to detect file type (but still no guarantee). Look at:
How do I find the mime-type of a file with php?
I think more safer is trying to get size of image or if convert to another image type is successful.
$whitelist = array(".jpg",".png");
foreach ($whitelist as $item) {
if(preg_match("/$item\$/i", $_FILES['uploadfile']['name'])) {
$uploaddir='uploads/uploads_image/';
// or code
}
}
I wonder whether someone can help me please.
I've created this form which allows users to record details about a specific location they've visited and as each location is saved a unique incrementing 'locationid' is saved as part of the mySQL record.
I've extended this further and when they click on the add 'Add Image' Button they will be able to save image files connected to the 'location' record created. This is done via the code below which saved the original image file and thumbnail version into a folder on my server.
<?php
//define a maxim size for the uploaded images
//define ("MAX_SIZE","100");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
$title = ($_POST['title']);
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image == '')
{
echo '<b> Error! </b> - You <b> must </b> select a file to upload before selecting the <b> "Upload image" </b> button. Please try again.';
$errors=1;
}
else
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 1150000)
{
echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=$title.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<b> Error! </b> Your file has not been loaded';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/thumbs/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
echo '<br><b> Success! </b> - Your image has been uploaded</br>';
echo '<img src="'.$thumb_name.'">';
}
?>
<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="text" name="title" ></td></tr>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
The problem I'm having is that I can't find a way of linking the 'location (parent)' record and the 'image (child)' record. Because the image upload is part of the parent record creation, the unique 'locationid' field hasn't been created.
I just wondered whether someone, perhaps with a lot more experience that I could suggest a way of overcoming this problem?
Many thanks and kind regards
Then uploading an image, save it's path on server to some storage (PHP session for example)
When saving your location, link images from session with created location and remove them from session (but not from server storage)
If action is cancelled - remove saved images from session and from server storage.
Also you need some garbage colection for the case if user just closing his browser without pressing any "cancel" buttons in yout UI.