Page 1 of 1

Help me please on my image upload and display code

Posted: Tue Feb 25, 2014 9:22 am
by session
So i want to add image to picture folder what is on same folder where is supp_send.php file and image name are saved to database whit other data what comes trought html form.
My code adds atm data to mysql database and add image to the folder called pictures, so im actually just need help here to display that picture throught mysql query(i mean row data and image from folder).
And how wrong is save image name to database or i shold save image id somehow instead of image name ? Ofc saving image name i shold to if statement and check are the name exist ^^.

Code: Select all

	<?php
	session_start();
	?>
	<!DOCTYPE html>
	<html>
	<head>
	</head>

	<body>

		<form method="POST" action="supp_send.php" enctype="multipart/form-data">
			<table>
					<h2>Enter new product information<H2>
				
				<tr>
					<td>Id (auto-incremented)<input type="text" name="XmlId"><?php//Auto generate product id for new product toing it later?></td>
				</tr> 
				<tr>
					<td>SupplierId<input type="text" name="SupplierId"> </td><?php//Auto add supplier id , Toing it later?>
				</tr>
				<tr>
					<td>Category (Admin set Category)<input type="text" name="CategoryId"><?php//Admin enter Category id from dropdown list or smth?></td>
				</tr>
				<tr>
					<td>Product name</td><td><input type="text" name="ProductName" maxlength="100" ></td>
				</tr>
				<tr>
					<td>Product description </br> </td><td><textarea rows="4" cols="40" name="ProductDescription" maxlength="225" ></textarea></td>
				</tr>
				<tr>
					<td>Additional information for administrator </br> </td><td><textarea rows="4" cols="40"  name="AdditionalInformation" maxlength="225" ></textarea></td>
				</tr>
				<tr>
					<td>Unit Price (tykki hind)</td><td> <input type="text" name="UnitPrice" ></td>
				</tr>
				<tr>
					<td>Discount price (allahindlus)</td><td> <input type="text" name="DiscountPrice" ></td>
				</tr>
				<tr>
					<td>Product sell timer </td><td><input type="text" name="ProductSellTimer" ></td>
				</tr>
				<tr>
					<td>Quantity(mittu myykiks)</td><td><input type="text" name="Quantity" ></td>
				</tr>
				<tr>
					<td>Sell quantity(mitmes on alahindluses)</td><td> <input type="text" name="SellQuantity" ></td>
				</tr>
				<tr>
					<td>Sell quantity price (allahindluse hind)</td><td> <input type="text" name="SellQuantityPrice" ></td>
				</tr>
				
				<tr>
					<td>Image</td><td> <input type="file" accept="image/gif, image/jpeg, image/png" name="image" ></td>
				</tr>
				<tr>
					<td><input type="submit" name="submit" value="Send"></td>
				</tr>
			</table>
		</form>
	<?php
		// connection to database
		$connection= mysql_connect("localhost","root","    ") or die(mysql_error());
		mysql_select_db("   ") or die(mysql_error());
		
		if (isset($_POST['submit'])){
			
			//save form image row data to image variable
			$image  = $_FILES['image']['name'];  
			echo $image_name = $_FILES['image']['name'];//image name
			echo $image_type = $_FILES['image']['type'];//image type
			echo $image_size = $_FILES['image']['size']; //image size
			echo $image_tmp_name = $_FILES['image']['tmp_name'];//image tempetory file name
			
				//Get other form row data
				$SupplierId = $_POST['SupplierId'];
				$CategoryId = $_POST['CategoryId'];
				$ProductName = $_POST['ProductName'];
				$ProductDescription = $_POST['ProductDescription'];
				$AdditionalInformation = $_POST['AdditionalInformation'];
				$UnitPrice = $_POST['UnitPrice'];
				$DiscountPrice = $_POST['DiscountPrice'];
				$ProductSellTimer = $_POST['ProductSellTimer'];
				$Quantity = $_POST['Quantity'];
				$SellQuantity = $_POST['SellQuantity'];
				$SellQuantityPrice = $_POST['SellQuantityPrice'];
			//Checking are the image variable is null
			if($image =='')
			{
			echo"No image selected";
			exit();
			}
			else
			{
			//Moving image to picture folder
			move_uploaded_file($image_tmp_name,"pictures/$image_name");
			echo"Image uploaded successfully <br>";
			echo"<img src='pictures/$image_name'>";
			//saving other row data and IMAGE NAME to the database
			$result = mysql_query("INSERT INTO preproduct (XmlId,SupplierId,CategoryId,image,ProductName,ProductDescription,
																AdditionalInformation,UnitPrice,DiscountPrice,ProductSellTimer,Quantity,SellQuantity,SellQuantityPrice)
																VALUES
																(default,'$SupplierId','$CategoryId','$image','$ProductName','$ProductDescription','$AdditionalInformation',
																'$UnitPrice','$DiscountPrice','$ProductSellTimer','$Quantity','$SellQuantity','$SellQuantityPrice')",$connection);
								//if query did fail				
								if(!$result)
								{
									die("Database query failed: ". mysql_error());
									exit();
								}
								print"<br>";
								print "Thank you, your file has been uploaded.";
		}
		mysql_close($connection);
			
		}
			
	?>
	</body>
	</html>
