Image upload to mysql - php

My site is able to upload a file but I don't understand how to get the path to the file for the database query. When someone uploads an image, the path to the image should get directly inserted into the users table in the userpic field. How can I achieve this?
<?PHP
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'],'files/'.$_FILES['file']['name']);
session_start();
$username = $_SESSION['user'];
$userpic = ???? // <-- what am i supposed to call here to put the path to my image file
include ("connect.php");
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$userpic);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "no files";
}
?>

If you store files using the name provided by the client when the file is uploaded, you will potentially overwrite images (e.g. if two users upload me.png) - it would be much better to use the username to store the images, and then you don't even need the mysql table to connect users to their pics..
<?php
session_start();
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$newpath = 'files/'.$username;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
In this code we use the username from the session, and check its not blank.
We then use this to store the image in your files folder.
Note this ignores a number of security issues:
Including ../ in your username which would cause the file to be saved outside of the files directory.
This may not be an issue if you have already validated the username, another solution would be to create a hash of the username and using this instead: $newpath = 'files/'.md5($username);
Not checking for errors, or verifying the file is indeed an image.
http://php.net/manual/en/features.file-upload.errors.php
PHP image upload security check list
How are these images going to be used after this?
If the files directory is within your htdocs, the contents will be available for all - it would probably be better to store it outside of your htdocs
e.g. $newpath = '/var/myappdata/userimages/'.md5($username);
You could then create another file userimage.php which reads the file:
<?php
session_start();
$username = $_SESSION['user'];
$path = '/var/myappdata/userimages/'.md5($username);
readfile($path);
This allows you to do additional checks e.g. that the user is allowed to see the image.
There is still a huge amount that could be covered here, hopefully this gives you enough to move forward, but do please read more about file upload security before putting this into production.
Your original question
If you did want to store information about the image in your database you could do something like this:
<?php
session_start();
include ("connect.php");
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$filename = basename($_FILES['file']['name']);
$newpath = 'files/'.$filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$filename);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
As I said though - you will run into conflicts if two users upload the same file.

You aren't going to want to store the entire URL in the database. You just need the path to where it is on the server. That is the part where you are moving the tmp file to a new location. In your case it would be the following.
$userpic = 'files/'.$_FILES['file']['name'];

Related

Uploading files using php very slow in xampp

I am new for developing.I have opted for php to learn coding.So I might make mistake as I learn by myself, kindly clarify my doubts.
I have problem in uploading files using php to a folder.What I really do is, I upload a file and the file is saved in a folder and the name of the file alone inserted in the database. While uploading the file I do copy the file to another folder which will be used for the editing purpose so that the original file will not be disturbed.Here the problem I get is, the file is uploaded successfully as well as the name too inserted in database. But it take much time to get upload even the size of the file is small.It works good while I test using my local but when I come in real time this issue(slow uploading) I face. What the person incharge in uploading do is, uploading a file and opening a new browser and upload another file. When the new browser is opened the files get uploaded but in the previous browser it is still in process. The code I have written to copy the file to another folder is not executed as the new browser is opened to upload another set of files. I am using xamp cp v3.2.1.To minimize the execution time I have set the default Maximum execution time to 30. But unable to upload file fastly.
Below is my php coding:
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
?>
It takes much time because, each and everytime all the files are copied to the newfolder. This exceeds the execution time.Only copying the uploaded files makes uploading and copying files fast.

not able to upload files in specific directory

