Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 762
  • Last Modified:

PHP image upload

Hello, I'm doing a project which is a real estate website what i need is when i add a property i can upload an image of the property to the server and save a reference in the database so it can be retrieved later. I also would like the script to rename the image to a unique id (could be the reference id) and re size the picture 148px × 98px

I will put 500 points for this Question as i think it need a lot of work

if you need anymore information please ask me Thank you :)

below is the code of my image upload form:

<fieldset>
                	<legend><b>Property Photo:</b></legend>
                    <input type="file" name="photo" id="photo">
                </fieldset>

Open in new window

0
MrFahad
Asked:
MrFahad
  • 16
  • 8
  • 3
1 Solution
 
Ray PaseurCommented:
This should help you get started.

Best regards, ~Ray
<?php // RAY_upload_example.php
// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php
 
// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';
 
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS
 
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt');
 
// ESTABLISH THE NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
 
 
 
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$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",
	6=>"Missing a temporary folder",
	7=>"Cannot write file to disk"
);
 
 
 
// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) )
{
	?>
	<h2>Upload a file</h2>
 
	<!-- ENCTYPE -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="p" value="1" />
	<!-- MAX_FILE_SIZE must precede the file input field -->
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
	<p>
	Find the file(s) you want to upload and click the "Upload" button below.
	</p>
 
	<?php 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 <b>overwrite</b> existing files.
	<input type="submit" name="_submit" value="Upload" />
	</form>
	<?php
	die();
}
else // WE HAVE GOT SOMETHING IN $_POST
{
 
// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: File Upload</h2>\n";
	echo "<p>\n";
 
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//	echo "<pre>"; var_dump($_FILES);
 
// 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() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
		$my_file	= $uploads . '/' . $f_name .'.'. $f_type;
 
// 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];
			echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
			die('Sorry');
		}
 
// MOVE THE FILE INTO THE DIRECTORY
		$overwrite	= $_POST['overwrite'];
		$file_size	= number_format($my_uploaded_file["size"]);
 
// IF THE FILE IS NEW
		if (!file_exists($my_new_file))
		{
			if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
			{
				$upload_success = 1;
			}
			else
			{
				$upload_success = -1;
			}
 
// IF THE FILE ALREADY EXISTS
		}
		else
		{
			echo "<b><i>$my_file</i></b> already exists.\n";
 
// SHOULD WE OVERWRITE THE FILE? IF NOT
			if (empty($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 "<b>Attempted Backup Failed!</b>\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 "It has been overwritten.\n"; }
		if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
		if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }
 
		if ($upload_success > 0)
		{
			echo "$file_size bytes uploaded.\n";
			chmod ($my_new_file, 0755);
		}
 
		echo "</p>\n";
		echo "<p><a href=\"$my_file\">See the file</a></p>\n";
// END ITERATOR
	}
}
?>

Open in new window

0
 
Ray PaseurCommented:
I will post another example that teaches how to resize an image.
0
 
Ray PaseurCommented:
This can be easily integrated with the uploads example.  As far as the data base goes, let's try to get the upload and resize working, then post the working code with a new question for the additional features and functions you need.

Good luck with your project, ~Ray


/* ********************************************************************************************* */
/* comment lines will work if GD2 is not installed, but will make poorer images                  */
/*                                                                                               */
// MAKE AN IMAGE INTO THE RIGHT SIZE FOR PAGE DISPLAY
function create_right_size_image($image, $width=720) {
 
	$source = imagecreatefromjpeg("$image");
 
	$imageX = imagesx($source);
	$imageY = imagesy($source);
 
	if ($imageX <= $width) {
return FALSE;
}
	if ($imageX > $width) {
		$tnailX = $width;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	} else {
		$tnailX	= $imageX;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	}
 
	$target = imagecreatetruecolor($tnailX, $tnailY);
//	$target = imagecreate($tnailX, $tnailY);
	imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
//	imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
 
return $target ;
}
/* ********************************************************************************************* */
 
 
// SAMPLE CALLING SEQUENCE
	if ($upload_success > 0) {
		if ($imageblob	= create_right_size_image($my_new_file)) {
			imagejpeg($imageblob, $my_new_file);
		}
	}

Open in new window

0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
MrFahadAuthor Commented:
Hello Ray,

for the 1st code how can you edit my present form

Thanks a lot buddy :)
here is my code:


