1

I am trying to upload image to database and getting this PHP error message:

Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51

Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA9E6.tmp' to '/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg' in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51 Upload Fail.

Here is my php script:

<?php
require("include/functions.php");
check_session();

$logged_user = $_SESSION['username'];

if(isset($_FILES['avator']['name']) && $_FILES['avator']['tmp_name'] !=""){


    //setting file properties
    $fileName = $_FILES['avator']['name'];
    $filetmpLoc = $_FILES['avator']['tmp_name'];
    $fileType = $_FILES['avator']['type'];
    $filesize = $_FILES['avator']['size'];
    $fileErrMsg = $_FILES['avator']['error'];

    //explose the filename extention into an array
    $kaboom = explode('.',$fileName);
    $fileExt = end($kaboom);
    list($width ,$height) = getimagesize($filetmpLoc);
    if( $width <10 || $height <10 ){

        //the image has not dimenssion
        echo 'The Image has no dimension.Try again!';
        exit();


        }else{
            // The image is has dimension so its OK

            $db_file_name = rand(100000000000,999999999999).".".$fileExt;
            //check the size of the image
            if($filesize > 1048576){

                echo 'Your avator file size was larger than 1mb.';
                exit();

                }else if(!preg_match('/\.(gif|png|jpg)$/i',$fileName)){
                    echo"Your avator file was not JPG,PNG or GIF type.Try again.";
                    exit();

                    }else if($fileErrMsg == 1){

                        echo "Unknoan Error occured. Upload Fail.";
                        exit();

                        }


                        //move uploaded avator
                $moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
                if( $moveResult !=true){

                    echo 'Upload Fail.';
                    exit();

                    }else{

                        //resize the image
                        include_once("include/resizeimage.php");
                        $target_file = "user/$logged_user/$db_file_name";
                        $resize_file ="user/$logged_user/$db_file_name";
                        $wmax = 200;
                        $hmax = 230;
                        img_resize($target_file,$resize_file,$wmax,$hmax,$fileExt);
                        $sql = "UPDATE mygust SET avatar = '$db_file_name' WHERE username='$logged_user' LIMIT 1";
                        $query = mysqli_query($con,$sql);
                        mysqli_close($con);
                        exit();



                        }


            }


    }

 ?>

My HTML code is:

   <form id="u_pro_pic" method="post" enctype="multipart/form-data" onSubmit="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<h2>Set your Profile Avator</h2><br>

<div id="av_wrap"><div id="avator_div"><img src="image/blank-profile.png" class="avator" title="Chose a file to upload"  onClick="triggerUpload(event,'avator')"></div>
<div id="ad_clarleft">
<input type="button" class="add" title="Choose a file to upload"  onClick="triggerUpload(event,'avator')" value="Add Avator"><br>
<hr>
<p>These brethren have uploaded their's and you should too. </p>
</div>
</div>



<input name="avator" type="file" id="avator" form="u_pro_pic" onChange="readURL(this)">
<input type="submit" name="u_avator" id="sumit" class="avt" value="Upload">

</form>

