---
title: "bilduppladning: image + thumb?"
type: "forum-thread"
url: "https://www.webforum.nu/amne/php/148219-bilduppladning-image-thumb"
topic: "PHP"
topic_url: "https://www.webforum.nu/amne/php"
author: "tobili"
published: "2006-06-19T13:26:44.000Z"
updated: "2006-07-02T21:29:41.000Z"
replies: 11
views: 645
page: 1
pages: 1
language: "sv-SE"
site: "webForum — webforum.nu"
rights: "Upphovsrätten till varje inlägg tillhör dess författare."
attribution: "Citera som: webForum, https://www.webforum.nu/amne/php/148219-bilduppladning-image-thumb"
---

# bilduppladning: image + thumb?

## #1 — tobili, 2006-06-19T13:26Z

Har lite brådis med en grej. Behöver hitta åt ett script som laddar upp en bild på servern och även gör en thumb av samma bild som läggs i en annan mapp. Helst ganska enkelt eftersom jag är ganska kass på php. Och ja, jag har sökt runt... :)

Permalänk: https://www.webforum.nu/p/148219

## #2 — henke, 2006-06-19T18:01Z

Postade här tidigare idag ett i stort sett komplett script för just detta... men här är nu ett helt komplett script som gör precis det du vill.

```php
<?php
if(empty($_FILES)) {
	
	/*
	 * Visa uppladdningsformuläret
	*/
	echo('<form enctype="multipart/form-data" action="' . $_SERVER['REQUEST_URI'] . '" method="post">
    Upload file: <input name="userfile" type="file" />
    <input type="submit" value="Upload file" />
	</form>');
}
else {
	
	/*
	 * Ta hand om den uppladdade filen
	*/
	$uploaddir = 'uploads/';
	$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
	
	//Flytta filen
	if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
		echo '<img src="' . $uploadfile . '" />';
	} else {
		echo 'Possible file upload attack!';
		exit;
	}

	
	/*
	 * Skapa tumnagel
	*/
	//Set a maximum height and width
	$width = 100;
	$height = 100;
	
	//Get new dimensions
	list($width_orig, $height_orig) = getimagesize($uploadfile);
	
	if ($width && ($width_orig < $height_orig)) {
		$width = ($height / $height_orig) * $width_orig;
	} else {
		$height = ($width / $width_orig) * $height_orig;
	}
	
	//Resample
	$image_p = imagecreatetruecolor($width, $height);
	$image = imagecreatefromjpeg($uploadfile);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
	
	//Output
	imagejpeg($image_p, $uploaddir . 'thumbs/' . $_FILES['userfile']['name'], 100);

	
	/*
	 * Visa tumnageln
	*/
	echo '<img src="' . $uploaddir . 'thumbs/' . $_FILES['userfile']['name'] . '" />';
}
?>
```

Permalänk: https://www.webforum.nu/p/1833340

## #3 — tobili, 2006-06-25T20:41Z

Just vad jag letade efter (y) Har bara ett par till frågor. Hur ändrar jag filnamnet på den uppladdade filen, t.ex. till ett id som jag får från ett annat fält i samma formulär?

Jag skulle också vilja begränsa den större bilden till en viss bredd, utan att förlora proportionerna från originalbilden?

Och om jag vill styra tumnageln att alltid bli t.ex. 100x80?

Frågor, frågor ;)

Permalänk: https://www.webforum.nu/p/1834708

## #4 — henke, 2006-06-26T15:31Z

```php
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
```