<form name="form" enctype="multipart/form-data" id="form" action="create_property.php" onSubmit="return validate(this) ;" method="post" >
				<fieldset>
                
                	<legend><b>Property Name</b></legend>
                
                	<label for="PropertyName"><em>Please insert a unique property name:</em></label>
                    
                	<input name="PropertyName" type="text" id="PropertyName" />
                </fieldset>
                
                <br />
                
              	<fieldset>
                	<legend><b>Property Type</b></legend>
                    
<em>                Please enter the type of the property that you are adding:
 
</em>				<select name="PropertyType">
 
               		<option value="1">Aapartment</option>
                    
					<option value="2">Villa</option>
                    
               		</select>
                    
                </fieldset>
				
				<br />
                <fieldset>
                	<legend><b>Property Photo:</b></legend>
                    <input type="file" name="photo" id="photo">
                </fieldset>
                
                <br />
                
                <fieldset>
                  <legend><b>Property Address</b></legend>
                   
				  <label for="PropertyAddress"><em>Please enter the address of the property</em>:</label>
                  
                  <input name="PropertyAddress" type="text" id="PropertyAddress"/>
				</fieldset>
                <br/>
              	<fieldset>
              	  <legend><b>Area Of Property</b></legend>
                  
			  	  <label for="Area"><em>Please add the area of the property</em>:</label>
                  
              	  <input name="Area" type="text" value="" id="Area" /> <p>*only numbers allowed, use meter sequire</p>
				</fieldset>
                
                <br />
                <fieldset>
                
                  <legend><b>Listing Price:</b></legend>
 
				   <em>Please enter the price of the property:</em>
                   
          	      <input name="listedPrice" type="text" value="" id="listedPrice"/>
                 
            
               	</fieldset>
                
                <br />
                
                <fieldset>
                	<legend><b>Number Of Bed Rooms:</b></legend>
			 	
                	Please enter the number of bedrooms of the property:
			    <select name="No_bedroom">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
 
		        </select>
                </fieldset>
		<br />
        		<fieldset>
                
             		<legend><b>Listing Date:</b></legend>
                    
              
<select name="lmonth" >
                    
        <option value='01'>January</option>
                    <option value='02'>February</option>
                    <option value='03'>March</option>
                    <option value='04'>April</option>
                    <option value='05'>May</option>
                    <option value='06'>June</option>
                    <option value='07'>July</option>
                    <option value='08'>August</option>
                    <option value='09'>September</option>
                    <option value='10'>October</option>
                    <option value='11'>November</option>
                    <option value='12'>December</option>
                  </select>
                
                Month
                <select name="ldate" >
                  <option value='01'>01</option>
                  <option value='02'>02</option>
                  <option value='03'>03</option>
                  <option value='04'>04</option>
                  <option value='05'>05</option>
                  <option value='06'>06</option>
                  <option value='07'>07</option>
                  <option value='08'>08</option>
                  <option value='09'>09</option>
                  <option value='10'>10</option>
                  <option value='11'>11</option>
                  <option value='12'>12</option>
                  <option value='13'>13</option>
                  <option value='14'>14</option>
                  <option value='15'>15</option>
                  <option value='16'>16</option>
                  <option value='17'>17</option>
                  <option value='18'>18</option>
                  <option value='19'>19</option>
                  <option value='20'>20</option>
                  <option value='21'>21</option>
                  <option value='22'>22</option>
                  <option value='23'>23</option>
                  <option value='24'>24</option>
                  <option value='25'>25</option>
                  <option value='26'>26</option>
                  <option value='27'>27</option>
                  <option value='28'>28</option>
                  <option value='29'>29</option>
                  <option value='30'>30</option>
                  <option value='31'>31</option>
                </select>
                Date
                <input name="lyear" type="text" size="4" id="lyear"/>
              Year(yyyy)
         </fieldset>
         <br/>
            <fieldset>
            <legend><b>Date build:</b></legend> 
            <select name="month">
                    
        <option value='01'>January</option>
                    <option value='02'>February</option>
                    <option value='03'>March</option>
                    <option value='04'>April</option>
                    <option value='05'>May</option>
                    <option value='06'>June</option>
                    <option value='07'>July</option>
                    <option value='08'>August</option>
                    <option value='09'>September</option>
                    <option value='10'>October</option>
                    <option value='11'>November</option>
                    <option value='12'>December</option>
                  </select>
                
                Month
                <select name="date" >
                  <option value='01'>01</option>
                  <option value='02'>02</option>
                  <option value='03'>03</option>
                  <option value='04'>04</option>
                  <option value='05'>05</option>
                  <option value='06'>06</option>
                  <option value='07'>07</option>
                  <option value='08'>08</option>
                  <option value='09'>09</option>
                  <option value='10'>10</option>
                  <option value='11'>11</option>
                  <option value='12'>12</option>
                  <option value='13'>13</option>
                  <option value='14'>14</option>
                  <option value='15'>15</option>
                  <option value='16'>16</option>
                  <option value='17'>17</option>
                  <option value='18'>18</option>
                  <option value='19'>19</option>
                  <option value='20'>20</option>
                  <option value='21'>21</option>
                  <option value='22'>22</option>
                  <option value='23'>23</option>
                  <option value='24'>24</option>
                  <option value='25'>25</option>
                  <option value='26'>26</option>
                  <option value='27'>27</option>
                  <option value='28'>28</option>
                  <option value='29'>29</option>
                  <option value='30'>30</option>
                  <option value='31'>31</option>
                </select>
                Date
                <input name="year" type="text" size="4" id="year" />
              Year(yyyy)
              </fieldset>
             <br/>
          
		<fieldset>     
     
  		<legend><b>Description:</b></legend>
              
                <textarea name="description" cols="100" rows="5" value="" id="description"></textarea>
                <input type="submit" value="submit" />
                </fieldset>
		  </form>

