Link to home
Start Free TrialLog in
Avatar of genesisvh
genesisvh

asked on

upload and replace selected image using php

I have a form that will be used to edit various fields including images. Everything works on this form except the images. When I choose the image i want to replace and upload the new image the location of the others get erased on the MySQL database and I'm just left with the one I replaced. How can I just change the image I pick to replace without erasing the location of the others? Is there a way just to tell the script to only replace the image that corresponds with the image selected? Thank You

Form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FormListing </title>
</head>

<body>\<?php
session_start();
if(empty($_SESSION['myusername'])){

// send them back to login

header('location: index.php');

}
$_SESSION['id'];
$_SESSION['$myusername'];


$id = (int)$_GET['id'];
$id = substr($id, 0,5);
	
if($id < 1 || $id > 99999) exit;
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name=""; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// get value of id that sent from address bar
$id=$_GET['id'];


// Retrieve data from database 
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);

$rows=mysql_fetch_array($result);
?>
<form method="post" action="aptmodifyform.php" enctype="multipart/form-data"/>
        <input type="hidden" name="id" id="id" value="<?php echo $id; ?>"  />
        <table width="914" height="1234" border="0">
          <tr>
            <td width="636" height="68"><div align="right"><span style="color: #F00">*</span>Title</div></td>
            <td width="11"><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="title"></label>
              <div align="left"><span id="sprytextfield1">
                <input name="title" type="text" value="<? echo $rows['title']; ?>" id="title" size="50" maxlength="50"/>
              </span></div></td>
          </tr>
          <tr>
            <td><div align="right">County</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="county"></label>
              <select name="county" id="county">
                <option selected="selected" <?=($rows['county'] == 'Bronx') ? 'selected="selected"' : ''?>>Bronx</option>
                <option <?=($rows['county'] == 'Brooklyn') ? 'selected="selected"' : ''?>>Brooklyn</option>
                <option <?=($rows['county'] == 'Manhattan') ? 'selected="selected"' : ''?>>Manhattan</option>
                <option <?=($rows['county'] == 'Queens') ? 'selected="selected"' : ''?>>Queens</option>
                <option <?=($rows['county'] == 'Staten Island') ? 'selected="selected"' : ''?>>Staten Island</option>
                <option>-----------------</option>
                <option <?=($rows['county'] == 'Nassau') ? 'selected="selected"' : ''?>>Nassau</option>
                <option <?=($rows['county'] == 'Suffolk') ? 'selected="selected"' : ''?>>Suffolk</option>
              </select></td>
          </tr>
          <tr>
            <td><div align="right">Town</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="town"></label>
              <input name="town" type="text" value="<? echo $rows['town']; ?>" id="town" size="50" maxlength="30"/></td>
          </tr>
          <tr>
            <td><div align="right">Description<br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
            </div></td>
            <td><div align="center">
              <p>:<br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />
              </p>
            </div></td>
            <td colspan="3" style="text-align: left"><label for="description"></label>
              <textarea name="description" cols="70" rows="25" id="description"><?php echo $rows['description']; ?></textarea></td>
          </tr>
          <tr>
            <td style="text-align: right; color: #000;">Service</td>
            <td style="text-align: center">:</td>
            <td colspan="3" style="text-align: left"><label for="service"></label>
              <select name="service" size="1" id="service">
                <option <?=($rows['service'] == 'Landlord') ? 'selected="selected"' : ''?>>Lanlord</option>
                <option <?=($rows['service'] == 'Property Mangement') ? 'selected="selected"' : ''?>>Property Mangement</option>
                <option <?=($rows['service'] == 'Realtor') ? 'selected="selected"' : ''?>>Realtor</option>
              </select></td>
          </tr>
          <tr>
            <td><div align="right">Service Fees</div></td>
            <td>:</td>
            <td colspan="3" style="text-align: left"><select name="feeornofee" id="feeornofee">
              <option <?=($rows['feeornofee'] == 'Broker Fees + Other Fees') ? 'selected="selected"' : ''?>>Broker Fees + Other Fees</option>
              <option <?=($rows['feeornofee'] == 'Broker Fees') ? 'selected="selected"' : ''?>>Broker Fees</option>
              <option <?=($rows['feeornofee'] == 'Other Fees - No Broker Fee') ? 'selected="selected"' : ''?>>Other Fees - No Broker Fee</option>
              <option <?=($rows['feeornofee'] == 'No Fees') ? 'selected="selected"' : ''?>>No Fees</option>
            </select></td>
          </tr>
          <tr>
            <td><div align="right">Lease Type</div></td>
            <td>:</td>
            <td colspan="3" style="text-align: left"><label for="lease"></label>
              <select name="lease" id="lease">
                <option <?=($rows['lease'] == 'Rent Stabilized ') ? 'selected="selected"' : ''?>>Rent Stabilized </option>
                <option <?=($rows['lease'] == 'Prime, non-stabilized lease') ? 'selected="selected"' : ''?>>Prime, non-stabilized lease</option>
                <option <?=($rows['lease'] == 'Coop (sub) Lease') ? 'selected="selected"' : ''?>>Coop (sub) Lease</option>
                <option <?=($rows['lease'] == 'Condo Lease') ? 'selected="selected"' : ''?>>Condo Lease</option>
                <option <?=($rows['lease'] == 'Commercial Lease') ? 'selected="selected"' : ''?>>Commercial Lease</option>
                <option <?=($rows['lease'] == 'Other') ? 'selected="selected"' : ''?>>Other</option>
              </select></td>
          </tr>
          &gt;
          <tr>
            <td><div align="right">Contact's Name</div></td>
            <td>:</td>
            <td colspan="3" style="text-align: left"><label for="contact"></label>
              <input name="contact" type="text" value="<? echo $rows['contact']; ?>" id="contact" size="40" maxlength="40" /></td>
          </tr>
          <tr>
            <td><div align="right">Name of Office</div></td>
            <td>:</td>
            <td colspan="3" style="text-align: left"><label for="office"></label>
              <input name="office" type="text" value="<? echo $rows['office']; ?>" id="office" size="40" maxlength="40" /></td>
          </tr>
          <tr>
            <td><div align="right">Pets</div></td>
            <td>:</td>
            <td colspan="3" style="text-align: left"><label for="pets"></label>
              <select name="pets" id="pets">
                <option <?=($rows['pets'] == 'Pets Allowed') ? 'selected="selected"' : ''?>>Pets Allowed</option>
                <option <?=($rows['pets'] == 'No Pets') ? 'selected="selected"' : ''?>>No Pets</option>
                <option <?=($rows['pets'] == 'Pets Allowed - Small pets') ? 'selected="selected"' : ''?>>Pets Allowed - Small pets</option>
              </select></td>
          </tr>
          <tr>
            <td><div align="right">Phone<br />
            </div>
              <br /></td>
            <td><div align="center">:<br />
              <br />
            </div></td>
            <td colspan="3" style="text-align: left"><label for="phone"></label>
              <span id="rental_phone">
                <input type="text" name="phone" value="<? echo $rows['phone']; ?>"id="phone" />
                <span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span><br />
              <span style="font-style: italic; font-size: 14px; font-weight: bold;">ex. (123) 456-7890 - Please keep this format.</span></td>
          </tr>
          <tr>
            <td style="text-align: right"><p>Location<br />
            </p>
              <p><br />
                <br />
                <br />
              </p></td>
            <td style="text-align: center">:<br />
              <br />
              <br />
              <br />
              <br /></td>
            <td colspan="3" style="text-align: left"><label for="cross_streets"></label>
              <input name="cross_streets" type="text" value="<? echo $rows['cross_streets']; ?>" id="cross_streets" size="80" maxlength="100" />
              <br />
              <span style="color: #F00">Please insert here the intersecting streets. Make sure you add the word &quot;and&quot; <br />
                between streets <br />
                OR<br />
                You can put the property's 
                full address. <br />
                e.g. 193rd Street AND Jamaica Avenue, Jamaica, NY </span></td>
          </tr>
          <tr>
            <td style="text-align: right">Zip Code</td>
            <td style="text-align: center">:</td>
            <td colspan="3" style="text-align: left"><input name="zipcode" type="text" id="zipcode" value="<? echo $rows['zipcode']; ?>" size="9" 