i have made a small image uploading system using php it was working fine but now when i tried to upload pics in a specific folder then it is giving errors and upload images in root folder only.
the php code is:
<?php
//checking if the user already has a directory or not.
if($r['directory']==0){
$query= "UPDATE user SET directory='1' where id='".$_SESSION['sess_id']."'";
mysqli_query($dbconn,$query);
$path='../akshay/work/'.$r['username'];
mkdir($path) or die("unable to create folder");
} if(isset($_POST['submit'])&& $r['directory']==1){
//uploading users work.
$path='../akshay/work/'.$r['username'];
$name=$_FILES['work']['name'];
$size=$_FILES['work']['size'];
$type=$_FILES['work']['type'];
$tmp_name=$_FILES['work']['tmp_name'];
$extension=strtolower(substr($name,strpos($name,'.') + 1));
//checking if the user has selected a file or not.
if(isset($name)){
if(!empty($name)){
//checking if the uploaded file is an image or not.
if($extension=='jpg'||$extension=='jpeg'&& $type=='image/jpeg'){
$location=$path;
if(move_uploaded_file($tmp_name,$location.$name)){
echo'uploaded succesfully';
}else{
echo'<p style=color:red;>please choose a file</p>';
}
} else {
echo'<p style=color:red;>format of the file must be jpg/jpeg</p>';
}
}
}
}
?>
i think the problem is in move_uploaded_file() function. plz help me fix this problem and please do tell me any other ways (if any) to do this. i am able to make directories using the first check.
the error is "undefined variable:dir_name "and prints the massage "uploaded succesfully".
i have did some editing in the code and now i am able to make a directory in the specified location but cant upload images in that folder instead it uploads the images in 'work' folder and with the username appended to the name of the image.
please help!!!
In else if part of your code, $dir_name is not defined.
So please update your code and add below:
else if(isset($_POST['submit'])&& $r['directory']==1){
$dir_name = $r['username'];
// your code continue..
Furthermore.. the code you are using is not good. as if if condition is true then the else if part will not be executed. so update your code as below:
<?php
//checking if the user already has a directory or not.
if($r['directory']==0){
$query= "UPDATE user SET directory='1' where id='".$_SESSION['sess_id']."'";
mysqli_query($dbconn,$query);
$dir_name=$r['username'];
$r['directory']=1;
mkdir($dir_name);
}
if(isset($_POST['submit'])&& $r['directory']==1){
$dir_name = $r['username'];
//uploading users work.
$name=$_FILES['work']['name'];
$size=$_FILES['work']['size'];
$type=$_FILES['work']['type'];
$tmp_name=$_FILES['work']['tmp_name'];
$extension=strtolower(substr($name,strpos($name,'.') + 1));
//checking if the user has selected a file or not.
if(isset($name)){
if(!empty($name)){
//checking if the uploaded file is an image or not.
if($extension=='jpg'||$extension=='jpeg'&& $type=='image/jpeg'){
if(move_uploaded_file($tmp_name,$dir_name.$name)){
echo'uploaded succesfully';
}else{
echo'<p style=color:red;>please choose a file</p>';
}
}
else
{
echo'<p style=color:red;>format of the file must be jpg/jpeg</p>';
}
}
}
}
?>
use this code ..
$directory ="../images/".$file_name;
move_uploaded_file($temp_name, $directory);
i think this will work for you

cannot upload images to mysql using php

I want to upload images to mysql server using php.
I have created html and sql connectivity but the image upload shows error.
I cant upload the image, it shows error of valid image i.e. you must upload jpeg,bmp,gif; and read/write in directory.
Can any1 help me solving this problem
the php file is
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Check to see if the type of file uploaded is a valid image type
function valid($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
//echo $file['type'];
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH = "image/";
$TARGET_PATH = $TARGET_PATH . basename( $_FILES['image']['name']);
$pimage = $_FILES['image']['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!valid($pimage))
{
$_SESSION['ERRMSG_ARR'] = array('You must upload a jpeg, gif, or bmp');
header("Location: admin.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['ERRMSG_ARR'] = array('A file with that name already exists');
header("Location: admin.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($_FILES['image']['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (p_category, p_name, p_quantity, p_desc, p_image) values ('$pcategory', '$pname','$pquantity','pdesc', '" . $pimage['name'] . "')";
$result = mysql_query($sql);
//Check whether the query was successful or not
if($result) {
$_SESSION['ERRMSG_ARR'] = array('Product added');;
$_SESSION['MSG_FLAG'] = 0;
session_write_close();
header("location: admin.php");
exit();
}else {
die("Query failed: ".mysql_error());
}
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['ERRMSG_ARR'] = array('Could not upload file. Check read/write persmissions on the directory');
header("Location: admin.php");
exit;
}
?>
I think
$pimage = $_FILES['image']['name'];
should be
$pimage = $_FILES['image'];
You probably missed this because your code is quite inconsistent - sometimes you use $pimage, while elsewhere you reference the $_FILES array directly. This makes it harder to maintain should the file field's name change. You could also type hint the valid() function to make PHP complain if $file isn't an array:
function valid(array $file) { ... }
What level of error reporting do you have set? It would highlight errors like trying to access undefined array keys.
See you are passing the image type in the line if (!valid($pimage))
But in the valid() function you are again trying to get the type of image $file['type'].
What George said should also work, but since you are making variables for the image type $ptype and name $pimage, you can use them itself.
So the changes should be $file['type'] becomes $file and $file['type'] & in the insert query $pimage['name'] becomes $pimage
I'm sure this solves it, Bahua ;)

Upload image to existing folder PHP

<?php
include('includes/db.php');
$drinks_cat = $_POST['drinks_cat'];
$drinks_name = $_POST['drinks_name'];
$drinks_shot = $_POST['drinks_shot'];
$drinks_bottle = $_POST['drinks_bottle'];
$drinks_availability = 'AVAILABLE';
$msg = "ERROR: ";
$itemimageload="true";
$itemimage_size=$_FILES['image']['size'];
$iname = $_FILES['image']['name'];
if ($_FILES['image']['size']>250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$itemimageload="false";}
if (!($_FILES['image']['type'] =="image/jpeg" OR $_FILES['image']['type'] =="image/gif" OR $_FILES['image']['type'] =="image/png"))
{$msg=$msg."Your uploaded file must be of JPG , PNG or GIF. Other file types are not allowed<BR>";
$itemimageload="false";}
$file_name=$_FILES['image']['name'];
$add="images"; // the path with the file name where the file will be stored
if($itemimageload=="true")
{
if (file_exists($add) && is_writable($add))
{
if(move_uploaded_file ($_FILES['image']['tmp_name'], $add."/".$_FILES['image']['name']))
{
echo "Image successfully updated!";
}
else
{
echo "Failed to upload file Contact Site admin to fix the problem";
}
}
else
{
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
echo $msg;
}
$dir = $add."/".$iname;
echo "<BR>";
// Connects to your Database
mysql_query("INSERT INTO `product_drinks`(`drinks_id`, `drinks_cat`, `drinks_name`, `drinks_shot`, `drinks_bottle`, `drinks_image`, `drinks_availability`) VALUES (NULL,'".$drinks_cat."', '".$drinks_name."','".$drinks_shot."','".$drinks_bottle."','".$dir."','".$drinks_availability."')") or die("insert error");
Print "Your table has been populated";
?>
The code I'm working on works but i have to create a new "image" folder for my admin folder. Is there any way that I could upload the file outside the admin folder and move it to to the original "image" folder". I know it's quite confusing but my directory looks like this.
clubmaru
-admin
-images
-css
-images
-js
You may be looking for PHP's rename function. http://php.net/manual/en/function.rename.php
Set the oldname parameter to the file (with its path) and the newname parameter to where you want it to be (along with the new path, obviously)
Just ensure the "image folder" you want to move the file to has the correct permissions set ensure it's writable. You also may want to consider changing the parameter in your move_uploaded_file to put the file where you want it in the first place!
Yes there is a way, you need to change the path. Right now you have the path as images/$name which means that it will put the file in the images directory found in the local directory to the script that is running.
Using directory layout:
clubmaru
->admin
->script.php (the upload file)
->images
->css
->images
->js
You make the path relative (or find another alternative)
$add="../css/images";
This means, go up a directory, go into css then into images.

PHP File Validation using If statements uploads

Hi I am quite new to php but i have been following some tutorials but they don't seem to work so I have tried to adapt them.
I have tested this code and it works to a point but theres something else I can't get my head around, the php file is not uploading (fine) but the details are still being writen to the datbase although the $ok is spose to be set to 0 (not fine). It might be easier if explain what is ment to happen here:
-The User can upload gif or jpeg files. Details added to the db.
-The User can upload no file as a default will be used. Details added to the db.
-The User should not be able to upload any other file. No record should be on the db, user should have to try again.
My Code so far:
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=0;
//This gets all the other information from the form
$name= mysql_real_escape_string ($_POST['nameMember']);
$bandMember= mysql_real_escape_string ($_POST['bandMember']);
$pic= mysql_real_escape_string ($_FILES['photo']['name']);
$about= mysql_real_escape_string ($_POST['aboutMember']);
$bands= mysql_real_escape_string ($_POST['otherBands']);
$uploaded_size=$_FILES['photo']['file_size'];
if ($uploaded_size > 350000)
{
echo "Your file is too large, 35Kb is the largest file you can upload.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
if ($uploaded_type =="image/gif")
{
echo "GIf<br>";$ok=1;
}
if (empty($pic)){
echo "You haven't uploaded a photo, a default will be used instead.<br/>";$ok=1;}
if ($ok==0)
{
Echo "Sorry your file was not uploaded, please try again with the correct format.";
}
//If everything is ok we try to upload it
else
{
// Connects to your Database
mysql_connect("localhost", "*******", "******") or die(mysql_error()) ;
mysql_select_db("project") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO dbProfile (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br/>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
else {
//Gives and error if its not
echo "<p>If you have uploaded a picture there may have been a problem uploading your file.</p>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
}
?>
Cheers in advance. CHL
The error probably is this if statement:
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
Because every time you upload an image that does not have a content type that equals "image/jpeg", $ok evaluates to 1, so everything gets written to the database.
But also notice, that just checking the MIME type like this can get you into trouble, since the user is able to fake the MIME type of a file.
You could use Imagick to get the correct image MIME type, for example. See more details here: http://de2.php.net/manual/en/function.imagick-identifyimage.php
Edit: Just noticed, that $uploaded_type does not get initialized anywhere in your script. As I said, you can do a rough estimation of the MIME type by using $_FILES['photo']['type'].

Categories