Open in new window

0
 
MrFahadAuthor Commented:
the file upload field is at line 30

0
 
MrFahadAuthor Commented:
sorry forgot to post the action page code:
<?php
	$PropertyAddress = $_POST['PropertyAddress'];
	$Area = $_POST['Area'];
	$listedPrice = $_POST['listedPrice'];
	$description = $_POST['description'];
	$datebuild = $_POST['year'] . -  $_POST['month'] . -  $_POST['date'];
	$listingdate = $_POST['lyear'] . -  $_POST['lmonth'] . -  $_POST['ldate'];
	$nobedroom = $_POST['No_bedroom'];
	$PropertyType = $_POST['PropertyType'];
	
?>
<?php
	$query = "INSERT INTO properties (
									  PropertyType, PropertyAddress, No_bedroom, ListingDate, ListedPrice, DateBuild, Area, Description
									  )VALUES (
									  {$PropertyType}, '{$PropertyAddress}', {$nobedroom}, '{$listingdate}', {$listedPrice}, '{$datebuild}', {$Area}, '{$description}'
									  )";
	$result = mysql_query($query, $connection);
	if ($result) {
		// Success!
		redirect_to("success.php");
	} else {
		// Display error message.
		echo "<p>Property addtion failed.</p>";
		echo "<p>" . mysql_error() . "</p>";
	}
?>
 
<?php mysql_close($connection); ?>

Open in new window

0
 
MrFahadAuthor Commented:
any help please :D thank you
0
 
Lukasz ChmielewskiCommented:
the action page code, try below code

also you'll need to include a image resize class in that script, can be downloaded from
http://shiege.com/scripts/thumbnail/ 
I've already included that class in script

<? 
############################################## 
# Shiege Iseng Resize Class 
# 11 March 2003 
# shiegege_at_yahoo.com 
# View Demo : 
#   http://shiege.com/scripts/thumbnail/ 
/*############################################*/
 
/*
---------------------------------------------- 
Note : 
- GD must Enabled 
- Autodetect file extension (.jpg/jpeg, .png, .gif, .wbmp) 
  but some server can't generate .gif / .wbmp file types 
- If your GD not support 'ImageCreateTrueColor' function, 
  change one line from 'ImageCreateTrueColor' to 'ImageCreate' 
  (the position in 'show' and 'save' function) 
*/############################################ 
 
 
class thumbnail 
{ 
    var $img; 
 