Ändra *basename($\_FILES\['userfile'\]\['name'\]* till det namn som du vill ha på filen.

> **tobili skrev:**
>
> Jag skulle också vilja begränsa den större bilden till en viss bredd, utan att förlora proportionerna från originalbilden?

Kör Skapa tumnagel-delen även för den stora bilden.

> **tobili skrev:**
>
> Och om jag vill styra tumnageln att alltid bli t.ex. 100x80?

Kommentera bort hela Get new dimensions-delen.

Permalänk: https://www.webforum.nu/p/1834880

## #5 — tobili, 2006-06-28T21:58Z

Jag använder skriptet tillsammans med ett formulär där jag skriver data till en databas. Det är inte alltid att användaren kommer att ladda upp en bild men när jag inte har valt en bild får jag ett felmeddelande. Hur kan jag skripta runt det?

```
<?php

//Om formuläret har skickats
if ($_POST) {

//Bild----------------------------------------------------------------------------------------------
//Ta hand om den uppladdade bilden
		
	$imagename = $_POST['product_no'];
	$imagename = $imagename . ".jpg";
	$uploaddir = 'products/';
	$uploadfile = $uploaddir . basename($imagename);
	
	//Flytta filen
	if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
		echo '';
	} else {
		echo 'Det blev något fel när bilden skulle laddas upp, försök igen.';
		exit;
	}

//Skapa skalad bild
	
	//Set a maximum height and width
	$width = 265;
	$height = 227;
	
	//Get new dimensions
	list($width_orig, $height_orig) = getimagesize($uploadfile);
	
	if ($width && ($width_orig < $height_orig)) {
		$width = ($height / $height_orig) * $width_orig;
	} else {
		$height = ($width / $width_orig) * $height_orig;
	}
	
	//Resample
	$image_p = imagecreatetruecolor($width, $height);
	$image = imagecreatefromjpeg($uploadfile);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
	
	//Output
	imagejpeg($image_p, $uploaddir . $imagename, 100);

	
//Visa skalad bild
	
	//echo '<br><br><img src="' . $uploaddir . 'full/' . $name . '" />';
	//echo '<br><br>' . $imagename;
		
//Skapa tumnagel
	
	//Set a maximum height and width
	$width = 100;
	$height = 50;
	
	//Get new dimensions
	list($width_orig, $height_orig) = getimagesize($uploadfile);
	
	if ($width && ($width_orig < $height_orig)) {
		$width = ($height / $height_orig) * $width_orig;
	} else {
		$height = ($width / $width_orig) * $height_orig;
	}
	
	//Resample
	$image_p = imagecreatetruecolor($width, $height);
	$image = imagecreatefromjpeg($uploadfile);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
	
	//Output
	imagejpeg($image_p, $uploaddir . 'thumbs/' . $imagename, 100);
	
//Bild----------------------------------------------------------------------------------------------
//Data----------------------------------------------------------------------------------------------

		$postdata = array_map("mysql_real_escape_string", $_POST);

		$item = $_POST['item'];
		$name = $_POST['name'];
		$type = $_POST['type'];
		$text = $_POST['text'];
		$product_no = $_POST['product_no'];

	//Lägg till produkt
   	if ($postdata['event'] == 'add') {
	
		mysql_query($query="INSERT INTO products (name, type, text, product_no, image) VALUES ('$name', '$type', '$text', '$product_no', '$imagename')");
		$result=mysql_query("SELECT * FROM products ORDER BY product_id DESC LIMIT 1");
		$message = " har lagts till";
		

	//Ändra produkt
	} else if ($postdata['event'] == 'edit') {
	
		mysql_query($query="UPDATE products SET name = '$name', type = '$type', text = '$text' WHERE product_no = '$item'");
		$result=mysql_query("SELECT * FROM products WHERE product_no='$item'");
		$message = " har ändrats";

	}
			while ($row = mysql_fetch_array($result)) {
		
				echo "<font color='#FF0000'>Modellen " . $row['name'] . $message . "</font><br><br>";
				echo '<br><br><img src="' . $uploaddir . $imagename . '" />';
			
			}
} else {
?>
Formulär
```

Permalänk: https://www.webforum.nu/p/1835551

## #6 — henke, 2006-06-29T11:17Z

Sätt if(!empty($\_FILES)) runt den kod (rad 6 och rad 78) som hanterar bilden enligt följande:

```php
<?php

//Om formuläret har skickats
if ($_POST) {

	if(!empty($_FILES)) {
	
		//Bild----------------------------------------------------------------------------------------------
		//Ta hand om den uppladdade bilden
				
			$imagename = $_POST['product_no'];
			$imagename = $imagename . ".jpg";
			$uploaddir = 'products/';
			$uploadfile = $uploaddir . basename($imagename);
			
			//Flytta filen
			if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
				echo '';
			} else {
				echo 'Det blev något fel när bilden skulle laddas upp, försök igen.';
				exit;
			}
		
		//Skapa skalad bild
			
			//Set a maximum height and width
			$width = 265;
			$height = 227;
			
			//Get new dimensions
			list($width_orig, $height_orig) = getimagesize($uploadfile);
			
			if ($width && ($width_orig < $height_orig)) {
				$width = ($height / $height_orig) * $width_orig;
			} else {
				$height = ($width / $width_orig) * $height_orig;
			}
			
			//Resample
			$image_p = imagecreatetruecolor($width, $height);
			$image = imagecreatefromjpeg($uploadfile);
			imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
			
			//Output
			imagejpeg($image_p, $uploaddir . $imagename, 100);
		
			
		//Visa skalad bild
			
			//echo '<br><br><img src="' . $uploaddir . 'full/' . $name . '" />';
			//echo '<br><br>' . $imagename;
				
		//Skapa tumnagel
			
			//Set a maximum height and width
			$width = 100;
			$height = 50;
			
			//Get new dimensions
			list($width_orig, $height_orig) = getimagesize($uploadfile);
			
			if ($width && ($width_orig < $height_orig)) {
				$width = ($height / $height_orig) * $width_orig;
			} else {
				$height = ($width / $width_orig) * $height_orig;
			}
			
			//Resample
			$image_p = imagecreatetruecolor($width, $height);
			$image = imagecreatefromjpeg($uploadfile);
			imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
			
			//Output
			imagejpeg($image_p, $uploaddir . 'thumbs/' . $imagename, 100);
			
		//Bild----------------------------------------------------------------------------------------------
	
	}
	
	
	//Data----------------------------------------------------------------------------------------------
	
			$postdata = array_map("mysql_real_escape_string", $_POST);
	
			$item = $_POST['item'];
			$name = $_POST['name'];
			$type = $_POST['type'];
			$text = $_POST['text'];
			$product_no = $_POST['product_no'];

	//Lägg till produkt
   	if ($postdata['event'] == 'add') {
	
		mysql_query($query="INSERT INTO products (name, type, text, product_no, image) VALUES ('$name', '$type', '$text', '$product_no', '$imagename')");
		$result=mysql_query("SELECT * FROM products ORDER BY product_id DESC LIMIT 1");
		$message = " har lagts till";
		

	//Ändra produkt
	} else if ($postdata['event'] == 'edit') {
	
		mysql_query($query="UPDATE products SET name = '$name', type = '$type', text = '$text' WHERE product_no = '$item'");
		$result=mysql_query("SELECT * FROM products WHERE product_no='$item'");
		$message = " har ändrats";

	}
			while ($row = mysql_fetch_array($result)) {
		
				echo "<font color='#FF0000'>Modellen " . $row['name'] . $message . "</font><br><br>";
				echo '<br><br><img src="' . $uploaddir . $imagename . '" />';
			
			}
} else {
?>
Formulär
```

Permalänk: https://www.webforum.nu/p/1835631

## #7 — tobili, 2006-06-29T14:31Z

Får det inte att funka, gör precis som du beskriver. Får felmeddelande ändå.

Permalänk: https://www.webforum.nu/p/1835671

## #8 — henke, 2006-06-29T14:38Z

Oooops... mitt misstag. Skriv *if(empty($\_FILES\['userfile'\]\['name'\]))* istället så ska det fungera. Ersätt *userfile* med namnet på det fält där du väljer fil.

Permalänk: https://www.webforum.nu/p/1835673

## #9 — tobili, 2006-06-29T15:16Z

Eh njet, den funkar tyvärr inte heller. Har testat lite olika varianter, allt funkar fint förutom när jag inte laddar upp en bild.

Permalänk: https://www.webforum.nu/p/1835683

## #10 — henke, 2006-06-29T15:33Z

Konstigt att det inte fungerar... här är ett färdigt schematiskt exempel på hur du kan lösa det:

```php
<?php
//Inget har postats till sidan - visa uppladdningsformuläret
if(empty($_POST)) {    
    echo('<form enctype="multipart/form-data" action="' . $_SERVER['REQUEST_URI'] . '" method="post">
    Upload file: <input name="userfile" type="file" /><br />
    Text field: <input type="text" name="textfield" /><br />
	<input type="submit" value="Submit" />
    </form>');
}

//Något har postats - ta hand om postningen
else {

	//Kolla om någon bild har laddats upp
	if(!empty($_FILES['userfile']['name'])) {
     
		//Bild har laddats upp - ta hand om bilden
		
	}
	else {

		//Ingen bild laddades upp

	}
	
	//Saker som ska göras oavsett om det har laddats upp en bild eller inte
}
?>
```

Är du med på vad jag menar?

Permalänk: https://www.webforum.nu/p/1835685

## #11 — tobili, 2006-07-01T15:43Z

> **henke skrev:**
>
> Är du med på vad jag menar?

Jepp, och nu fick jag det att funka :) Tack (y)

Permalänk: https://www.webforum.nu/p/1836045

## #12 — tobili, 2006-07-02T21:29Z

En grej till... Jag använder samma kod för att skala originalbilden till max 689 px i både höjd eller bredd. Grejen är bara den att om bilden är mindre än 689 px så blåser koden upp den till 689 px. Hur kommer jag tillrätta med det lilla problemet?

```
/Skapa skalad bild 
             
            //Set a maximum height and width 
	      $width = 689;
	      $height = 689;
             
            //Get new dimensions 
            list($width_orig, $height_orig) = getimagesize($uploadfile); 
             
            if ($width && ($width_orig < $height_orig)) { 
                $width = ($height / $height_orig) * $width_orig; 
            } else { 
                $height = ($width / $width_orig) * $height_orig; 
            } 
             
            //Resample 
            $image_p = imagecreatetruecolor($width, $height); 
            $image = imagecreatefromjpeg($uploadfile); 
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
```

Permalänk: https://www.webforum.nu/p/1836306

---

Tråden på webben: https://www.webforum.nu/amne/php/148219-bilduppladning-image-thumb
