Jump to content

Uploading Files - Working on one server, but on another! (?)


Raider

Recommended Posts

Hi!

 

I've created a simple blogging infrastructure. I've been using WAMP to test it and everything seemed fine. However, now I've bought a domain and have some server space, but there's a function that doesn't seem to work: uploading images.

 

When you write an article, I give the option to upload images and use PHP to upload to the correct folder and use the correct filename. This is the code I'm using:

 

for ($i = 1; $i < 9; $i++)  {
	$img = 'img' . $i;
	if (isset($_FILES[$img])) {
		if (!($_FILES[$img]['error'] > 0)) {
			if (in_array($_FILES[$img]['type'], $allowed)) {
				if ($_FILES[$img]['size'] < 1000000) {
					if (file_exists("images/articleImages/" . $_FILES[$img]['name'])) {
						echo "An image already exists with the same name as image $i: " . $_FILES[$img]['name'];
						echo "<br />";
					}
					else {
						move_uploaded_file($_FILES[$img]['tmp_name'], "images/articleImages/" . $_FILES[$img]["name"]);
						echo "Successfully uploaded image $i<br />";
					}
				}
			}
		}
	}
}

 

$allowed just contains acceptable file formats (image/bmp, image/gif, image/jpg, etc.).

 

I have a for loop because you have the ability to upload up to eight images. The HTML code I am using for the file upload section of the form is:

 

 

<input class="form" name="img1" id="img1" type="file" />

 

 

This code is repeated eight times, and the fields are called img2, img3, img4, etc...

 

 

I have no idea why it isn't working on the new server. The article is published correctly, but the selected files aren't uploaded (this DOES work on my own computer, using WAMP).

 

 

Any ideas as to why this is freaking out?

 

Thanks :)

Link to comment
Share on other sites

Your code has some error checking (test if the values are what you expect), but it has no error reporting (output meaningful user error messages that tell you why it did not work or what values were unexpected.)

 

Every one of your if(){} conditional tests that is checking some aspect of the external data NEEDS an else {} statement that outputs as much information about why the if(){} test failed.

 

If $_FILES[$img] is not set, output a user error message telling you (that condiation actually indicates you have exceeded the maximum post size setting).

 

If $_FILES[$img]['error'] is greater than zero, out what value it is so you can troubleshoot which upload error is occuring.

 

if $_FILES[$img]['type'] is not one of the allowed values, display what value was received, perhaps one browser type is sending a mime type that is perfectly valid for the type of file and you should add it to your list.

 

If the size $_FILES[$img]['size'] is too large, output a user error message stating that is the reason why the file was not processed.

 

You might want to look at the following post for more error checking and error reporting ideas, because for all we know uploads are not enabled on your live server - http://www.phpfreaks.com/forums/index.php/topic,278952.msg1320835.html#msg1320835

Link to comment
Share on other sites

Hey. Thanks for the replies. I added error messages as well now, but I'm still a bit baffled.

 

OK, so here's the form I'm using:

<form name="form1" method="post" action="index.php?a=005" enctype="multipart/form-data">
<div class="articleContainerFullDiv">
<div class="articleGenericDiv">
    	Title:<br /><input type="text" name="title" class="form" id="title" value="" /> 
        (<?php echo date('d, D / M / Y'); ?>) - Posted by <?php echo $_SESSION['user']; ?>
    </div>
    <div class="articleGenericDiv">
    	Description:<br /><textarea class="form" name="description" id="description" cols="80" rows="7"></textarea>
    </div>
    <div class="articleGenericDiv">
    	Article:<br /><textarea class="form" name="article" id="article" cols="80" rows="15"></textarea>
    </div>
    <div class="articleGenericDiv">
    	Source:<br /><input class="form" type="text" name="src" id="src" value="" />
    </div>
    <div class="articleGenericDiv">
    	Image 1:<br /><input class="form" name="img1" id="img1" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 2:<br /><input class="form" name="img2" id="img2" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 3:<br /><input class="form" name="img3" id="img3" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 4:<br /><input class="form" name="img4" id="img4" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 5:<br /><input class="form" name="img5" id="img5" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 6:<br /><input class="form" name="img6" id="img6" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 7:<br /><input class="form" name="img7" id="img7" type="file" />
    </div>
    <div class="articleGenericDiv">
    	Image 8:<br /><input class="form" name="img8" id="img8" type="file" />
    </div>
    <div class="articleIconListContainerDiv">
    	<?php echo articles_displayIcons(); ?>
    </div>

    <div class="articleGenericDiv">
    	<input name="createArticle" type="hidden" value="1" />
	<input name="submit" type="submit" class="form" id="submit" value="Create New Article" />
    </div>
</div>

 

When submitted, the following function is executed:

 