    function thumbnail($imgfile) 
    { 
        //detect image format 
        $this->img["format"]=ereg_replace(".*\.(.*)$","\\1",$imgfile); 
        $this->img["format"]=strtoupper($this->img["format"]); 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            $this->img["format"]="JPEG"; 
            $this->img["src"] = ImageCreateFromJPEG ($imgfile); 
        } elseif ($this->img["format"]=="PNG") { 
            //PNG 
            $this->img["format"]="PNG"; 
            $this->img["src"] = ImageCreateFromPNG ($imgfile); 
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            $this->img["format"]="GIF"; 
            $this->img["src"] = ImageCreateFromGIF ($imgfile); 
        } elseif ($this->img["format"]=="WBMP") { 
            //WBMP 
            $this->img["format"]="WBMP"; 
            $this->img["src"] = ImageCreateFromWBMP ($imgfile); 
        } else { 
            //DEFAULT 
            echo "Not Supported File"; 
            exit(); 
        } 
        @$this->img["lebar"] = imagesx($this->img["src"]); 
        @$this->img["tinggi"] = imagesy($this->img["src"]); 
        //default quality jpeg 
        $this->img["quality"]=75; 
    } 
 
    function size_height($size=100) 
    { 
        //height 
        $this->img["tinggi_thumb"]=$size; 
        @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"]; 
    } 
 
    function size_width($size=100) 
    { 
        //width 
        $this->img["lebar_thumb"]=$size; 
        @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"]; 
    } 
 
    function size_auto($size=100) 
    { 
        //size 
        if ($this->img["lebar"]>=$this->img["tinggi"]) { 
            $this->img["lebar_thumb"]=$size; 
            @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"]; 
        } else { 
            $this->img["tinggi_thumb"]=$size; 
            @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"]; 
        } 
    } 
 
    function jpeg_quality($quality=75) 
    { 
        //jpeg quality 
        $this->img["quality"]=$quality; 
    } 
 
    function show() 
    { 
        //show thumb 
        @Header("Content-Type: image/".$this->img["format"]); 
 
        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/ 
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]); 
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]); 
 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            imageJPEG($this->img["des"],"",$this->img["quality"]); 
        } elseif ($this->img["format"]=="PNG") { 
            //PNG 
            imagePNG($this->img["des"]); 
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            imageGIF($this->img["des"]); 
        } elseif ($this->img["format"]=="WBMP") { 
            //WBMP 
            imageWBMP($this->img["des"]); 
        } 
    } 
 
    function save($save="") 
    { 
        //save thumb 
        if (empty($save)) $save=strtolower("./thumb.".$this->img["format"]); 
        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/ 
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]); 
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]); 
 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            imageJPEG($this->img["des"],"$save",$this->img["quality"]);
        } elseif ($this->img["format"]=="PNG") {
            //PNG
            imagePNG($this->img["des"],"$save");
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            imageGIF($this->img["des"],"$save"); 
        } elseif ($this->img["format"]=="WBMP") {
            //WBMP
            imageWBMP($this->img["des"],"$save");
        }
    } 
} 
?>
 
 
<?php
 
 
 
if(isset($_FILES['photo']['name']))
{
  $base_path = "yourimagepath/";
  $extension = explode(".",$_FILES['photo']['name']);
  $filename = "imgtest.".$extension[1];
 
  $target_path = $base_path.$filename;
  
  if(move_uploaded_file($_FILES['photo']['tmp_name'], $target_path))
  {
   	$thumb = new thumbnail($target_path);            // generate image_file, set filename to resize
       	$thumb->size_auto(200);                    // set the biggest width or height for thumbnail
       	$thumb->jpeg_quality(100);                // [OPTIONAL] set quality for jpeg only (0 - 100) (worst - best), default = 75
        $thumb->save($target_path);                // save your thumbnail to file
  }
 
 
 
	$PropertyAddress = $_POST['PropertyAddress'];
	$Area = $_POST['Area'];
	$listedPrice = $_POST['listedPrice'];
	$description = $_POST['description'];
	$datebuild = $_POST['year'] . -  $_POST['month'] . -  $_POST['date'];
	$listingdate = $_POST['lyear'] . -  $_POST['lmonth'] . -  $_POST['ldate'];
	$nobedroom = $_POST['No_bedroom'];
	$PropertyType = $_POST['PropertyType'];
	
?>
<?php
	$query = "INSERT INTO properties (
									  PropertyType, PropertyAddress, No_bedroom, ListingDate, ListedPrice, DateBuild, Area, Description
									  )VALUES (
									  {$PropertyType}, '{$PropertyAddress}', {$nobedroom}, '{$listingdate}', {$listedPrice}, '{$datebuild}', {$Area}, '{$description}'
									  )";
	$result = mysql_query($query, $connection);
	if ($result) {
		// Success!
		redirect_to("success.php");
	} else {
		// Display error message.
		echo "<p>Property addtion failed.</p>";
		echo "<p>" . mysql_error() . "</p>";
	}
