简体   繁体   中英

PHP file upload Issues - Can't Move uploaded File

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.

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.

Ie:

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:

Ie:

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!

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");

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM