Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File Upload issue 1

Status
Not open for further replies.

Katerine

Programmer
Mar 9, 2001
234
US
Hi,
I have what I hope is a simple problem. I'm fairly new to PHP, so it's very possible that I'm just missing something. :)

Here's the issue: I have code to upload a file. The code is pretty much copied from W3Schools' example PHP upload code. But when I use it, it doesn't upload the file.

My code also adds a Graphic link (just an internal URL) to a GraphicLinks table, and adds a reference to that record to the Clients table, in MySQL. This part actually works fine... except that the link is always just the link to the directory, without the filename.

So, to sum up, everything seems to work fine, except that the file does not get uploaded, and the value of $internalURL when I submit a file, appears to be just, 'uploads/'. Which means basename($_FILES["fileToUpload"]["name"]) is apparently returning nothing at all, which I'm guessing is why the file is not getting uploaded. But how do I fix?

I'm trying to get this to work on my (development) computer, running IIS7 (Win 10), before uploading to the production Apache server. I haven't tried it on the production server yet.

Here's most of the code, with some changes for security:

PHP:
<?php
$rootdirprefix = '../';
$formtitle = 'Upload Graphic for Client';

if(isset($_POST['Submit'])) {
	//upload file code from [URL unfurl="true"]http://www.w3schools.com/php/php_file_upload.asp[/URL]
	$target_dir = 'uploads/';
	$internalURL = $target_dir . basename($_FILES["fileToUpload"]["name"]);
	$target_file = $rootdirprefix . $internalURL;
	$uploadOk = 1;
	$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
	// Check if image file is a actual image or fake image
	if(isset($_POST["submit"])) {
		$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
		if($check !== false) {
			echo "File is an image - " . $check["mime"] . ".";
			$uploadOk = 1;
		} else {
			echo "File is not an image.";
			$uploadOk = 0;
		}
	}
	// Check if file already exists
	if (file_exists($target_file)) {
//		echo 'Sorry, file already exists.';
//		$uploadOk = 0;
		echo 'File already exists. Overwriting.';
		unlink($target_file);
	}
	// Check file size
	if ($_FILES["fileToUpload"]["size"] > 500000) {
		echo "Sorry, your file is too large.";
		$uploadOk = 0;
	}
	// Allow certain file formats
	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
	&& $imageFileType != "gif" ) {
		echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
		$uploadOk = 0;
	}
	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk == 0) {
		echo "Sorry, your file was not uploaded.";
	// if everything is ok, try to upload file
	} else {
		if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
			echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
		} else {
			echo "Sorry, there was an error uploading your file.";
		}
	}
	//end file upload code
	
    // Add to the GraphicLinks table
	$clientid=filter_input(INPUT_POST,'clientid',FILTER_SANITIZE_NUMBER_INT);
	
	if (isset($_POST['clientid']) && $_POST['clientid'] > '') { 
		//Insert to GraphicLinks
		$graphicLinkID = 0;
		if ($edit_stmt = $mysqli->prepare("INSERT INTO `GraphicLinks` (`InternalURL`) VALUES (?);")) {
			if (! $edit_stmt->bind_param('s', $internalURL)) {
				$err='Link Insert failure: BINDING PARAMETERS FAILED ' . $internalURL;
				header('Location: login_err.php?err=' . $err);
				exit();
			}
			// Execute the prepared query.
			if (!$edit_stmt->execute()) {
				$err='Link Insert failure: INSERT ' . $internalURL;
				header('Location: login_err.php?err=' . $err);
				exit();
			}
			
			$graphicLinkID = $edit_stmt->insert_id;
		}
		
		// update Client record with the GraphicLinkID
		if ($graphicLinkID == 0) {
			$err='Could not retrieve the ID of the inserted graphic link.';
			header('Location: login_err.php?err=' . $err);
			exit();
		}
		
		if ($edit_stmt = $mysqli->prepare("UPDATE `Clients` SET `GraphicLinkID` = ? WHERE ClientID = ?")) {
			if (! $edit_stmt->bind_param('ii', $graphicLinkID, $clientid)) {
				$err='Client Update failure: BINDING PARAMETERS FAILED ' . $graphicLinkID . ' : ' . $clientid;
				header('Location: login_err.php?err=' . $err);
				exit();
			}
			// Execute the prepared query.
			if (!$edit_stmt->execute()) {
				$err='Client Update failure: UPDATE ' . $graphicLinkID . ' : ' . $clientid;
				header('Location: login_err.php?err=' . $err);
				exit();
			}
		}
	} else { //no client id. show error.
		$err='No client ID set.';
		header('Location: login_err.php?err=' . $err);
		exit();
	}
	
	header('Location: clientlisting.php');

} else {
	// check to see if an ID was passed to the form, and load the data into an edit form
	if (isset($_GET["clientid"])) {
		$clientid = filter_input(INPUT_GET,'clientid',FILTER_SANITIZE_NUMBER_INT);
	} else {
		// create blank add form
		$clientid='';
		$error_msg = 'WARNING: No client ID has been set. If you upload a graphic, it won\'t be linked to anything.';
	}
}
?>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title><?php echo $formtitle ?></title>