[/b]

Re: Help me please on my image upload and display code

Posted: Wed Feb 26, 2014 2:36 am
by social_experiment
In terms of the table row; at this point you haven't written the image name to the database yet so there is no row to retrieve.
function.mysql-insert-id
have a look at this function - it retrieves the last id for an auto-increment column within your table so it can be used to retrieve the image name from the table; but only if the query has successfully completed.
session wrote:And how wrong is save image name to database or i shold save image id somehow instead of image name ?
Saving the image name isn't such a problem but a better alternative is to rename the image and store that new name instead of the existing name. The url's below will give you a better understanding and show you some more ideas for image upload security

http://www.phpclasses.org/blog/post/67- ... mages.html
https://www.owasp.org/index.php/Unrestr ... ile_Upload

Re: Help me please on my image upload and display code

Posted: Wed Feb 26, 2014 8:25 am
by session
Aight, thanks alot i go check out thows pages :P

Re: Help me please on my image upload and display code

Posted: Sat Mar 01, 2014 3:45 am
by session
ok, now , code check image type, size and if image file exist then it add random number into the image name.
Im kinda new on php, and to it only for practise :)


Code: Select all

	// connection to database
		$connection= mysql_connect("localhost","root","") or die(mysql_error());
		mysql_select_db("") or die(mysql_error());
		
		if (isset($_POST['submit'])){
		//save form image row data to image variable
		$image_name =$_FILES['image']['name'];//image name
		$image_type = $_FILES['image']['type'];//image type
		$image_size = $_FILES['image']['size']; //image size
		$image_tmp_name = $_FILES['image']['tmp_name'];//image tempetory file name
		
			if($image_name ==''){
			echo"No image selected";
			exit();
			}else{
			
				$allowedExts = array("gif", "jpeg", "jpg", "png");
				$temp = explode(".",$image_name);
				$extension = end($temp);
					if ((($_FILES["image"]["type"] == "image/gif")
					|| ($_FILES["image"]["type"] == "image/jpeg")
					|| ($_FILES["image"]["type"] == "image/jpg")
					|| ($_FILES["image"]["type"] == "image/png"))
					&& in_array($extension, $allowedExts))
						{
						if($_FILES["image"]["size"] > 400000){
						echo"Image size is to big".$_FILES['image']['size'];
						exit();
						}
						  else if($_FILES["image"]["error"] > 0)
							{
							echo "Error: " . $_FILES["image"]["error"] . "<br>";
							exit();
							}else
								{
								//Get other form row data
								$SupplierId = $_POST['SupplierId'];
								$CategoryId = $_POST['CategoryId'];
								$ProductName = $_POST['ProductName'];
								$ProductDescription = $_POST['ProductDescription'];
								$AdditionalInformation = $_POST['AdditionalInformation'];
								$UnitPrice = $_POST['UnitPrice'];
								$DiscountPrice = $_POST['DiscountPrice'];
								$ProductSellTimer = $_POST['ProductSellTimer'];
								$Quantity = $_POST['Quantity'];
								$SellQuantity = $_POST['SellQuantity'];
								$SellQuantityPrice = $_POST['SellQuantityPrice'];
																		
								$file ='pictures/'.$image_name.''; // 'pictures/'.$file (physical path)
								if (file_exists($file))
									{
									echo "The file <b> $image_name </b> exists. <br/>";
									include('scripts/rename_image.php');
										}
										else{	
															
										//Moving image to picture folder
										echo"Image uploaded successfully <br>";
										echo"<img src='pictures/$image_name'>";
																		
									//saving other row data and IMAGE_NAME to the database
									$result = mysql_query("INSERT INTO preproduct (XmlId,SupplierId,CategoryId,image,ProductName,ProductDescription,																AdditionalInformation,UnitPrice,DiscountPrice,ProductSellTimer,Quantity,SellQuantity,SellQuantityPrice)
						VALUES																						(default,'$SupplierId','$CategoryId','$image_name','$ProductName','$ProductDescription','$AdditionalInformation',																						'$UnitPrice','$DiscountPrice','$ProductSellTimer','$Quantity','$SellQuantity','$SellQuantityPrice')",$connection);
																				//if query did fail				
																				if(!$result){
																					die("Database query failed: ". mysql_error());
																					exit();
																				}
																		print"<br>";
																		print "Thank you, your file has been uploaded.";
																		}
												
												mysql_close($connection);
													
												}
						}
							else{
							echo"Invalid File : <br/>".$_FILES['image']['name']."<br/> Type : ".$_FILES['image']['type']."<br/><b>Only images allowed(gif, jpeg, jpg and png)!</b>";
							}
				}
			}
	
and change name when name exist



Code: Select all


	//separate extension from filename
	function findexts ($image_name){ 
	$image_name = strtolower($image_name) ;	
	$exts = split("[/\\.]", $image_name) ; 
	$n = count($exts)-1; 
	$exts = $exts[$n]; 
	return $exts; 
	} 
       //removing everything after '.' (if name contains '.' then it but random nr after the '.', need to make js script to not take images whit '.')
	$name = strstr($image_name,'.',true);

	//This applies the function to our file  
	$ext = findexts ($_FILES['image']['name']) ; 	
	
	//This line assigns a random number to a variable.
	$ran = rand () ;
							
	//This takes the random number you generated and adds a . on the end, so it is ready of the file extension to be appended.
	$ran2 = $ran.".";

	//saving image real name and generated random number together
	$new_imageName = $name.$ran2;

	//This assigns the subdirectory you want to save into... make sure it exists!
	$target = "pictures/";
							
	//This combines the directory, the random file name, and the extension $target = $target . $ran2.$ext; 
	$target = $target . $new_imageName.$ext; 	
						
		if(move_uploaded_file($_FILES['image']['tmp_name'], $target))  {
		//adding  extension to real image name and saving it into new variable
		$new_name =$new_imageName.$ext;
		
		echo "The file has been modify and saved as ".$new_name;	
		echo"<img src='pictures/$new_name'>";
			
		//saving other row data and IMAGE_NAME to the database
		$result = mysql_query("INSERT INTO preproduct (XmlId,SupplierId,CategoryId,image,ProductName,ProductDescription,
														AdditionalInformation,UnitPrice,DiscountPrice,ProductSellTimer,Quantity,SellQuantity,SellQuantityPrice)
								VALUES
														(default,'$SupplierId','$CategoryId','$new_name','$ProductName','$ProductDescription','$AdditionalInformation',
														'$UnitPrice','$DiscountPrice','$ProductSellTimer','$Quantity','$SellQuantity','$SellQuantityPrice')",$connection);
			//if query did fail				
			if(!$result)
				{
				die("Database query failed: ". mysql_error());
				exit();
				}
			print"<br>";
			print "Thank you, your file has been uploaded.";
		}
							
	 else{
		 echo"Something went wrong!";
		 exit();
		 }


Re: Help me please on my image upload and display code

Posted: Sat Mar 01, 2014 7:01 am
by Celauran
Is there a question in there somewhere? Something not working?