move_uploaded_file() creates .tmp but never moves to the destination directory

I have the following code:

[php]
$upload_dir = ‘…/media/flyer/’;

function bytesToSize1024($bytes, $precision = 2) {
$unit = array(‘B’,‘KB’,‘MB’);
return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).’ '.$unit[$i];
}

$sFileName = $_FILES[‘image_file’][‘name’];
$sFileType = $_FILES[‘image_file’][‘type’];
$sFileSize = bytesToSize1024($_FILES[‘image_file’][‘size’], 1);

echo <<<EOF

Your file: {$sFileName} has been successfully received.

Type: {$sFileType}

Size: {$sFileSize}

EOF;

//NO ERROR BUT NO TMP FILE MOVE
move_uploaded_file($sFileName[‘tmp_name’], $upload_dir.$sFileName[‘name’]);
[/php]

The issue is that the php###.tmp file is created in C:\Windows\Temp but never moved to the Destination Folder. I checked my PHPLog on the Server and there are no error and the page even displays that the file was received successfully.

FYI:

[ul][li]I own and manage the Server.[/li]
[li]It is a Test Environment.[/li]
[li]The Destination has "Everyone"with Full Control (For Testing)[/li][/ul]

What am I missing?

Thanks in advance.
Joe

this line:
$sFileName = $_FILES[‘image_file’][‘name’];

creates a string variable out of an array. Just as it should.

This line:
move_uploaded_file($sFileName[‘tmp_name’], $upload_dir.$sFileName[‘name’]);

Tries to move an array based on the NON-array string… Try this instead:
move_uploaded_file($sFileName, $upload_dir.$sFileName);

ErnieAlex,

Thank you for the quick response. I made the suggested changes ans still have same issue.

I tried twice and i got 2 temp files in the c:\windows\temp folder and no error log. I understand what you said about the array. I didn’t catch it as I did another tutorial that was drag and drop and didn’t realize that it was creating an array and that the bracketed text was referring to the array. The difference being, in that tutorial I was successfully moving the files.

Full Code is still the same with your suggested change.

[php]<?php
$upload_dir = ‘…/media/flyer/’;

function bytesToSize1024($bytes, $precision = 2) {
$unit = array(‘B’,‘KB’,‘MB’);
return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).’ '.$unit[$i];
}

$sFileName = $_FILES[‘image_file’][‘name’];
$sFileType = $_FILES[‘image_file’][‘type’];
$sFileSize = bytesToSize1024($_FILES[‘image_file’][‘size’], 1);

echo <<<EOF

Your file: {$sFileName} has been successfully received.

Type: {$sFileType}

Size: {$sFileSize}

EOF;

//NO ERROR BUT NO TMP FILE MOVE
move_uploaded_file($sFileName, $upload_dir.$sFileName);[/php]

Okay, I may have flying fingers and sleepy when I typed… LOL…
Here is the general way that files are moved when uploaded. Just a sampler first…
$target_path = “uploads/” . basename( $_FILES[‘uploadedfile’][‘name’]);
if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {
echo "The file “. basename( $_FILES[‘uploadedfile’][‘name’]). " has been uploaded”;
}else{
echo “There was an error uploading the file, please try again!”;
}
So, I showed this sample so you can see the basics. It includes a little error checking so you know if the file actually got uploaded or not. Now to alter your code to fit this version…
[php]

<?php function bytesToSize1024($bytes, $precision = 2) { $unit = array('B','KB','MB'); return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i]; } $upload_dir = '../media/flyer/' . basename($_FILES['image_file']['name']); if(move_uploaded_file($_FILES['image_file']['tmp_name'], $upload_dir)) { // File made it, now display the info... $sFileName = $_FILES['image_file']['name']; $sFileType = $_FILES['image_file']['type']; $sFileSize = bytesToSize1024($_FILES['image_file']['size'], 1); echo <<<EOF

Your file: {$sFileName} has been successfully received.


Type: {$sFileType}


Size: {$sFileSize}


EOF; }else{ echo "There was an error uploading the file, please try again!"; } [/php] Basically, it is a streamlined combined sample and your version. Should work. Let me know...

OK.

I copied and pasted your code.

No error in logs, No Results on html page, and no file move. It is still in Windows\Temp as php****.tmp @ 414 kb ???

I guess my basic questions are

  1. What is moving it to Windows\Temp? php, HTML or JScript?
  2. How am I retrieving the Windows\Temp\php****.tmp file by name and moving it since $sFilename = Actual File Name?

BTW, I created a simple test using the basic php example you provided and it does exactly the same thing.

[code]

Please select image file [/code]

and

[php]<?php
$target_path = “…/media/flyer/” . basename( $_FILES[‘uploadedfile’][‘name’]);
if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {
echo "The file “. basename( $_FILES[‘uploadedfile’][‘name’]). " has been uploaded”;
}else{
echo “There was an error uploading the file, please try again!”;
}[/php]

Sysinfo:
WinServer2008R2
IIS7
PHP5.3

But since it is late I will resume tomorrow.

I really appreciate the help. I am sure it is something small. I just can’t see it. And as you can see PHP is not my forte.