?>
 
<?php mysql_close($connection); ?>

Open in new window

0
 
MrFahadAuthor Commented:
Parse error: syntax error, unexpected $end in /Applications/MAMP/htdocs/realestate/create_property.php on line 179
0
 
MrFahadAuthor Commented:
it's 189 in ur code
0
 
Lukasz ChmielewskiCommented:
somewhere the pairs of the open andclose tags do not match, search for it
sorry for the link I didn't know the page no longer exist. at least you have the class
0
 
MrFahadAuthor Commented:
ya good thing u had it :D ok i will search now for the open and closed tags
0
 
MrFahadAuthor Commented:
i found one mistake i forgot to require_once the connection file after i added it, it's still the same problem
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
/*
---------------------------------------------- 
Note : 
- GD must Enabled 
- Autodetect file extension (.jpg/jpeg, .png, .gif, .wbmp) 
  but some server can't generate .gif / .wbmp file types 
- If your GD not support 'ImageCreateTrueColor' function, 
  change one line from 'ImageCreateTrueColor' to 'ImageCreate' 
  (the position in 'show' and 'save' function) 
*/############################################ 
 
 
class thumbnail 
{ 
    var $img; 
 
    function thumbnail($imgfile) 
    { 
        //detect image format 
        $this->img["format"]=ereg_replace(".*\.(.*)$","\\1",$imgfile); 
        $this->img["format"]=strtoupper($this->img["format"]); 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            $this->img["format"]="JPEG"; 
            $this->img["src"] = ImageCreateFromJPEG ($imgfile); 
        } elseif ($this->img["format"]=="PNG") { 
            //PNG 
            $this->img["format"]="PNG"; 
            $this->img["src"] = ImageCreateFromPNG ($imgfile); 
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            $this->img["format"]="GIF"; 
            $this->img["src"] = ImageCreateFromGIF ($imgfile); 
        } elseif ($this->img["format"]=="WBMP") { 
            //WBMP 
            $this->img["format"]="WBMP"; 
            $this->img["src"] = ImageCreateFromWBMP ($imgfile); 
        } else { 
            //DEFAULT 
            echo "Not Supported File"; 
            exit(); 
        } 
        @$this->img["lebar"] = imagesx($this->img["src"]); 
        @$this->img["tinggi"] = imagesy($this->img["src"]); 
        //default quality jpeg 
        $this->img["quality"]=75; 
    } 
 
    function size_height($size=100) 
    { 
        //height 
        $this->img["tinggi_thumb"]=$size; 
        @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"]; 
    } 
 
    function size_width($size=100) 
    { 
        //width 
        $this->img["lebar_thumb"]=$size; 
        @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"]; 
    } 
 
    function size_auto($size=100) 
    { 
        //size 
        if ($this->img["lebar"]>=$this->img["tinggi"]) { 
            $this->img["lebar_thumb"]=$size; 
            @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"]; 
        } else { 
            $this->img["tinggi_thumb"]=$size; 
            @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"]; 
        } 
    } 
 
    function jpeg_quality($quality=75) 
    { 
        //jpeg quality 
        $this->img["quality"]=$quality; 
    } 
 
    function show() 
    { 
        //show thumb 
        @Header("Content-Type: image/".$this->img["format"]); 
 
        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/ 
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]); 
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]); 
 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            imageJPEG($this->img["des"],"",$this->img["quality"]); 
        } elseif ($this->img["format"]=="PNG") { 
            //PNG 
            imagePNG($this->img["des"]); 
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            imageGIF($this->img["des"]); 
        } elseif ($this->img["format"]=="WBMP") { 
            //WBMP 
            imageWBMP($this->img["des"]); 
        } 
    } 
 
    function save($save="") 
    { 
        //save thumb 
        if (empty($save)) $save=strtolower("./thumb.".$this->img["format"]); 
        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/ 
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]); 
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]); 
 
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") { 
            //JPEG 
            imageJPEG($this->img["des"],"$save",$this->img["quality"]);
        } elseif ($this->img["format"]=="PNG") {
            //PNG
            imagePNG($this->img["des"],"$save");
        } elseif ($this->img["format"]=="GIF") { 
            //GIF 
            imageGIF($this->img["des"],"$save"); 
        } elseif ($this->img["format"]=="WBMP") {
            //WBMP
            imageWBMP($this->img["des"],"$save");
        }
    } 
} 
?> 
<?php
 
 
 