maxlength="5" /></td>
          </tr>
          <tr>
            <td style="text-align: right"><span style="color: #000">Email </span><br />
              <br /></td>
            <td style="text-align: center">:<br />
              <br /></td>
            <td colspan="3" style="text-align: left"><label for="email"></label>
              <input name="email" type="text" value="<? echo $rows['email']; ?>" id="email" size="60" maxlength="60" />
              <br />
              <span style="font-size: 12px; font-style: italic;">This field is optional. It will be viewable to users.</span></td>
          </tr>
          <tr>
            <td><div align="right">Rooms</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="rooms"></label>
              <select name="rooms" id="rooms">
                <option <?=($rows['rooms'] == '0') ? 'selected="selected"' : ''?>>0</option>
                <option <?=($rows['rooms'] == '1') ? 'selected="selected"' : ''?>>1</option>
                <option <?=($rows['rooms'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option>
                <option <?=($rows['rooms'] == '2') ? 'selected="selected"' : ''?>>2</option>
                <option <?=($rows['rooms'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option>
                <option <?=($rows['rooms'] == '3') ? 'selected="selected"' : ''?>>3</option>
                <option <?=($rows['rooms'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option>
                <option <?=($rows['rooms'] == '4') ? 'selected="selected"' : ''?>>4</option>
                <option <?=($rows['rooms'] == '4.5') ? 'selected="selected"' : ''?>>4.5</option>
                <option <?=($rows['rooms'] == '5') ? 'selected="selected"' : ''?>>5</option>
                <option <?=($rows['rooms'] == '5.5') ? 'selected="selected"' : ''?>>5.5</option>
                <option <?=($rows['rooms'] == '6') ? 'selected="selected"' : ''?>>6</option>
              </select>
              0 = Studio, 1 = 1 Bedroom, etc.</td>
          </tr>
          <tr>
            <td><div align="right">Bath</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="bath"></label>
              <select name="bath" id="bath">
                <option <?=($rows['bath'] == '0') ? 'selected="selected"' : ''?>>0</option>
                <option <?=($rows['bath'] == '1') ? 'selected="selected"' : ''?>>1</option>
                <option <?=($rows['bath'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option>
                <option <?=($rows['bath'] == '2') ? 'selected="selected"' : ''?>>2</option>
                <option <?=($rows['bath'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option>
                <option <?=($rows['bath'] == '3') ? 'selected="selected"' : ''?>>3</option>
                <option <?=($rows['bath'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option>
                <option <?=($rows['bath'] == '4') ? 'selected="selected"' : ''?>>4</option>
              </select></td>
          </tr>
          <tr>
            <td><div align="right">Square ft.</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="square"></label>
              <input name="square" type="text" value="<? echo $rows['square']; ?>" id="square" size="6" maxlength="6" /></td>
          </tr>
          <tr>
            <td><div align="right"><span style="color: #F00">*</span>Rent</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3" style="text-align: left"><label for="rent">
              $ 
                <input name="rent" type="text" value="<? echo $rows['rent']; ?>" id="rent" size="10" maxlength="10" />
              </label></td>
          </tr>
          <tr>
            <td><div align="right"><span style="color: #F00">*</span>Fees 
            </div></td>
            <td><div align="center">
              <p>:              </p>
</div></td>
            <td colspan="3" style="text-align: left"><label for="fees"></label>
              <span id="sprytextfield3">
                <input name="fees" type="text" id="fees" value="<? echo $rows['fees']; ?>" size="90" />
              </span></td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center; font-weight: bold; font-size: 18px; color: #F00;"> Video Link</td>
          </tr>
          <tr>
            <td><div align="right">URL</div></td>
            <td><div align="center">:</div></td>
            <td colspan="3"><p>&nbsp;
              </p>
              <p>
                <input name="url" type="text" id="url" value="<? echo $rows['url']; ?>"size="80" />
                </td>
          </tr>
          <tr>
            <td><div align="center" style="color: #F00">
              <div align="right">Name Your
                Video Link</div>
            </div></td>
            <td><div align="center">
              <p>:            </p>
            </div></td>
            <td colspan="3"><br />
              <p>
              <input name="videotitle" type="text" id="videotitle" value="<? echo $rows['videotitle']; ?>"size="80" />
                <br />
              <span style="color: #E62E00">If you posted a URL for your video you must give it a title to give it a link.</span></p></td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
            <td style="text-align: center">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl1']; ?>" width="200" /><br /></td>
            <td width="213" style="text-align: center"><img src="<? echo $rows['imageurl2']; ?>" width="200" /></td>
            <td width="180" style="text-align: center"><img src="<? echo $rows['imageurl3']; ?>" width="200" /></td>
            <td width="188" style="text-align: center"><img src="<? echo $rows['imageurl4']; ?>" width="200" /></td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center"><div align="center">
              <input id="image3" type="file" name="image1" />
            </div></td>
            <td style="text-align: center"><div align="center">
              <input id="image3" type="file" name="image2" />
            </div></td>
            <td style="text-align: center"><div align="center">
              <input id="image3" type="file" name="image3" />
            </div></td>
            <td style="text-align: center"><div align="center">
              <input id="image4" type="file" name="image4" />
            </div></td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl5']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl6']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl7']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl8']; ?>" width="200" /></td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center"><input id="image5" type="file" name="image5" /></td>
            <td style="text-align: center"><input id="image6" type="file" name="image6" /></td>
            <td style="text-align: center"><input id="image7" type="file" name="image7" /></td>
            <td style="text-align: center"><input id="image8" type="file" name="image8" /></td>
          </tr>
	  <tr>
            <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl9']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl10']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl11']; ?>" width="200" /></td>
            <td style="text-align: center"><img src="<? echo $rows['imageurl12']; ?>" width="200" /></td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center"><input id="image9" type="file" name="image9" /></td>
            <td style="text-align: center"><input id="image10" type="file" name="image10" /></td>
            <td style="text-align: center"><input id="image11" type="file" name="image11" /></td>
            <td style="text-align: center"><input id="image12" type="file" name="image12" /></td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center"><span style="color: #F00">*</span> REQUIRED FIELDS </td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center"> PRESS SUBMIT ONCE!!!</td>
          </tr>
          <tr>
            <td colspan="5" style="text-align: center"><input type="submit" name="button" id="button" value="Submit Changes" />
              <input type="reset" name="button" id="button" value="Reset" /></td>
          </tr>
        </table>
        </form>
</body>
</html>

Open in new window


PHP Script
<?php
session_start();
include('SimpleImage.php');
$image = new SimpleImage();    
//error_reporting(E_ALL); 


	// image upload folder
    $image_folder = 'images/classified/'; 
	// fieldnames in form
	$all_file_fields = array('image1', 'image2' ,'image3', 'image4', 'image5', 'image6', 'image7', 'image8', 'image9', 'image10', 'image11', 'image12');
	// allowed filetypes
	$file_types = array('jpg','gif','png');
	// max filesize 5mb
	$max_size = 5000000;
	//echo'<pre>';print_r($_FILES);exit;
	
	$time = time();
	$count = 1;
	
	foreach($all_file_fields as $fieldname){ 
		if($_FILES[$fieldname]['name'] != ''){
			
			$type = substr($_FILES[$fieldname]['name'], -3, 3);
						
			// check filetype
			if(in_array(strtolower($type), $file_types)){
				
				//check filesize
				if($_FILES[$fieldname]['size']>$max_size){
					$error = "File too big. Max filesize is ".$max_size." MB";
				
				}else{
				
					// new filename	
					$filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type;
			
					// move/upload file
					$image->load($_FILES[$fieldname]['tmp_name']);
					if($image->getWidth() > 150) { //if the image is larger that 150.
						$image->resizeToWidth(500); //resize to 500.
					}
					$target_path = $image_folder.basename($filename); //image path.
					
					$image->save($target_path); //save image to a directory.					
				
					//save array with filenames
					$images[$count] = $image_folder.$filename;
					$count = $count+1;

				}//end if

			}else{ $error = "Please use jpg, gif, png files";
			
			}//end if
		}//end if
	}//end foreach



if($error != ''){ echo $error;	
}else{
//error_reporting(E_ALL);
//ini_set('display_errors','On');

$id = $_POST['id'];
$id = substr($id, 0,5);
if($id < 1 || $id > 99999) exit;

  $servername = "localhost";
  $username	= "";
  $password	= "";
	
	if(!$_POST["title"] || !$_POST["rent"] || !$_POST["fees"]){
		header('location: fields.php');
		
}else if (!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["rent"])))){
		header('location: rent.php');
	
	}else{	
	$conn =  mysql_connect($servername,$username,$password)or die(mysql_error());
	mysql_select_db("genesis_apts",$conn);

// validate id belongs to user
	$sql_check = "SELECT * FROM apartments WHERE id = '".$id."' AND username = '".$myusername."'";
	$res = mysql_query($sql_check,$conn) or die(mysql_error());
	$count = mysql_num_rows($res);

if ($count > 0){

		  $sql = "UPDATE apartments SET title = '".mysql_real_escape_string($_POST['title'])."', description = '".mysql_real_escape_string($_POST['description'])."', cross_streets = '".mysql_real_escape_string($_POST['cross_streets'])."', county = '".mysql_real_escape_string($_POST['county'])."', town = '".mysql_real_escape_string($_POST['town'])."', service = '".mysql_real_escape_string($_POST['service'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', contact = '".mysql_real_escape_string($_POST['contact'])."', office = '".mysql_real_escape_string($_POST['office'])."', pets = '".mysql_real_escape_string($_POST['pets'])."', email = '".mysql_real_escape_string($_POST['email'])."', rooms = '".mysql_real_escape_string($_POST['rooms'])."', bath = '".mysql_real_escape_string($_POST['bath'])."', square = '".mysql_real_escape_string($_POST['square'])."', rent = '".mysql_real_escape_string($_POST['rent'])."', fees = '".mysql_real_escape_string($_POST['fees'])."', service = '".mysql_real_escape_string($_POST['service'])."', feeornofee = '".mysql_real_escape_string($_POST['feeornofee'])."', lease = '".mysql_real_escape_string($_POST['lease'])."', url = '".mysql_real_escape_string($_POST['url'])."', zipcode = '".mysql_real_escape_string($_POST['zipcode'])."', videotitle = '".mysql_real_escape_string($_POST['videotitle'])."', imageurl1 = '".mysql_real_escape_string($images[1])."', imageurl2 = '".mysql_real_escape_string($images[2])."', imageurl3 = '".mysql_real_escape_string($images[3])."', imageurl4 ='".mysql_real_escape_string($images[4])."', imageurl5 = '".mysql_real_escape_string($images[5])."', imageurl6 = '".mysql_real_escape_string($images[6])."', imageurl7 = '".mysql_real_escape_string($images[7])."', imageurl8 = '".mysql_real_escape_string($images[8])."', imageurl9 = '".mysql_real_escape_string($images[9])."', imageurl10 = '".mysql_real_escape_string($images[10])."', imageurl11 = '".mysql_real_escape_string($images[11])."', imageurl12 = '".mysql_real_escape_string($images[12])."' WHERE id = '".$id."'";

 		  
      //replace info with the table name above
      $result = mysql_query($sql,$conn) or die(mysql_error());
	        header('location: apartments.php');


}else{
        header('location: wrong.php');
}
	}	
		}
 
?>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

This script allows you to upload images and choose whether or not to overwrite the existing images (if any).  Please read it over and post back if you have any questions.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY (MUST ALREADY EXIST)
$uploads = 'RAY_junk';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'mp3'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

Avatar of genesisvh
genesisvh

ASKER

I appreciate the script but it took me forever to write the one above on my own using simpleimage.php I would like to know how I change the one I have to just replace the images that were selected? How I can overwrite the existing images? Thanks
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial