Jump to content

Image Uploading help


andrew_biggart

Recommended Posts

I am trying to built a php upload script to allow users to upload profile pictures. I want it to do the following...

 

1. upload the image

2 . resize original image without distorting it

2. store the file name in the database

3. create and save a thumbnail

 

So far I have got the following code which successfully uploads the image but doesn't change the file name in the database any ideas why and also what step do I take next? Any help of tutorials would be appreciated thanks.

 

<?php

$host="xxxx"; // Host name
$db_username="xxxx"; // Mysql username
$db_password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name

// Connect to server and select databse.
mysql_connect("$host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");


$username=$_SESSION['myusername'];
$query = "SELECT User_id FROM biggartfp9_user_infot WHERE Username = '$username'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result);
$User_id = $row['User_id'];
$uploadDir = '../Profile_pics/';

if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName  = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];

$filePath = $uploadDir . $fileName;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading!";
exit;
}

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
    $filePath = addslashes($filePath);
}

$result = mysql_query("UPDATE biggartfp9_user_infot SET Profile_picture='$fileName' WHERE User_id='$User_id'") 
or die(mysql_error());  

echo "$fileName <h1>Success!</h1> You have successfully added a Profile Photo. <a href=profile.php?username=$User_id>Return to Profile</a><br><br><br>";
}
else
{
echo" 
<form name=Image enctype=multipart/form-data method=POST>
<table cellspacing=2 cellpadding=2 border=0>
<tr><td>Image: </td><td><input type=file name=file accept=image/gif, image/jpeg, image/x-ms-bmp, image/x-png size=26 class=textbox /></td></tr>
<tr><td> </td><td><input type=submit name=submit value=Upload class=button /></td></tr></table>
</form><br>";
}
?>

 

Link to comment
https://forums.phpfreaks.com/topic/198109-image-uploading-help/
Share on other sites

I'm not too sure about creating thumbnails. Though here is an image upload form, with a class to process it, also to insert it into the database (depending on what you want to do)

 

The main page is..

<?php
include("inc/config.php"); //Connection to database
include('classes/imgmanip.php'); //Directory to the class

if(isset($_POST['upload'])){
		if (isset($_FILES['photo']) && $_FILES['photo']['error'] != 4) {
			$img = new ImageManip($_FILES['photo'], 10000000000); // 1000000000 is the max file size
			$img->set_size(400,400); //Replace 400, 400 with the size you wish to resize the image to.
			$file = "profile/photos/" . time() . "-" . $_FILES['photo']['name'];
			$img->save($file);
			//Save to database
			$query = mysql_query("--- PUT YOUR QUERY HERE ---") or trigger_error("Query failed: ".mysql_error());
		}
	}
	echo "<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">
	<label for=\"file\">Filename:</label>
	<input type=\"file\" name=\"photo\" id=\"photo\" />
	<br />
	<input type=\"submit\" name=\"upload\" value=\"Submit\" />
	</form>";
?>

 

The class is..

<?php

class ImageManip {

var $height;
var $width;

var $data = null;
var $details;

var $errors = array();

// You can add as many as you want, dont worry about the uppercase versions
// we will handle that in the code
var $file_types = array(
	'image/jpeg',
	'image/pjpeg',
	'image/gif'
);

function __construct($array, $max_file_size) {
	// Once the class is called this function is started, so we want to check the rest of the parameters
	if ($array['error'] > 0) {
		// Throw your error warning //
		$errors[] = '- Return Code: ' . $array["error"];
	} elseif (!in_array(strtolower($array['type']),$this->file_types)) {
		// Throw an invalid file type error //
		$errors[] = '- Invalid filetype';
	} elseif ($array['size'] > $max_file_size) {
		// Throw a file size limit exceeded error //
		$errors[] = '- Max file size exceeded';
	} else {
		// Lets begin //
		$this->details = $array;
		$this->data = imagecreatefromstring(file_get_contents($array['tmp_name']));
	}
}

public function set_size($width = null, $height = null) {
	// This pretty much explains itself //
	if (is_null($width) || is_null($height)) {
		// Some sort of warning that height and width are both required //
		$errors[] = '- Height and Width are both required';
	} else {
		$this->height = $height; $this->width = $width;
	}
}

private function resize() {
	# Keeps aspect ratio of the image to the longest edge #
  	$width = imagesx($this->data);
  	$height = imagesy($this->data);
  	$scale = min($this->width/$width, $this->height/$height);
  	if ($scale < 1) {
   		$new_width = floor($scale*$width);
    	$new_height = floor($scale*$height);

    	$img = imagecreatetruecolor($new_width, $new_height);

    	imagecopyresampled($img, $this->data, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    	imagedestroy($this->data);
    	$this->data = $img;
  	}
}

public function save($output = null) {
	if (!empty($this->errors)) {
		echo join('<br/>',$this->errors);
	} else {
		if ($output === null) {
			// Can put direct output stuff in here //
			header("Content-type: image/jpeg");
			imagejpeg($this->data,'',100);
		} else {
			if (file_exists($output)) {
				echo 'This file ['.$this->details['name'].'] already exists';
			} else {
				// Starts the resizing //
				$this->resize();
				// Outputs the image to a file //
				return imagejpeg($this->data,$output,500);
				//imagedestroy($this->data);
			}
		}
	}
}
}

?>

 

This resizes an humungus image, to a size you put down on the form validation (400, 400)

Smaller images, do not get resized. This also doesn't crop to square it.

I've got a script which resizes, and crops. Isn't involved with the file upload though, but I use it for thumbnails also. :)

Ok yea that is working but again the only bit I cannot seem to get working is the adding to the database, I am writing the query wrong?

 

<?php
include('upload_class.php'); //Directory to the class

$username=$_SESSION['myusername'];
$query = "SELECT User_id FROM biggartfp9_user_infot WHERE Username = '$username'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result);
$User_id = $row['User_id'];

if(isset($_POST['upload'])){
		if (isset($_FILES['photo']) && $_FILES['photo']['error'] != 4) {
			$img = new ImageManip($_FILES['photo'], 10000000000); // 1000000000 is the max file size
			$img->set_size(100,100); //Replace 400, 400 with the size you wish to resize the image to.
			$file = "../Profile_pics/" . time() . "-" . $_FILES['photo']['name'];
			$img->save($file);
			//Save to database
			$query = mysql_query("UPDATE biggartfp9_user_infot SET Profile_picture = '$file' WHERE User_id = '$User_id'") or trigger_error("Query failed: ".mysql_error());
		}
	}
	echo "<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">
	<label for=\"file\">Filename:</label>
	<input type=\"file\" name=\"photo\" id=\"photo\" />
	<br />
	<input type=\"submit\" name=\"upload\" value=\"Submit\" />
	</form>";
?>

 

No need to shout.. >'_'<

You can remove

$username=$_SESSION['myusername'];
$query = "SELECT User_id FROM biggartfp9_user_infot WHERE Username = '$username'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result);
$User_id = $row['User_id'];

 

And you can just change the actual query to..

$query = mysql_query("UPDATE biggartfp9_user_infot SET Profile_picture = '$file' WHERE Username = '".$_SESSION['myusername']."'") or trigger_error("Query failed: ".mysql_error());

 

For lack of more code. The query itself shouldn't be a problem.. it should execute it as it works for me, and if it gives out no errors.. then I have no idea on whats going on? Other than perhaps faulty connection with your database etc.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.