×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

File Upload issue

File Upload issue

File Upload issue

(OP)
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. smile

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:

CODE --> PHP

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

if(isset($_POST['Submit'])) {
	//upload file code from http://www.w3schools.com/php/php_file_upload.asp
	$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! smile

Katie

RE: File Upload issue

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

RE: File Upload issue

Hi

Maybe I am too pessimistic, but I find this line occurs too soon :

CODE --> ( fragment )

$internalURL = $target_dir . basename($_FILES["fileToUpload"]["name"]); 

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

Feherke.
feherke.ga

RE: File Upload issue

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" enctype="multipart/form-data"  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

RE: File Upload issue

(OP)
Many thanks for looking into this, everyone. smile

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. smile

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

RE: File Upload issue

(OP)
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

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close