Well, The problem is that you are using an invalid name… You can not use *** in a filename!

Also, in your HTML the new version the file name used is: ‘image_file’ …
BUT, in your PHP, it is : ‘uploadedfile’ …

SO, that code would NEVER work! You have to change the 3 uploadedfile to image_file…

Also, did you check this folder “…/media/flyer/” ??? If the folder does not exist then nothing will copy.
Note: If you are in the root directory, this folder will not work. If you are in, let’s say a TEST folder, like this:
www.yourdomain.com/test/some filename.html Then, your PHP code is looking for:
www.yourdomain.com/media/flyer/ Caps count. So, it could just be the target is not in place.
If you running the HTML from /test/ and you change …/media/flyer to media/flyer then it looks for:
www.yourdomain.com/test/media/flyer/ Did that make sense. Sorry if you already know that!

The other question… The “move_uploaded_file” is what moves the file. The PHP system creates a temp file in the server’s temp directory, on a windows system, it is windows temporary folder. This file name is passed in the $_FILES array and that is what you move from. To the actual name. Oh, the ****'s you mentioned was probably the random number PHP made up for the uploaded file which is just a .tmp…

SO, not sure about your NEW version you switched to, but, my previous is acurate. Unless the folder is not set up correctly. Check that… Hope some of this helps!

Correct on the ****. Stands for Random Numbers, ;D and so that answer to Question 2 Answers a lot. Move Upload creates a file and therefore knows what the random filename is.

I told you it was late. I totally missed the filename matchup in the HTML to PHP Handoff.

The “NEW” version was just to test my logic and serverside. Because when I added the code you sent back, all reporting stopped in the HTML Side so I stripped it down into another less glorified version. I really want to nail down the one that I am working on as it will be the basis of my entire management console for the site.

I own the server and I manage it so in IIS “sitename/media/flyer” was created manually by me and currently has an everyone permission of full, and they are not virtual.

I think your first line says it all. I am passing a different filename then it is expecting. I will test some more later and report back.

Thanks again. This is very informative.

Quick update on folder structure:

sitename/admin/index.html (The upload HTML file we are discussing)
sitename/admin/upload.php

sitename/media/flyer

So pretty sure it the upload path should be:
‘…/media/flyer/’

Or as I have been all along, I could still be wrong. :o

Yes, that should be correct…

I will do some testing on my server later today and try to sort this issue out.

Oh, one more thing, does the upload folder have write permission enabled?

I have gotten it working. Went through another tutorial then went through my current code that you have been analyzing: Letter by Letter.

Outcome is testable at l2technotes.dyndns.org/admin/ (I plan on securing this with ACL) when development and testing are complete.

Here is the Complete Code. I believe a single image_file was out of sync or mistyped. IDK. So next is checking file_exists(). I’m sure I’ll be back for more. ;D

Thank you again for you help and patience. Hope to talk to you again soon ;).

HTML

[code]

Pure HTML5 file upload | Script Tutorials

Pure HTML5 file upload

Back to original tutorial on Script Tutorials

You can select the file (image) and click Upload button

        <div class="upload_form_cont">
            <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
                <div>
                    <div><label for="image_file">Please select image file</label></div>
                    <div><input type="file" name="image_file" id="image_file" onchange="fileSelected();" /></div>
                </div>
                <div>
                    <input type="button" value="Upload" onclick="startUploading()" />
                </div>
                <div id="fileinfo">
                    <div id="filename"></div>
                    <div id="filesize"></div>
                    <div id="filetype"></div>
                    <div id="filedim"></div>
                </div>
                <div id="error">You should select valid image files only!</div>
                <div id="error2">An error occurred while uploading the file</div>
                <div id="abort">The upload has been canceled by the user or the browser dropped the connection</div>
                <div id="warnsize">Your file is very big. We can't accept it. Please select more small file</div>

                <div id="progress_info">
                    <div id="progress"></div>
                    <div id="progress_percent">&nbsp;</div>
                    <div class="clear_both"></div>
                    <div>
                        <div id="speed">&nbsp;</div>
                        <div id="remaining">&nbsp;</div>
                        <div id="b_transfered">&nbsp;</div>
                        <div class="clear_both"></div>
                    </div>
                    <div id="upload_response"></div>
                </div>
            </form>

            <img id="preview" />
        </div>
    </div>
</body>
[/code]

[php]<?php

$target_path = “…/media/flyer/”;

$target_path = $target_path . basename( $_FILES[‘image_file’][‘name’]);

if(move_uploaded_file($_FILES[‘image_file’][‘tmp_name’], $target_path)) {
echo "The file “. basename( $_FILES[‘image_file’][‘name’]).
" has been uploaded”;
} else{
echo “There was an error uploading the file:”. basename( $_FILES[‘image_file’][‘name’]).
“, please try again!”;
}[/php]

GREAT! Glad you got it working… Since our last messages, I had this happen on another project I am working on here. It just will not show the uploaded file. So, I am going to test it on my live server and see what happens. But, that is off-topic.

Glad to see you solved it. And, hope this helps others by looking at your working version. Thanks for posting it!

Since Completing the Upload segment I venture into more depth.

