Can you perhaps tell me why I'm getting this error?

I'm trying to upload a image to a database through php and I'm getting this error the whole time in my picUpload.php

These are the errors I'm getting:

Warning: move_uploaded_file(avatars/beetgejo.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in C:\xampp\htdocs\picUpload.php on line 27

AND

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\xampp\tmp\php206A.tmp' to 'avatars/beetgejo.jpg' in C:\xampp\htdocs\picUpload.php on line 27

and here is my picUpload.php

<?php 
 include 'connect.php';
 include 'header.php';

 //This is the directory where images will be saved 
 $target = "avatars/"; 
 $target = $target . basename( $_FILES['file']['name']); 

 //This gets all the other information from the form 
 $pic_location=($_FILES['file']['name']); 

 //Writes the information to the database 
 $sql = "INSERT INTO users (pic_location) VALUES ('$pic_location')" ; 

 //Writes the photo to the server 
 if(move_uploaded_file($_FILES['file']['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"; 
 } 
 else { 

 //Gives and error if its not 
 echo "Sorry, there was a problem uploading your file."; 
 } 
 ?>

I DON'T KNOW WHAT'S WRONG IN LINE 27! If you can help me solve it, it'll be awesome! Thanks!

a few posibilities.

-check the permissions on both the source and destination folders. Make sure php can write to these.

-It might have to do with the destination not being complete. for your target try

$target=$_SERVER['DOCUMENT_ROOT'] . "/avatars/" . basename( $_FILES['file']['name']);

Awesome stuff! Thank you ajbest!

I managed to upload the picture and everything now BUT my problem now is that I want to INSERT the location path of the uploaded picture to the user's pic_location in the database and I don't know how the query will look if I want to achieve that.

The member is logged in when he uploads the pic so the SESSION is running.

I will give you my code to have a look see and if you can spot what to do...

Thanks

My picUpload.php (Where I uploaded the picture and where I want to INSERT the location path into the user's pic_loaction column in the table users)

<?php 
	 include 'connect.php';
	 include 'header.php';
	 
	 //This is the directory where images will be saved 
	 $target=$_SERVER['DOCUMENT_ROOT'] . "/images/" . basename( $_FILES['file']['name']); 
	 
	 //This gets all the other information from the form 
	 $pic_location=($_FILES['file']['name']); 
	 
	 //Writes the information to the database 
	 $sql = "INSERT INTO users (pic_location) VALUES ('$pic_location')" ; 
	 
	 //Writes the photo to the server 
	 if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) 
	 { 
	 
	 //Tells you if its all ok 
	 echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory"; 
	 } 
	 else { 
	 
	 //Gives and error if its not 
	 echo "Sorry, there was a problem uploading your file."; 
	 }
	 
	 ///////////////////////////////
	 ////////// HELP HERE //////////
	 ///////////////////////////////
	 
	 //Putting the storage path in the logged in user's pic_location path
	 //HOW WILL THE QUERY LOOK IF I WANT TO ADD THE PATH OF THE UPLOADED PICTURE TO THE USER'S pic_location IN THE DATABASE TABLE???
	 
	 $sql = "INSERT INTO
					users(pic_location)
				VALUES('" . mysql_real_escape_string($_POST['pic_location']) . "',NOW(),0)";
										
		$result = mysql_query($sql);
		if(!$result)
		{
			//something went wrong, display the error
			echo 'Error!';
		}
		else
		{
			echo 'Success!';
		}

?>

my profile.php

<?php
	include 'connect.php';
	include 'header.php';
		
		if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
			{
				//the user is not an admin
				echo '<br/>';
				echo 'Sorry! You have to be <a href="/signin.php"><b>logged in</b></a> to view your profile <a href="signup.php" title="Become a registered user!"></a>.';
				echo '<br/><br/>';
			}
			else
			{
				echo '<h2>Profile of </h2>'.$_SESSION['user_name'];
				echo '<h2>Info about you: </h2>';
				echo '<img src="beetgejo.jpg"/>';	echo'<pp><a href="#" title="Change your profile picture">edit</a></pp>';
				echo '<br/><br/>';
				echo '<b>Logged in as: </b>'.$_SESSION['user_name'];	echo'<pp><a href="#" title="Change your user name">edit</a></pp>';
				echo '<br/><br/>';
				echo '<b>Your email address: </b>'.$_SESSION['user_email'];	echo'<pp><a href="#" title="Change your email address">edit</a></pp>';
				echo '<br/><br/>';
				echo '<b>Your user level: </b>'.$_SESSION['user_level'].'   (1 = admin AND 0 = user)';
				echo '<br/><br/>';
				echo '<b>Your friends: </b> // FRIENDS';
				
				//echo 'Welcome, ' . $_SESSION['user_name'] . '! <br /><br/><br/><a href="index.php"><b>Proceed to the link sharing</b></a>.';
				///////////////////////////////
				/// adding users as friends ///
				///////////////////////////////
				
				//while($user = mysql_fetch_array($result))
				//echo $user['user_name'].' 
					//<a href="addfriend.php?user='.$user['id'].'">ADD TO FRIENDS</a><br/>';
				echo 'Do you want to upload or change your profile picture?';
				echo '<br/><br/>';
				echo '<form action="picUpload.php" method="post" enctype="multipart/form-data">
						<label for="file">Filename: </label>
						<input type="file" name="file" id="file"/>		
						<br/>
						<input type="submit" name="submit" value="Upload" />
					 </form>';
				
				//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
				
				
			}
			include 'footer.php';
?>

and my database.sql

CREATE TABLE users (  
user_id     INT(8) NOT NULL AUTO_INCREMENT,  
user_name   VARCHAR(30) NOT NULL,  
user_pass   VARCHAR(255) NOT NULL,  
user_email  VARCHAR(255) NOT NULL,  
user_date   DATETIME NOT NULL,  
user_level  INT(8) NOT NULL,  
pic_location  VARCHAR(255) NOT NULL,  
UNIQUE INDEX user_name_unique (user_name),  
PRIMARY KEY (user_id)  
);

CREATE TABLE categories (  
cat_id          INT(8) NOT NULL AUTO_INCREMENT,  
cat_name        VARCHAR(255) NOT NULL,  
cat_description     VARCHAR(255) NOT NULL,  
UNIQUE INDEX cat_name_unique (cat_name),  
PRIMARY KEY (cat_id)  
);

CREATE TABLE topics (  
topic_id        INT(8) NOT NULL AUTO_INCREMENT,  
topic_subject       VARCHAR(255) NOT NULL,  
topic_date      DATETIME NOT NULL,  
topic_cat       INT(8) NOT NULL,  
topic_by        INT(8) NOT NULL,  
PRIMARY KEY (topic_id)  
); 

CREATE TABLE posts (  
post_id         INT(8) NOT NULL AUTO_INCREMENT,  
post_content        TEXT NOT NULL,  
post_date       DATETIME NOT NULL,  
post_topic      INT(8) NOT NULL,  
post_by     INT(8) NOT NULL,  
PRIMARY KEY (post_id)  
);

This is a matter of personal preference on whether to store the full file path in the db or to just store the file name. I generally like to only store the file name because if I later deside that I want the folder to be located somewhere else I wont have to go back in and fix all the links in the db. Furthermore, If I access the image from different pages in different locations in my file structure I dont have to try and correct the path to make it correctly relative to the document. If this were my script I would use this for the storage;

//set destination info
   $dir=$_SERVER['DOCUMENT_ROOT'] . "/images/user_images/";  
   $temp=explode(".", basename($_FILES['file']['name']));
   $image_name= $temp[0] . rand(1000,9999) . $temp[1];//add in a random number as greater protection against duplicate file names.
//move the file
  if(move_uploaded_file($_FILES['file']['tmp_name'], $dir . $image_name)){ 
     mysql_query("UPDATE users SET pic_location = '$image_name' WHERE id = '".$_SESSION['user_id']."'");
  }

Then when it came time to display the image I would put the relative location of the user_images folder based on the doc location. assuming the doc was in the server root location:

<img src="images/user_images/<? echo $user['pic_location'];?>" />

Ah but I use sessions to get my info from the database tables

echo "<img src='" . $_SESSION['pic_location'] . "' />";

That code only gives me like a little dot thingy :( don't know why?

This is a matter of personal preference on whether to store the full file path in the db or to just store the file name. I generally like to only store the file name because if I later decide that I want the folder to be located somewhere else I wont have to go back in and fix all the links in the db. Furthermore, If I access the image from different pages in different locations in my file structure I dont have to try and correct the path to make it correctly relative to the document. If this were my script I would use this for the storage;

This is the good way! Don't store full path. You can store folder path to images in config file and retrieve it from there (A technique common in frameworks but will do great help here too)

Well this is how far I got! But I can't spot the error!!!! :(

Here is my picUpload.php document

<?php
             include 'connect.php';
             include 'header.php';

             if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
            {
                 //This is the directory where images will be saved 
                 $target=$_SERVER['DOCUMENT_ROOT'] . "/avatars/" . basename( $_FILES['file']['name']); 

                 //$target = "avatars/"; 
                //$target = $target . basename( $_FILES['file']['name']); 

                 //This gets all the other information from the form 
                 $pic_location=($_FILES['file']['name']); 

                 //Writes the information to the database
                 $sql = "UPDATE users SET pic_location='$target' WHERE user_id=" . $_SESSION['user_id'];
                 $result = mysql_query($sql);

                 if(!$result)
                {
                    //something went wrong, display the error
                    echo "Sorry, there was a problem uploading your file.";
                    //echo mysql_error(); //debugging purposes, uncomment when needed
                }
                else
                {
                    //Writes the photo to the server 
                    if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
                    {
                        //Tells you if its all ok 
                        echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory"; 
                    } 
                    else
                    {
                    //nothing
                    }
                }
            }
?>

and my profile.php where I want to display the image

<?php
        include 'connect.php';
        include 'header.php';

            //

            if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
                {
                    //the user is not an admin
                    echo '<br/>';
                    echo 'Sorry! You have to be <a href="/signin.php"><b>logged in</b></a> to view your profile <a href="signup.php" title="Become a registered user!"></a>.';
                    echo '<br/><br/>';
                }
                else
                {
                    echo '<h2>Profile of </h2>'.$_SESSION['user_name'];
                    echo '<h2>Info about you: </h2>';

                    //user_pass = '" . mysql_real_escape_string($_POST['user_pass']) . "'";
                    //DISPLAY THE IMAGE
                    $explodedPath = explode("C:/xampp/htdocs/avatars" , $_SESSION['pic_location']);
                    echo '<img src="http://[localhost]'.$explodedPath[1].'" />';

                    echo '<br/><br/>';
                    echo '<b>Logged in as: </b>'.$_SESSION['user_name'];    echo'<pp><a href="#" title="Change your user name">edit</a></pp>';
                    echo '<br/><br/>';
                    echo '<b>Your email address: </b>'.$_SESSION['user_email']; echo'<pp><a href="#" title="Change your email address">edit</a></pp>';
                    echo '<br/><br/>';
                    echo '<b>Your user level: </b>'.$_SESSION['user_level'].'   (1 = admin AND 0 = user)';
                    echo '<br/><br/>';
                    echo '<b>Your friends: </b> // FRIENDS';

                    //echo 'Welcome, ' . $_SESSION['user_name'] . '! <br /><br/><br/><a href="index.php"><b>Proceed to the link sharing</b></a>.';
                    ///////////////////////////////
                    /// adding users as friends ///
                    ///////////////////////////////

                    //while($user = mysql_fetch_array($result))
                    //echo $user['user_name'].' 
                        //<a href="addfriend.php?user='.$user['id'].'">ADD TO FRIENDS</a><br/>';
                    echo '<br/><br/>';
                    echo '<br/><br/>';
                    echo '<b>Do you want to upload or change your profile picture?</b>';
                    echo '<br/><br/>';
                    echo '<form action="picUpload.php" method="post" enctype="multipart/form-data">
                            <label for="file">Filename: </label>
                            <input type="file" name="file" id="file"/>      
                            <br/><br/>
                            <input type="submit" name="submit" value="Upload" />
                         </form>';

                    //NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER


                }
                include 'footer.php';
?>

I'm using picUpload.php to upload the image and profile.php to show the image in...

When I try to display my image in profile.php line 21 and 22 it doesn't show! :( I don't know what I'm doing wrong.

why do you do this?

$explodedPath = explode("C:/xampp/htdocs/avatars" , $_SESSION['pic_location']);
echo '<img src="http://[localhost]'.$explodedPath[1].'" />';

What I would do is:
I will store the full path in config file and store filename in session then I will simply concatenate the two!

It's to break the path. I don't think it;'s best when it's directly from C:/xampp/htdocs/avatars? What do you prefer doing? Because I already tried

echo "<img src='" . $_SESSION['pic_location'] . "' />";

and that does not work either?

my database table looks like this

CREATE TABLE users (  
user_id     INT(8) NOT NULL AUTO_INCREMENT,  
user_name   VARCHAR(30) NOT NULL,  
user_pass   VARCHAR(255) NOT NULL,  
user_email  VARCHAR(255) NOT NULL,  
user_date   DATETIME NOT NULL,  
user_level  INT(8) NOT NULL,  
pic_location  VARCHAR(255) NOT NULL,  
UNIQUE INDEX user_name_unique (user_name),  
PRIMARY KEY (user_id)  
);

must I change the VARCHAR next to pic_location to something else?

It's for breaking the path! I think it's not good when you have the full path!

and I tried

echo "<img src='" . $_SESSION['pic_location'] . "' />";

and it also doe not work?

here is my table... I'm beginning to wonder if I must not change the VARCHAR next to pic_location to something else that is more eficient when working with images? Any ideas?

CREATE TABLE users (  
user_id     INT(8) NOT NULL AUTO_INCREMENT,  
user_name   VARCHAR(30) NOT NULL,  
user_pass   VARCHAR(255) NOT NULL,  
user_email  VARCHAR(255) NOT NULL,  
user_date   DATETIME NOT NULL,  
user_level  INT(8) NOT NULL,  
pic_location  VARCHAR(255) NOT NULL,  
UNIQUE INDEX user_name_unique (user_name),  
PRIMARY KEY (user_id)  
);

Sorry about the double post... :/

you can do is put the config file on root dir of your project (Not root of your web se) and put something like

define("DS", DIRECTORY_SEPARATOR);
define("BASE_PATH", dirname(realpath(__FILE__)).DS);
define("IMG_PATH", BASE_PATH."images".DS);

then include this file in the profile file and then with picture name in session thne

$pic  = IMG_PATH.$_SESSION['pic_location'];
echo $pic;

I use in MVC so it might need little polish to be used in your project but it should not be that hard!

you didn't tell us what helped you. BTW here is alternative to putting config in root dir. Just an idea
I have just given an Idea, it is not supposed to be copy and paste. For more info read comments.

<?php
/*Conf.php must have fields defining the full path of application
* something like $conf["base_url"]="http://example.com/site/";
* Since the config is global by just including file (config.php) then 
* you dont need to store full path in database. Path can be http or C:\\something\\server\\public_html
* to make things more easier you can add to config array the images path something like
* $conf["img_url"]="http://example.com/site/images/";
*/
session_start();
include $conf["base_url"]."include/config.php";
$pic_id = $_SESSION["profile_img"];
$img_path = $conf["base_url"].$pic_id;
echo "<img alt='Profile Image' src='$img_path' />";
?>

I just changed the entire path to the folder where the pictures are uploaded. Didn't think it liked the ENTIRE path... so yah, that's it! I rather not use config because I'm not so good or experienced with that... But thanks for all the help on the post! Really appreciate it guys!

J

I just changed the entire path to the folder where the pictures are uploaded. Didn't think it liked the ENTIRE path... so yah, that's it! I rather not use config because I'm not so good or experienced with that... But thanks for all the help on the post! Really appreciate it guys!

J

:)

you need to create a directory other wise known as a folder and create it with same name that your file sais it should goto for example uploads or files etc you see?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.