Need PHP script for a form to upload two files to server

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cheska
Forum Newbie
Posts: 5
Joined: Sun Jun 18, 2006 12:29 pm

Need PHP script for a form to upload two files to server

Post by cheska »

Hi,

I have scoured the internet for quite a while now looking for a free php script that will enable me to:

1. Put a form on a page that has two uplaod boxes for a client to upload two file svia theeir browser
2.The files will be one image (jpg) and one pdf
3. The files will always (each day) be called headshot.jpg and resume.pdf
4. The script must allow the files on the server to be overwritten by the new files of the same name each day

I have found MANY scripts, som eof which i can get to work, but they were too sofisticated (checked for many things taht i was not concerned for, didnt allow files to be overwritten, changed directories of where the files were uplaoded to, changed the file names automatically) and many that i wasnt able to get to work.

I just need something simple like the above. Unfortunately I am no scripter, so when i tried to decifer the ready made scripts and rearrange them to suit my needs, i messed things up.

Thanks immensely in advance of anyone who canb offer m eany help or point me in a better direction. I wasnt sure where to post this query/help plea.

Cheska

:D
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

Seeing you got the script, I have removed them...


If you need help with the changes, just ask


pif!
Last edited by printf on Sun Jun 18, 2006 4:41 pm, edited 1 time in total.
cheska
Forum Newbie
Posts: 5
Joined: Sun Jun 18, 2006 12:29 pm

Post by cheska »

YAY that looks great - i will download it as soon as i get back ( i have to run out for a few hours)....i guess i will just be able to delete the text feild for renaming (since i dont want them to rename the file).....i will reply when i have looked into it.
thanks so much!
cheska
cheska
Forum Newbie
Posts: 5
Joined: Sun Jun 18, 2006 12:29 pm

Post by cheska »

Nooo!!!!!!
I hadn't actually downloaded it yet.....sorry!!!!
Please can you post it again and I'll let you know as soon as I'v downloaded it -
Thanks!
Cheska
cheska
Forum Newbie
Posts: 5
Joined: Sun Jun 18, 2006 12:29 pm

Post by cheska »

Jason...

where did you go? :?

:cry:
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

This is probably a little overkill...

Code: Select all

<?php


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 = true; // 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;
			$name = $name.$this->get_extension($this->the_file);
		} else {
			$name = $this->the_file;
		}
		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) {
		umask(0);
		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)) {
					if ($this->replace == "y") {
						//system("chmod 0777 $newfile"); // maybe you need to use the system command in some cases...
						chmod($newfile , 0777);
					} else {
						// system("chmod 0755 $newfile");
						chmod($newfile , 0755);
					}
					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, 0775); 
				$delete = @unlink($file); 
				$delete = @system("del $filesys");
			}
		}
	}
	// some error (HTTP)reporting, change the messages or remove options if you like.
	function error_text($err_num) {
			// 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>.";
		return $error[$err_num];
	}
}

class muli_files extends file_upload {
	
	var $number_of_files = 0;
	var $names_array;
	var $new_names;
	var $tmp_names_array;
	var $error_array;
	var $wrong_extensions = 0;
	var $bad_filenames = 0;
	var $per_file_errs = array();
	