</head>

<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
	<h1 id="formtitle"><?php echo $formtitle ?></h1>
	<?php
	if (!empty($error_msg)) {
		echo $error_msg;
	}
	?>
	<ul class="instructions" id="forminstructions">
	</ul>
	
	<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" name="input_form" class="cmxform">
		<fieldset>
			<legend>Upload Graphic</legend>
			<ul>
			<li>
				<input type="hidden" name="clientid" id="clientid" value="<?php echo $clientid;?>" />
				<label for="fileToUpload">Select image to upload:</label>
				<input type="file" name="fileToUpload" id="fileToUpload">
			</li>
			<li>
				<input type="Submit" value="Submit" name="Submit" />
			</li>
			</ul>
		</fieldset>
	</form>
	
</body>
</html>

Many thanks! :)

Katie
 
Test it on on machine that isn't 'localhost to localhost' before deciding that it doesn't work.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Hi

Maybe I am too pessimistic, but I find this line occurs too soon :
Code:
[navy]$internalURL[/navy] [teal]=[/teal] [navy]$target_dir[/navy] [teal].[/teal] [COLOR=orange]basename[/color][teal]([/teal][navy]$_FILES[/navy][teal][[/teal][i][green]"fileToUpload"[/green][/i][teal]][[/teal][i][green]"name"[/green][/i][teal]]);[/teal]

After checking the presence of [tt]$_POST['Submit'][/tt], I would continue with checking whether [tt]$_FILES['fileToUpload'][/tt] was populated then with checking whether [tt]$_FILES['fileToUpload']['error'][/tt] signals an upload error.


Feherke.
feherke.ga
 
As mentioned checking for the existence of an uploaded file before performing any file based actions is paramount.


However, to address your issue, I've found that a form needs to have an encode type defined for uploads to successfully occur.

The form in your code does not, so I would suggest adding enctype="multipart/form-data" to your form definition.

Code:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" [i][COLOR=#A40000]enctype="multipart/form-data"[/color][/i]  name="input_form" class="cmxform">


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Many thanks for looking into this, everyone. :)

Ok, so progress: adding enctype="multipart/form-data" did indeed result in $internalURL returning the directory and file name, rather than just the directory. This seems to have fixed the problem altogether (at least on the production server. I'd still very much like to get it working on the development server, though... any ideas on how that might be done?)

I now have a separate, relatively minor issue that I was wondering if you could help this PHP newbie with. :)

When I click the Submit button, it submits, but it doesn't redirect me back to the client listing page the way it should. I get the following error messages on the page (which currently has detailed messages on):

----------
The file aonclip1_6.gif has been uploaded.
Warning: Cannot modify header information - headers already sent by (output started at /secureinternaldirectorylistingsnipped/uploadclientgraphic.php:58) in /secureinternaldirectorylistingsnipped/uploadclientgraphic.php on line 113
----------

Line 113 is this line:
header('Location: clientlisting.php');

Many thanks again!

Katie
 
Never mind. I figured out the redirect problem. I didn't know that header('Location:') apparently doesn't work if anything's been previously echoed to the screen. When I commented out:
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

...it worked perfectly.

Katie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top