function articles_printFormCreate() {	
//	Description:		Prints the form to create a new article. 
//
//	Input Arguments:
//						NONE
//	Last Modified: Fabian Siddiqi (09 / 08 / 2009)

if (!isset($_POST['createArticle'])) {
	include(FORMAT_ARTICLES_CREATE);
}
elseif (isset($_POST['createArticle'])) {
	if ($_POST['createArticle'] == 1) {
		$desc = mysql_real_escape_string($_POST["description"]);
		$a = mysql_real_escape_string($_POST["article"]);

		$t = mysql_real_escape_string($_POST["title"]);
		$s = mysql_real_escape_string($_POST["src"]);
		$u = mysql_real_escape_string($_SESSION["id"]);

		$i = $_POST['articleIcon'];
		$d = time();

		articles_upload();

		mysql_query("INSERT INTO articles (`id`, `title`, `description`, `article`, `user`, `src`, `date`, `likes`, `dislikes`, `views`, `icon`, `trash`, `published`) VALUES (NULL, '$t', '$desc', '$a', '$u', '$s', '$d', '0', '0', '0', '$i', '0', '0')");			
	}
}
}

 

The 'articles_upload()' function is as follows:

 

function articles_upload() {	
//	Description:		Uploads images if an article is modified or created. 
//
//	Input Arguments:
//						NONE
//	Last Modified: Fabian Siddiqi (09 / 08 / 2009)

//	Allowed formats.
$allowed = array('image/bmp', 
				 'image/gif', 
				 'image/jpeg',
				 'image/pjpeg', 
				 'image/svg+xml', 
				 'image/x-portable-anymap',
				 'image/x-portable-bitmap', 
				 'image/x-portable-greymap', 
				 'image/x-portable-pixmap');

//	Repeat process for all 8 images. First check if file is being uploaded, then check if there are any errors. If not, check
//	file size and type. Then, if all is OK, upload.
echo "Trying to upload files...";
for ($i = 1; $i < 9; $i++) {
	$img = 'img' . $i;
	if (isset($_FILES[$img])) {
		if (!($_FILES[$img]['error'] > 0)) {
			if (in_array($_FILES[$img]['type'], $allowed)) {
				if ($_FILES[$img]['size'] < 1000000) {
					if (file_exists("images/articleImages/" . $_FILES[$img]['name'])) {
						echo "Error: File with the same name already exists.";	
					}
					else {
						move_uploaded_file($_FILES[$img]['tmp_name'], "images/articleImages/" . $_FILES[$img]['name']);
						if (file_exists("images/articleImages/" . $_FILES[$img]['name'])) {
							echo "Image successfully uploaded<br />";
						}
					}
				}
				else {
					echo "Error: File too big.<br />";
				}
			}
			else {
				echo "Error: Filetype not allowed.<br />";
			}
		}
		else {
			echo "Error: " . $_FILES[$img]['error'];
		}
	}
	else {
		echo "Error: '$img' does not have a value.<br />";
	}
}
}

 

When I create an article, everything works fine (a new row is added to the database as expected). Problems arise when actually trying to upload an image. The error I receive is that $_FILES[$img]['error'] is not 0. I get an error code of 4 which, from what I've read on the PHP website, is:

 

"Value: 4; No file was uploaded."

 

I have no idea what exactly this means. At first I thought that I couldn't write to the server, but then I saw there was another error 7 means "Could not write to disk" which would be a more appropriate error if that were the case.

Link to comment
Share on other sites

Any type="file" form field that is left empty will produce an error value of 4.

 

If your file input(s) are optional, you would need to test in the error handling if the error is a 4 and basically ignore it and continue.

 

For debugging display exactly what data is being submitted to your page -

echo "<pre>";
echo "GET:";
print_r($_GET);
echo "POST:";
print_r($_POST);
echo "FILES:";
print_r($_FILES);
echo "</pre>";

Link to comment
Share on other sites

OK, so I added that bit of code, and I get the following:

 

GET:Array
(
    [a] => 005
)
POST:Array
(
    [title] => fasf
    [description] => dasdf
    [article] => asdfasdf
    [src] => asdfasdf
    [articleIcon] => m.jpg
    [createArticle] => 1
    [submit] => Create New Article
)
FILES:Array
(
    [img1] => Array
        (
            [name] => yo3.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpFzGv5v
            [error] => 0
            [size] => 89804
        )

    [img2] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img3] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img4] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img5] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img6] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img7] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [img8] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

)

 

So, here I'm only trying to upload one image and no errors occur. However, when I log on to my FTP to see if it's actually uploaded it, it hasn't.  :confused:

 

*EDIT*

The 'tmp' directory didn't exist, so I created it. It still doesn't work.

Link to comment
Share on other sites

Is your code executing the following line and outputting the success message? -

echo "Image successfully uploaded<br />";

 

It's likely that the move_uploaded_file() is failing, but again the code is not doing enough error checking or error reporting to get it (your code) to tell you what it is doing. You need an else {} statement and a meaningful user message when the move_uploaded_file() function fails to move the uploaded file.

 

Add the following two lines of code immediately after your first opening <?php tag to get php to display all php errors -

ini_set("display_errors", "1");
error_reporting(E_ALL);

 

 

 

Link to comment
Share on other sites

Aha! Got it, finally. Yes, the error was with move_uploaded_file() => The problem was that I didn't have permissions to write to that directory.    :'(

Now it's all sorted out, images are uploading without any problem!

 

Thank you so much, I really doubt I would have found this problem on my own so quickly.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.