if(isset($_FILES['photo']['name']))
{
  $base_path = "images/";
  $extension = explode(".",$_FILES['photo']['name']);
  $filename = "imgtest.".$extension[1];
 
  $target_path = $base_path.$filename;
  
  if(move_uploaded_file($_FILES['photo']['tmp_name'], $target_path))
  {
   	$thumb = new thumbnail($target_path);            // generate image_file, set filename to resize
       	$thumb->size_auto(200);                    // set the biggest width or height for thumbnail
       	$thumb->jpeg_quality(100);                // [OPTIONAL] set quality for jpeg only (0 - 100) (worst - best), default = 75
        $thumb->save($target_path);                // save your thumbnail to file
  }
 
 
 
	$PropertyAddress = $_POST['PropertyAddress'];
	$Area = $_POST['Area'];
	$listedPrice = $_POST['listedPrice'];
	$description = $_POST['description'];
	$datebuild = $_POST['year'] . -  $_POST['month'] . -  $_POST['date'];
	$listingdate = $_POST['lyear'] . -  $_POST['lmonth'] . -  $_POST['ldate'];
	$nobedroom = $_POST['No_bedroom'];
	$PropertyType = $_POST['PropertyType'];
	
?>
<?php
	$query = "INSERT INTO properties (
									  PropertyType, PropertyAddress, No_bedroom, ListingDate, ListedPrice, DateBuild, Area, Description
									  )VALUES (
									  {$PropertyType}, '{$PropertyAddress}', {$nobedroom}, '{$listingdate}', {$listedPrice}, '{$datebuild}', {$Area}, '{$description}'
									  )";
	$result = mysql_query($query, $connection);
	if ($result) {
		// Success!
															  header( 'Location: success.php' );
	} else {
		// Display error message.
		echo "<p>Property addtion failed.</p>";
		echo "<p>" . mysql_error() . "</p>";
	}
?>
<?php mysql_close($connection); ?>

Open in new window

0
 
MrFahadAuthor Commented:
by they way, why don't we just use one <?php ?> does it make a difference ?
0
 
Lukasz ChmielewskiCommented:
true, no difference, I've just pasted the code
0
 
MrFahadAuthor Commented:
so what's the problem?
0
 
MrFahadAuthor Commented:
Roads it worked no we just need to do the (add info to database) and unique ID by the way, i tried to upload 280kb (1920 x 1400) image but it give me this error:

Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 7680 bytes) in /Applications/MAMP/htdocs/realestate/create_property.php on line 28
0
 
Lukasz ChmielewskiCommented:
you need to increase the file size limit
take a look here
http://www.tech-recipes.com/rx/777/solve-php-fatal-error-allowed-memory-size-of-8388608-bytes-exhausted-tried/

as for the upload try to add a function which hashes the filename
$h = md5($_FILES['photo']['name']);
and insert into database into table containing image data

insert into imginfo('$h','$_FILES[photo][name]');
so you will receive a unique string for each file name (you need to remember that every image has to be of a unique name)
0
 
MrFahadAuthor Commented:
Can't we do some thing like:

adding timestamp as a suffix to the name

thank you :)
0
 
MrFahadAuthor Commented:
and ya what if i want the name of the image to be in a field in the properties table
0
 
Lukasz ChmielewskiCommented:
of course
$t = time();
$filename_to_db = $t.$_FILES['photo']['name'];
0
 
Lukasz ChmielewskiCommented:
then you insert into table values
('$filename_to_db',($_POST[photo][name]')
0
 
MrFahadAuthor Commented:
i set the limit to 124 and still get the error
0
 
Lukasz ChmielewskiCommented:
you need to set the value in proper php.ini file AND restart apache to this change take place
0
 
MrFahadAuthor Commented:
lol i didn't know that thanks for the info
0
 
Lukasz ChmielewskiCommented:
well, in case you know, the proper set of the value in proper place needs to be reloaded for the apache. this is the classic case for the xampp for windows where there are about three php.ini files and you need to know which php.ini must be changed, the restarting of apache does nothing if you change the bad file. maybe your mamp has the same issue, so thats why i wrote that - no need to be ironic, Im just trying to help
0
 
MrFahadAuthor Commented:
Great Help, Thanks buddy :)
0

Featured Post

Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

  • 16
  • 8
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now