Please any help would be much appreciating.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
James Favour
  • 97
  • 1
  • 2
  • 9
  • 1
    Try using absolute path when moving the file – Dimitar Stoyanov Oct 31 '15 at 13:26
  • your file name follow minus symbol -416649605.jpg try replacing this – Azmat Karim Khan Oct 31 '15 at 13:26
  • Please make sure that the directories are exists where you are moving the images. – Rizwan Khan Oct 31 '15 at 13:29
  • @Azmatkarim. I really don't understand what you saying... can you write something coding ?? – James Favour Oct 31 '15 at 13:29
  • @James change $db_file_name to **$db_file_name ="test.jpg";** and try, Let me know what yo get – Azmat Karim Khan Oct 31 '15 at 13:33
  • Why does this question have the flag `phpmyadmin`? That software is nowhere involved! – arkascha Oct 31 '15 at 13:34
  • @Azmatkarim...I got. Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/test.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51 – James Favour Oct 31 '15 at 13:39
  • @Fred-ii-...If I click on the arrow down to accept answers it says I have to gain 16 reputation. I am sorry. – James Favour Oct 31 '15 at 13:41
  • Add error reporting to the top of your file(s) right after your opening PHP tag for example ` – Funk Forty Niner Oct 31 '15 at 14:07
  • @Fred-ii- : Thank you...well noted. – James Favour Oct 31 '15 at 14:08
  • You're welcome @JamesFavour – Funk Forty Niner Oct 31 '15 at 14:08
  • @JamesFavour You have some javascript happening also and we don't know what that does and if it's adding to the possible failure. Try it without the javascript and as pure PHP and use error reporting as I outlined in my comment above. It might just be a folder permissions issue and/or a path issue. – Funk Forty Niner Oct 31 '15 at 14:10
  • @JamesFavour you're using sessions also. Make sure it was started with `session_start();` at the top of all files using sessions. Error reporting will also tell you if there's anything wrong with it. – Funk Forty Niner Oct 31 '15 at 14:13
  • @Fred-ii- : upon turn off error reporting, upload was not successful because the is a statement where it check to see if file was moved successfully. and because it wasn't able to move file it php echo Upload fail. – James Favour Oct 31 '15 at 14:13
  • @Fred-ii- : the admin can delete this post since there is no answer I will try and change the file upload method. maybe I can store everything in database in the BLOB file type – James Favour Oct 31 '15 at 14:15
  • @JamesFavour another thing I see failing is this `$logged_user` in your `move_uploaded_file` area. That folder needs to exist in order to be able to write to it. You will need to implement `mkdir` in there to first create the folder. And `"/upload/` implies a server path which won't work. It needs to either be `"/var/usr/public/upload/` or `"upload/` if running the script from the root or `"../upload/` as a relative path. That's the best help I can offer and you would need to figure out how to create the folders or just get rid of the `$logged_user` in order to see if it does upload. – Funk Forty Niner Oct 31 '15 at 14:18
  • @JamesFavour If you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html. However, when using a BLOB to insert into the db directly, you will have to use `mysqli_real_escape_string()` for that. Otherwise it won't work. http://php.net/manual/en/mysqli.real-escape-string.php – Funk Forty Niner Oct 31 '15 at 14:19
  • @JamesFavour You will need to flag your question if you want the mods to delete the question. However, I can write up an answer with the comments I used above to outline what is "not" happening, due to the fact that the error you received is due to the folders not being created and must first exist before writing to those folders, which must first exist. However this part of the filename `-416649605.jpg` am not entirely sure if that is in fact the file that is to be uploaded. If not, then the hyphen is coming from somewhere. Maybe something missing before the hyphen? – Funk Forty Niner Oct 31 '15 at 14:26
  • @JamesFavour So, what did you decide to do? Flag to delete or have me post an answer (the answer though may not completely solve your issue, but most of it anyway). Let me know, *cheers* – Funk Forty Niner Oct 31 '15 at 14:35
  • @Fred-ii- : ok give a try on it and let me see how good it will work because am confused.LOL LOL – James Favour Oct 31 '15 at 14:52
  • @JamesFavour I posted an answer for you below. However, I will not be able to provide further help on it. I have given you enough information in there to get you started and believe I have covered most of the issues with your code, good luck. *Cheers* – Funk Forty Niner Oct 31 '15 at 15:29

3 Answers3

0

PHP tries to move your uploaded file to a folder that does not exist:

//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");

The path "/upload" does not look like a correct windows path. Change it to something like "C:\xampp\htdocs\learnphp\upload". Create this folder manually if it does not exist.

//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"C:/xampp/htdocs/learnphp/upload/$logged_user/$db_file_name");
maxhb
  • 8,554
  • 9
  • 29
  • 53
0

Replace your $moveResult statement with the following two statement as you have to store the file in folder with a specific name.

$destination = "./".$_FILES['avator']['name'];

$moveResult = move_uploaded_file( $_FILES['avator']['tmp_name'],$destination);
oreopot
  • 3,392
  • 2
  • 19
  • 28
  • @JamesFavour Check the updated code. for the time being it will move uploaded file to the folder where your `index.php` is located. – oreopot Nov 01 '15 at 04:09
0

The reason why you're getting an error on the upload, is that the folder itself does not exist; least that's the impression I am getting from it and to be honest, we don't know if efc5ad334bca9f31b19d85a6cc2ada57 exists or not.

Sidenote: Use file_exists() which is referenced further down in this answer.

  • Since you are using sessions for $logged_user as the username session array, make sure the session was started inside all files using sessions. session_start(); must reside inside all files, and at the top of your code.

It is good practice to check if the session is also set using isset() or !empty().

References:

If not (which am pretty sure it doesn't), you would first need to create it using the mkdir() function.

The syntax is: mkdir("/path/to/my/dir", 0700); - 0700 can be changed to 0755 which is the usual setting for folders and it must be set so that the folder can be written to, using chmod.

The syntax being, one of the 3 listed from the manual:

chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode

So, you will need to use the mkdir() function after the session file and before "moving" it to the folder created by $logged_user and its associated name.

I.e.:

mkdir("/path/to/your/dir", 0700); // you can use variables here
$moveResult = move_uploaded_file(...);

This part of your code /upload/ suggests using a full server path syntax.

move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name")

Either you use what your full server path is, for example:

/var/usr/public/upload/

or as referenced in another answer given C:/xampp/htdocs/learnphp/upload/

or a relative path:

I.e.:

upload/ or ../upload/ depending on the execution location of your script. The former being if executed from the root of the public area.

Nota: I am unsure if -416649605.jpg is the actual filename being uploaded, or if there is anything missing before the hyphen, or the hyphen is being added somewhere. You will need to look into that.

Pulled from my comment:

Now, if you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html.

However, when using a BLOB to insert into the db directly, you will have to use mysqli_real_escape_string() for that, otherwise it won't work; you will get a syntax error thrown back.

Reference:

So, keep on using error reporting until you can figure out where the problems may be occuring.

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// if using MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

Also add or die(mysqli_error($con)) to $query = mysqli_query($con,$sql); to check for database errors.

Reference:

Additional reference:

Footnotes:

Your code in its present state is open to an SQL injection. Use a prepared statement

References:

I believe I have given you enough information in order to point you in the right direction that will and hope will lead you to success, cheers!

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141