1

my form is to upload an image for a user. the images are stored in a folder, and the path is supposed to be stored in the db, but it is not. that is, the image is properly being uploaded to folder, but the path is not being saved to db.

ive tried two totally different queries, but neither has worked. also, i referenced both of these questions; How to upload images into MySQL database using PHP code and php image not uploading to database, the following is the code in question.

<?php

  // load current profile photo script

  $username='';
  $check_pic='';
  $check_pic = mysqli_query($connection,"SELECT profile_pic FROM users WHERE username='$username'");
  $get_pic_row = mysqli_fetch_assoc($check_pic);
  $profile_pic_db = $get_pic_row['profile_pic'];
  if ($profile_pic_db == "") {
  $profile_pic = "images/default_pic.jpg";
  }
  else
  {
  $profile_pic = "userdata/profile_pics/".$profile_pic_db;
  }


  //script for uploading profile photo

   if (isset($_FILES['profilepic'])) {
   if ((@$_FILES["profilepic"]["type"]=="image/jpeg")) {

   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $rand_dir_name = substr(str_shuffle($chars), 0, 15);
   mkdir("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name");

   if (file_exists("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
   {
    echo @$_FILES["profilepic"]["name"]." Already exists";
   }
   else
   {

//moves images to folder userdata/profile_pics...

   move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

 //saves image url to table...

  $profile_pic_name = (@$_FILES["profilepic"]["name"]);
  $profile_pic_loc = "C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/$profile_pic_name'";

  if($profile_pic_query = mysqli_query($connection, "INSERT INTO users (profile_pic) VALUES ('$profile_pic_loc')")){

   echo "successful upload";
     }
   else {

   echo "unsuccessful upload";
     }

  header("Location: profile.php");

  }
  }
   else
  {
   echo "unsuccessful";
  }
  }


echo"

<p>UPLOAD PROFILE PHOTO:</p>
<form action='' method='POST' enctype='multipart/form-data'>
<img src='$profile_pic' width='70' />
<input type='file' name='profilepic' /><br />
<input type='submit' name='uploadpic' value='Upload Image'>
</form>
";

?>

i tried the $profile_pic_query being part of the if statement, as seen above, and without the if statement. i also tried $profile_pic_name = file_get_contents(@$_FILES["profilepic"]["name"]); with and without file_get_contents, with no difference. this was the other format of my query i tried that didnt do anything different;

//saves image to folder userdata/profile_pics...

 move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

//saves image url to table...

 $profile_pic_name = @$_FILES["profilepic"]["name"];
 $profile_pic_query = mysqli_query($connection, "UPDATE users SET profile_pic='C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/$profile_pic_name' WHERE username='$username'");

and this is the session stuff...

<? php
session_start();
if (isset($_SESSION['user_login'])) {
$username = $_SESSION["user_login"];
}
else {
$username = "";
}
?>

so is there something wrong with the session, the query, or did i make a syntax error that im not being warned about for some reason?

****UPDATE**

Following suggestion below, I comment out the;

header(location: 'profile.php');

And I get apparently pretty popular error:

file_get_contents(.jpg): failed to open stream: no such file or directory

Common suggestions seem to revolve around ensuring that a proper tmp_file have been created, but that doesn't seem the case here?

Community
  • 1
  • 1
user74091
  • 301
  • 3
  • 13
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Sep 02 '16 at 02:34
  • @tadman noted. i am aware of the vulnerabilities, learning one thing at a time though. security will be next. – user74091 Sep 02 '16 at 02:36
  • Whats `mysqli_query($connection, $profile_pic_loc)`? You can't just send the image-url to MySQL and expect it to know what to do with it. – tkausl Sep 02 '16 at 02:39
  • @tkausl sorry, i corrected the query above, must have gotten deleted when i was editing for the post. – user74091 Sep 02 '16 at 02:44
  • also, it is not echo(ing) either "unsuccessful" or "unsuccessful upload", for whatever that is worth diagnostically. – user74091 Sep 02 '16 at 02:52
  • remove the 'header("Location: profile.php");'. Only then it will echo.. – Arun Krish Sep 02 '16 at 03:59
  • @user74091 If you do it properly the first time you don't have to worry about this sort of stuff later. You're learning, that's great. Don't half-ass it and waste all sorts of time tracking bugs that would never have happened if done by the book. – tadman Sep 02 '16 at 23:21
  • @tadman thanks for your advice, and dont take this the wrong way but if i knew how to do it properly the first time i wouldnt be here on SE asking this question in the first place. and despite it not working, i actually have put in quite a bit of effort into getting to this point. – user74091 Sep 03 '16 at 18:51

3 Answers3

1

You have several problems.

The first is that your query to store the location is wrong, your "insert ... Where..." form isn't correct. You should use "insert into ... values ..." as explained in MySQL documentation.

Second, you shouldn't use relative paths in functions such as move or mkdir. You can learn why here : PHP - Failed to open stream : No such file or directory

Third, you cannot use "header()" after echo. Header() sends headers of http response. This cannot be done once you have started echoing, since headers have already been sent.

Community
  • 1
  • 1
Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76
  • I have added a part to my answer. Also your query still seems wrong because you are not specifying the username for which to add the user picture. In any case it would be good that you as the full details of the errors you are getting into your question – Vic Seedoubleyew Sep 03 '16 at 10:42
  • i accepted your answer, i still have not figured out what is wrong but i think its best i figure out on my own, and with the help you have given me thus far, why its not working. – user74091 Sep 03 '16 at 18:54
  • Yes, there are quite a number of dimensions in your code, many things that you need to learn – Vic Seedoubleyew Sep 04 '16 at 17:31
0

i have since resolved this problem myself and would like to share for anyone of similar predicament... there were several distinct problems. well, i the errors i was receiving were seemingly erroneous. the errors were with respect to the portion of the script that was responsible for uploading the images from the client to the hdd of the server. the script was properly uploading and saving the images, however the errors i was getting were fixed when i removed uneccessary portions of the path.

the main problem was with the query, uploading the image url to the table, that wasnt happening at all. this was all corrected when i re-wrote the query. see all code below.

<?php



  $check_pic = mysqli_query($connection,"SELECT profile_pic FROM users WHERE username='$username'");
  $get_pic_row = mysqli_fetch_assoc($check_pic);
  $profile_pic_db = $get_pic_row['profile_pic'];
  if ($profile_pic_db == "") {
  $profile_pic = "images/default_pic.jpg";
  }
  else
  {
  $profile_pic = "userdata/profile_pics/".$profile_pic_db;
  }

  //script for uploading profile photo to hard disk

   if (isset($_FILES['profilepic'])) {
   if ((@$_FILES["profilepic"]["type"]=="image/jpeg")) {

   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $rand_dir_name = substr(str_shuffle($chars), 0, 15);
   mkdir("userdata/profile_pics/$rand_dir_name");

   if (file_exists("userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
   {
    echo @$_FILES["profilepic"]["name"]." Already exists";
   }
   else
   {
   move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

  //update table with url for photo

 $profile_pic_loc = "$rand_dir_name/".@$_FILES["profilepic"]["name"];


 $profile_pic_query = mysqli_query($connection, "UPDATE users SET profile_pic='$profile_pic_loc' WHERE username='$username'"); 


  if ($profile_pic_query) {

   header("Location: profile.php");
     }

   else 
   {
        die('failure');
     }
   }
  }
   }


   echo    " 

<div>
<p>UPLOAD PROFILE PHOTO:</p>
<form action='profile.php' method='POST' enctype='multipart/form-data'>
<img src='$profile_pic' width='70' />
<input type='file' name='profilepic' /><br />
<input type='submit' name='uploadpic' value='Upload Image'>
</form>
</div>
";


?>

changing;

mkdir("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name");

   if (file_exists("C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))

and;

move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"C:/xampp/htdocs/folder/userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

to;

mkdir("userdata/profile_pics/$rand_dir_name");

   if (file_exists("userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
   {

and;

move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);

corrected all the erroneous errors about 'filed to open file stream' and what not... although i still dont know what that means.

also correcting the query to;

$profile_pic_loc = "$rand_dir_name/".@$_FILES["profilepic"]["name"];


 $profile_pic_query = mysqli_query($connection, "UPDATE users SET profile_pic='$profile_pic_loc' WHERE username='$username'"); 


  if ($profile_pic_query) {

   header("Location: profile.php");
     }

   else 
   {
        die('failure');
     }

successfully inserted the image URL into the table. works like a champ now.

user74091
  • 301
  • 3
  • 13
-1

Change the code of mkdir() it may help you.

 mkdir("userdata/profile_pics/$rand_dir_name");

TO

 mkdir("userdata/profile_pics/$rand_dir_name/{$_FILES['profilepic']['name']}");
tpunt
  • 2,552
  • 1
  • 12
  • 18
Rana Aalamgeer
  • 702
  • 2
  • 8
  • 22
  • **warning** mkdir(): No such file or directory in C:\xampp\htdocs\folder\temp.php on line 49. – user74091 Sep 02 '16 at 16:58
  • **warning** move_uploaded_file(userdata/profile_pics/epQF01A72TZ6WqL/_DSC1232.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\folder\temp.php on line 57 – user74091 Sep 02 '16 at 16:59
  • **warning** move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA5D5.tmp' to 'userdata/profile_pics/epQF01A72TZ6WqL/_DSC1232.jpg' in C:\xampp\htdocs\folder\temp.php on line 57 – user74091 Sep 02 '16 at 17:00