	function extra_text($msg_num) {
			$extra_msg[1] = "Error for: <b>".$this->the_file."</b>";
			$extra_msg[2] = "You have tried to upload ".$this->wrong_extensions." files with a bad extension, the following extensions are allowed: <b>".$this->ext_string."</b>";
			$extra_msg[3] = "Select at least one file.";
			$extra_msg[4] = "Select the file(s) for upload.";
			$extra_msg[5] = "You have tried to upload <b>".$this->bad_filenames." files</b> with invalid characters inside the filename.";
		return $extra_msg[$msg_num];
	}
	// this method checkes the number of files for upload
	// this example works with one or more files
	function count_files() {
		foreach ($this->names_array as $test) {
			if ($test != "") {
				$this->number_of_files++;
			}
		}
		if ($this->number_of_files > 0) {
			return true;
		} else {
			return false;
		} 
	}
	function upload_multi_files () {
		$this->message = "";
		if ($this->count_files()) {
			foreach ($this->names_array as $key => $value) { 
				if ($value != "") {
					$this->the_file = $value;
					$file_apart = explode(".", $this->the_file);
					$amount = count($file_apart) - 1;
					$extension = $file_apart[$amount];
					$this->new_file_name = $this->new_names[$key] . "." . $extension;
					$new_name = $this->new_file_name;
					if ($this->check_file_name($new_name)) {
						if ($this->validateExtension()) {
							$this->file_copy = $new_name;
							$this->the_temp_file = $this->tmp_names_array[$key];
							if (is_uploaded_file($this->the_temp_file)) {
								if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
									$this->message[] = $this->error_text($this->error_array[$key]);
									if ($this->rename_file) $this->message[] = $this->error_text(16);
									sleep(1); // wait a seconds to get an new timestamp (if rename is set)
								}
							} else {
								$this->message[] = $this->extra_text(1);
								$this->message[] = $this->error_text($this->error_array[$key]);
							}
						} else {
							$new_key = $this->new_names[$key];
							$this->per_file_errs[$new_key] = "<b>" . $value . ":</b> Invalid file extension - see acceptable extensions above.";
							$this->wrong_extensions++;
						}
					} else {
						$this->bad_filenames++;
					}
				} 
			}
			if ($this->bad_filenames > 0) $this->message[] = $this->extra_text(5);
			if ($this->wrong_extensions > 0) {
				$this->show_extensions();
				$this->message[] = $this->extra_text(2);
			}
		} else {
			$this->message[] = $this->extra_text(3);
		}
	}
}


$multi_upload = new muli_files;

$multi_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/php/upload/files/"; // "files" is the folder for the uploaded files (you have to create this folder)
$multi_upload->extensions = array(".png", ".jpg", ".tiff", ".tif", ".psd", ".pdf"); // specify the allowed extensions here
$multi_upload->message[] = $multi_upload->extra_text(4); // a different standard message for multiple files
//$multi_upload->rename_file = true; // set to "true" if you want to rename all files with a timestamp value
$multi_upload->do_filename_check = "y"; // check filename ...
		
if($_POST['action'] == "upload") {
	$multi_upload->tmp_names_array = $_FILES['userfile']['tmp_name'];
	$multi_upload->names_array = $_FILES['userfile']['name'];
	$multi_upload->new_names =  $_POST['names'];
	$multi_upload->error_array = $_FILES['userfile']['error'];
	$multi_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
	$multi_upload->upload_multi_files();
	$multi_upload->show_error_string();
	
	if(!empty($multi_upload->message)){
		echo "<h1 style='color: #900; font-size: 14px'>Results:</h1>";
		echo "<p class='error'>";
		foreach($multi_upload->message as $val){
			echo $val . "<br />";
		}
		if(!empty($multi_upload->per_file_errs)){
			echo "<br />";
			foreach($multi_upload->per_file_errs as $val){
				echo $val . "<br />";
			}
		}
		echo "</p>";
	}
	else{
		echo "<p class='error'>We're sorry, there has been an error. Please try again later.</p>";
	}
}

?>
cheska
Forum Newbie
Posts: 5
Joined: Sun Jun 18, 2006 12:29 pm

Post by cheska »

Thanks Ninja Space Goat....

I think that i s a little overkill....it may take ME a century to work through an dunderstand it. Unfortunately any tim ei think i understand a script, and try to make modifications (usually take out or remove superfluent functionality fo rmy needs) I am unsuccesful.

Is there or do you know how to write short script that just puts uploaded files in a directory and tahts that (no renaming or filkes or anything). I guess the most extra that would be useful would be max file size and file type checking, but only if its easy to implemement.

Thanks if you're able to shed any extra light or help, and regardless, I wil ttempt to decifer some of the above script you posted.

Thanks again,

Cheska...
Post Reply