I am now prohibiting anything but jpg files.
I am reaming the file so that it replaces a diplayed image on the Homepage.
Next I explored the option of renaming an existing file on the server.

Now I successfully:

[ul][li]Restrict File Type to .jpg[/li]
[li]Restrict File Type to .jpg[/li]
[li]Upload the Image “Anyfile.jpg”[/li]
[li]Rename the Existing file “Exactfile.jpg” to “00 Mon 12 Exactfile.jpg” using the Date() function[/li]
[li]Rename the file “Anyfile.jpg” to "Exactfile.jpg.[/li][/ul]

All that with this little bit of PHP code and a tag in HTML. b[/b]

I must express that none of this would have been possible (as easily) without your help.
Thank you again.

Working PHP Code
[php]<?php

$target_path = “…/media/flyer/”;
$date = Date(“d M y”);
$targetpath = $target_path . basename( $_FILES[‘image_file’][‘name’]);
$rentarget = “flyer.jpg”;

rename("…/media/flyer/flyer.jpg" , “…/media/flyer/” . $date . " flyer.jpg");
Sleep(1);
if(move_uploaded_file($_FILES[‘image_file’][‘tmp_name’], “…/media/flyer/flyer.jpg”)) {
rename($targetpath , $rentarget);
echo "The file “. basename( $_FILES[‘image_file’][‘name’]).
" has been uploaded and has been renamed flyer.jpg and will be displayed on the Home page.”;
} else{
echo “There was an error uploading the file:”. basename( $_FILES[‘image_file’][‘name’]).
“, please try again!”;
}[/php]

HTML Tag

<div><input type="file" name="image_file" id="image_file" accept="image/jpeg" onchange="fileSelected();" /></div>

Glad you got it working!

But, I wouldn’t use spaces in your filenames. That is usually not a good idea due to using filenames in displays. Using CSS, sometimes the filenames get broken up due to the space issue. Instead of spaces, they suggest using the underscore “_”… Well, just a thought! CONGRATS on the puzzle solved!

Good advice. Again. I can easily Change that.

On to my next Challenge.

Forcing the page to reload on backbutton press after uploading the Image so the image is automatically displayed without a refresh.

Well, glad you understand the filename issue. That can be a problem one day!

And, so, to refresh your “active” page, there are several ways to do it… It is different depending on your need. So, first, if you want it to refresh without the page actually refreshing, you can do this with JQuery, Javascript, hidden PHP iFrames and other ways… It gets a bit tricky, but, can be done. So, if you upload a picture, normally it is not shown immediately because it is just loaded into a gallery folder. Then, the code switches to the gallery display page which will show the newly uploaded display. (Possibly with another option to upload another picture…) So, to do that “dynamically”, you would have to have some way to load the pictures or data without changing the rest of the screen. There are tons of ways to this. You can use JQuery to load the data behind the scenes and then make them visible. Or, you could load the data using PHP in a hidden iFrame and then move the data to the correct area or just make the iFrame visible. And, several other ways, too.

So, I would suggest laying out an idea of what you would like to do thinking about the above ideas. Then, give us some further idea on which way you would like to try and we can help…

You give excellent advice.

In short, I have taken down the Dev site. But I think I will put it back up as I, admittedly, am going to need plenty of assistance. ;D

On the homepage of the Production Site there is a jpg file that is displayed.

I would like that jpg to self refresh when changed by the admin page via upload. This way the user doesn’t have to refresh their browser to reset the Cache state.

I am researching a way in HTML5 or CSS3 to do this.

The Current code is handled in the HTML and CSS:

[code]

​[/code]

Well, I not quite sure what you mean by dynamic. First, if you change a picture that is on a page, that is not a dynamic site. It is just an update on the site. Any user that logs in after you change a picture should get the new picture. The “cache” as you called it changes if the page changes. So, there are a hundred ways of doing that. the easiest is to create an ADMIN page that allows you to load a new picture or flyer. Then, in that code for updating, it changes the picture that would be loaded on the page. You can either store the name of the picture inside of a database and the page can load it from there, or just have an actual page called something and upload the new picture to that picture name. When a webpage sees a picture has been changed, it will load the new version.

So, just leave the code you have and just have the new flyer replace the old flyer. I think that should work.

A “dynamic” site would be one that changes the flyer every 5 minutes or other set time frame…

Hope that makes sense!

That makes sense. Problem is that the page doesn’t refresh on Back Button Submit, and I would like it to reload on entry, thus, loading the newly uploaded image.

Well, if your upload code uploads the file (flyer.jpg) as the same name, it should load the new version whenever someone goes to the page.

But, using the “back” button usually just loads the same page that is cached.
Now I understand what you want. Instead of using the “back” button, place a HREF anchor on your page just below the upload. This will cause the browser to reload the page.

Or, even better, just have your PHP uploading code switch back to the page using a header. That would also cause the browser to reload the page.

The “trick” here is to make the browser think it is going to a brand new page so it will check for changes and load anything that is new such as the flyer.jpg. Just don’t use the “back” button. Hope that helps!

Sponsor our Newsletter | Privacy Policy | Terms of Service