Upload files not working, whats wrong with this code? - php

This is the PHP code used for the upload:
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
} else { echo "Error"; }
When I test the script, it says "The file has been uploaded successfully." but when I check the FTP server, it hasn't really...
Also, if you need to know, here's the HTML codes:
Form tag:
<form name="profilestyle" action="account.php?action=profiletheme" method="post" enctype="multipart/form-data">
Input tag:
<input type="file" name="bgimage" />
Extra Information:
Yes, I remembered the CHMod the uploads directory

Odd, the code looks fine as far as I can see.
Can you use file_exists() to check whether the file exists, but maybe is not visible to your FTP user?
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file '$upload' has been uploaded successfully.";
if (file_exists($upload)) echo "And it exists! It is ".filesize($upload)." bytes big.";
else echo "But it doesn't exist.";
} else { echo "Error"; }

You also need to check $_FILES['bgimage']['error'] to make sure it is equal to UPLOAD_ERR_OK and is not an error code.

Please try the following test code
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
sprintf('<pre>Debug: moving file from %s to %s</pre>',
$_FILES['bgimage']['tmp_name'],
$upload
);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
sprintf('<pre>Debug: realpath=%s, filesize=%d</pre>',
realpath($upload),
filesize($upload)
);
}
else {
echo "Error";
}
and esp. keep an eye on the realpath=xyz output.

Related

PHP move_uploaded_file not successful and no warning is shown

I am learning PHP through w3schools and the upload file php code does not seem to work. At first, there are warning shown that said "unable to open stream" but as I refreshed multiple times (trying to debug) the warning stopped showing but it still failed to upload the file.
Thus I decided to simplify the code (omitting all the features) and focus on uploading only. Some basic information, I am using an apache server on my localhost device. Below are the simplified code
<html>
<head><title>File upload test page</title></head>
<body>
<form action="upload_test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadedfile">
<input type="submit" value="Upload File">
</form>
</body>
</html>
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
?>
The error keeps persisting. I am very new to php so any help would be much appreciated. Thank you!
"unable to open stream", means process user of apache have no write permission for dir "uploads/", try to change user of "uploads/" (such as "chown apache.apache uploads") or change permission of the dir (such as "chmod 777 uploads"). And if u can not get useful message next time, try this to catch exception maybe u can get
some useful messages
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
try{
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]. ["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
}catch(Exception $e){
var_dump($e->getMessage());
}

upload succeeding but picture is not there

I have a php page that is supposed to store the uploaded image to my server. When I run this, I get the "Upload successful" message, but the picture has not been uploaded.
What could it be?
update: can people please leave a comment as to why they down vote my question. I'm new here and I dont know why this question got down voted. thanks
<?
if(!empty($_FILES['uploaded_file'])) {
if ($_FILES['uploaded_file']['error'] > 0 )
echo "Error: " . $_FILES['uploaded_file']['error'] . "<br />";
else{
// Add the original filename to target path.
$target_path = 'MemberPics\\user'.$userid.'.jpg' ;
$success = move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path);
if(!$success) {
echo "There was an error uploading the file, please try again!";
}else {
echo "Upload successful, please go back to your home page";
}
}
}
?>
I believe the problem you are running into is that you are saving the image in an incorrect location (An invalid one from the looks of your link syntax).
Either of these should work:
$target_path = 'MemberPics/user'.$userid.'.jpg' ;
or
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "MemberPics/user" . $_FILES["uploaded_file"]["name"]);

move_uploaded_file() showing successful but not working

I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';

Running php in JavaScript

I am making an application on my server, where the user uploads an image through some HTML combined with javascript.
The user finds an image on the computer through
<form action="uploadimage.php" method="post"
enctype="multipart/form-data">
<label for="file">Filnavn:</label>
<input type="file" name="file" id="file" value="100000" />
Then the point behind the javascript, is to validate on the users image
if(picture_headline.value == "" || picture_uploaded.value == "" || !ischecked)
{
// Don't execute, stay on same site
}
else
{
// execute php and upload image
}
the php is an upload image php script
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I must say I am a bit confused here, since I have only been working with html, php and javascript for a few days now.
Am I totally off or what?
I found some "simple" examples online, which I put on my server through cuteFTP, but everytime i press upload, the website just sends me to the .php file and says the site doesn't exist.
Like Boann points out you're trying to access a non-existent file in your PHP code ("uploaded" and "uploadedfile" rather than "file" (which is what you named the field in your HTML form)).
But regarding "running PHP from JavaScript": You don't have to. The JavaScript should only return false if the form is invalid. If it's valid you don't need to do anything and the form will submit, in turn running your PHP script:
form.onsubmit = function () {
if (!formIsValid()) {
return false;
}
};
If the form is invalid it won't submit (the return false bit (you could use event.preventDefault() instead)), if it is valid nothing will happen and the form will do what it does (ie submit the data to the server).
Each array key in $_FILES corresponds with the name attribute of a file field in the form, so to match your form it should be 'file' rather than 'uploaded' or 'uploadedfile':
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['file']['name'] ) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}

PHP Upload Script not Functioning Properly with New Host

I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.

Categories