Jump to content

upload script not overwriting


jeff5656

Recommended Posts

I have this upload script that has an option to overwrite or rename an uploaded file.  However, whether or not I check the form to replace, the uploaded file always gets renamed. instead of replaced.

The option on the form to replace is $replace.  Actually here is a line from that form:

 

	$my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true

 

and here is the processing script (sorry it's long):

class file_upload {

    var $the_file;
var $the_temp_file;
    var $upload_dir;
var $replace;
var $do_filename_check;
var $max_length_filename = 100;
    var $extensions;
var $ext_string;
var $language;
var $http_error;
var $rename_file; // if this var is true the file copy get a new name
var $file_copy; // the new name
var $message = array();
var $create_directory = true;

function file_upload() {
	$this->language = "en"; // choice of en, nl, es
	$this->rename_file = false;
	$this->ext_string = "";
}
function show_error_string() {
	$msg_string = "";
	foreach ($this->message as $value) {
		$msg_string .= $value."<br />\n";
	}
	return $msg_string;
}
function set_file_name($new_name = "") { // this "conversion" is used for unique/new filenames 
	if ($this->rename_file) {
		if ($this->the_file == "") return;
		$name = ($new_name == "") ? strtotime("now") : $new_name;
		sleep(3);
		$name = $name.$this->get_extension($this->the_file);
	} else {
		$name = str_replace(" ", "_", $this->the_file); // space will result in problems on linux systems
	}
	return $name;
}
function upload($to_name = "") {
	$new_name = $this->set_file_name($to_name);
	if ($this->check_file_name($new_name)) {
		if ($this->validateExtension()) {
			if (is_uploaded_file($this->the_temp_file)) {
				$this->file_copy = $new_name;
				if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
					$this->message[] = $this->error_text($this->http_error);
					if ($this->rename_file) $this->message[] = $this->error_text(16);
					return true;
				}
			} else {
				$this->message[] = $this->error_text($this->http_error);
				return false;
			}
		} else {
			$this->show_extensions();
			$this->message[] = $this->error_text(11);
			return false;
		}
	} else {
		return false;
	}
}
function check_file_name($the_name) {
	if ($the_name != "") {
		if (strlen($the_name) > $this->max_length_filename) {
			$this->message[] = $this->error_text(13);
			return false;
		} else {
			if ($this->do_filename_check == "y") {
				if (preg_match("/^[a-z0-9_]*\.(.){1,5}$/i", $the_name)) {
					return true;
				} else {
					$this->message[] = $this->error_text(12);
					return false;
				}
			} else {
				return true;
			}
		}
	} else {
		$this->message[] = $this->error_text(10);
		return false;
	}
}
function get_extension($from_file) {
	$ext = strtolower(strrchr($from_file,"."));
	return $ext;
}
function validateExtension() {
	$extension = $this->get_extension($this->the_file);
	$ext_array = $this->extensions;
	if (in_array($extension, $ext_array)) { 
		// check mime type hier too against allowed/restricted mime types (boolean check mimetype)
		return true;
	} else {
		return false;
	}
}
// this method is only used for detailed error reporting
function show_extensions() {
	$this->ext_string = implode(" ", $this->extensions);
}
function move_upload($tmp_file, $new_file) {
	if ($this->existing_file($new_file)) {
		$newfile = $this->upload_dir.$new_file;
		if ($this->check_dir($this->upload_dir)) {
			if (move_uploaded_file($tmp_file, $newfile)) {
				umask(0);
				chmod($newfile , 0644);
				return true;
			} else {
				return false;
			}
		} else {
			$this->message[] = $this->error_text(14);
			return false;
		}
	} else {
		$this->message[] = $this->error_text(15);
		return false;
	}
}
function check_dir($directory) {
	if (!is_dir($directory)) {
		if ($this->create_directory) {
			umask(0);
			mkdir($directory, 0777);
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}
function existing_file($file_name) {
	if ($this->replace == "y") {
		return true;
	} else {
		if (file_exists($this->upload_dir.$file_name)) {
			return false;
		} else {
			return true;
		}
	}
}
function get_uploaded_file_info($name) {
	$str = "File name: ".basename($name)."\n";
	$str .= "File size: ".filesize($name)." bytes\n";
	if (function_exists("mime_content_type")) {
		$str .= "Mime type: ".mime_content_type($name)."\n";
	}
	if ($img_dim = getimagesize($name)) {
		$str .= "Image dimensions: x = ".$img_dim[0]."px, y = ".$img_dim[1]."px\n";
	}
	return $str;
}
// this method was first located inside the foto_upload extension
function del_temp_file($file) {
	$delete = @unlink($file); 
	clearstatcache();
	if (@file_exists($file)) { 
		$filesys = eregi_replace("/","\\",$file); 
		$delete = @system("del $filesys");
		clearstatcache();
		if (@file_exists($file)) { 
			$delete = @chmod ($file, 0644); 
			$delete = @unlink($file); 
			$delete = @system("del $filesys");
		}
	}
}
// this function creates a file field and if $show_alternate is true it will show a text field if the given file already exists
// there is also a submit button to remove the text field value 
function create_file_field($element, $label = "", $length = 25, $show_replace = true, $replace_label = "Replace old file?", $file_path = "", $file_name = "", $show_alternate = false, $alt_length = 30, $alt_btn_label = "Delete image") {
	$field = ($label != "") ? "<label>".$label."</label>\n" : "";
	$file_field = "<input type=\"file\" name=\"".$element."\" size=\"".$length."\" />\n";
	$file_field .= ($show_replace) ? "<span>".$replace_label."</span><input type=\"checkbox\" name=\"replace\" value=\"y\" />" : "";
	if ($file_name != "" && $show_alternate) {
		$field .= "<input type=\"text\" name=\"".$element."\" size=\"".$alt_length."\" value=\"".$file_name."\" readonly=\"readonly\"";
		$field .= (!@file_exists($file_path.$file_name)) ? " title=\"".sprintf($this->error_text(17), $file_name)."\" />\n" : " />\n";
		$field .= "<input type=\"checkbox\" name=\"del_img\" value=\"y\" /><span>".$alt_btn_label."</span>\n";
	} else {
		$field .= $file_field;
	} 
	return $field;
}
function error_text($err_num) {
	switch ($this->language) {

		default:
		// start http errors
		$error[0] = "File: <b>".$this->the_file."</b> successfully uploaded!";
		$error[1] = "The uploaded file exceeds the max. upload filesize directive in the server configuration.";
		$error[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.";
		$error[3] = "The uploaded file was only partially uploaded";
		$error[4] = "No file was uploaded";
		// end  http errors
		$error[10] = "Please select a file for upload.";
		$error[11] = "Only files with the following extensions are allowed: <b>".$this->ext_string."</b>";
		$error[12] = "Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.";
		$error[13] = "The filename exceeds the maximum length of ".$this->max_length_filename." characters.";
		$error[14] = "Sorry, the upload directory doesn't exist!";
		$error[15] = "Uploading <b>".$this->the_file."...Error!</b> Sorry, a file with this name already exitst.";
		$error[16] = "The uploaded file is renamed to <b>".$this->file_copy."</b>.";
		$error[17] = "The file %s does not exist.";
	}
	return $error[$err_num];
}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/103607-upload-script-not-overwriting/
Share on other sites

The line of code that produces the checkbox <input field looks okay. When you do a "view source" of the form, is the form actually correct and the checkbox <input field is within the <form...> </form> tags?

 

What does your <form ... > tag look like? I have seen cases where invalid information has prevented post fields from working.

Here is the php file with the form:

 

<?php
require ('secure.php'); 
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root)

$max_size = 1024*450; // the max. size for uploading

$my_upload = new file_upload;

$my_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/schedules/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".zip", ".pdf"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = true;

if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename
$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
if ($my_upload->upload($new_name)) { // new name is an additional filename information, use this to rename the uploaded file
	$full_path = $my_upload->upload_dir.$my_upload->file_copy;
	$info = $my_upload->get_uploaded_file_info($full_path);
	// ... or do something like insert the filename to the database
}
}
?> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Upload example</title>
<link href="styles/table_design.css" rel="stylesheet" type="text/css">
<link href="styles/sample.css" rel="stylesheet" type="text/css">
</head>

<body>
<h3 align="center">Update the ICU teaching schedule.</h3>
<p align="center"><h3>Max. filesize = <?php echo $max_size; ?> bytes.</h3>
<strong>Remember to save it as a web page</strong>
<table width="676" border="0" cellspacing="0" cellpadding="0">
  <tr><form name="form1" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>"><br>
  <table width="620" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="280" rowspan="2"><label for="upload">Select a file...</label><p><input type="file" name="upload" size="30">
  </td>
      <td width="426">Current month: <strong>icu-current.htm</strong></td>
    <tr>
      <td>Next month <strong> icu-next.htm</strong></td>
    </tr>
    

    <tr>
      <td colspan="2"> </td>
    </tr>
    <tr><td colspan="2">
  
  <label for="name">New name?</label><input type="text" name="name" size="20"> 
  (without extension!) </td></tr>
  <tr><td>
  <label for="replace">Replace ?</label><input type="checkbox" name="replace" value="y"></td></tr>
  <tr><td>
  <label for="check">Validate filename ?</label><input name="check" type="checkbox" value="y" checked>
  <input style="margin-left:120px;" type="submit" name="Submit" value="Submit">
</form>
</table>
<br clear="all">
<p><?php echo $my_upload->show_error_string(); ?></p>
<?php if (isset($info)) echo "<blockquote>".nl2br($info)."</blockquote>"; ?> 
</body>
</html>

If you had done a "view source" of your form or read the code, you would notice that the name of the checkbox is not 'replace', so $_POST['replace'] will never get a value.

 

You have got code in your class that sets the field name correctly, is there are reason you are not using it?

If you had done a "view source" of your form or read the code, you would notice that the name of the checkbox is not 'replace', so $_POST['replace'] will never get a value.

 

You have got code in your class that sets the field name correctly, is there are reason you are not using it?

 

where in this line of code does it say that the name is not replace?  It sure looks like the name is replace to me.

<label for="replace">Replace ?</label><input type="checkbox" name="replace" value="y"></td></tr>

 

That is in my form when I did a "view source" (actually put it into dreamweaver)

While I'm waiting for an answer, I was just thinking - could the problem be that after the file is uploaded, the server doesn't give permission for the file to be overwritten and then by default simply uploads it as a new name?

I came across another post talking about chmod, and I thought maybe this was a possibility?

what do you mean?  I see the next line down.  I could not find this in  the accompanying script either.  Not sure how to edit the script so that it doesn't automatically rename the file.  I cannot gewt it to overwrite the file no matter WHAT is checked.

Ok thanks for trying.  Maybe I will try to contact the author of the script.

Is there anyone else out there that has advice on how to make this work?  I thought an upload script would be easy but maybe not.

Maybe it's mpre difficult because the script I chose has lots of OOP?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.