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: 351
  • Last Modified:

php code to browse and upload an image.

Hi,

I want to browse and upload an image to the database. once i upload it i need a preview of it before i store the image to the database.also tell me in what format i shd store it in the database.

i am using php and mysql.
0
whspider
Asked:
whspider
  • 4
  • 3
  • 2
2 Solutions
 
mahomeCommented:
Don't store images in a database. It makes things complicated and your bound to your database. Why do you want to do that. Just store the imagePath in the DB.
0
 
whspiderAuthor Commented:
ok even then tell me how to browse,upload and preview the image
0
 
mahomeCommented:
Have a look here: http://www.w3schools.com/PHP/php_file_upload.asp

For a preview you also have to store the image, so that you can refer to it in img-Tag. You could use a temporary preview folder and if the file should be stored use another folder where you really store it.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Ray PaseurCommented:
Here is an example that teaches how to upload images and then look at them.  I concur with the others who say "Do not put the image itself into the data base"

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
 
whspiderAuthor Commented:
Hi,

thank you for the reply...i executed the code am getting an error think i missed something

Warning: move_uploaded_file(C:\Program Files\xampp\htdocs\test/\test\upload/star1.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in C:\Program Files\xampp\htdocs\test\upload.php on line 117

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Program Files\xampp\tmp\php51.tmp' to 'C:\Program Files\xampp\htdocs\test/\test\upload/star1.png' in C:\Program Files\xampp\htdocs\test\upload.php on line 117


line 117 is

if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))

can u tell me what $my_uploaded_file['tmp_name'] will do?
0
 
Ray PaseurCommented:
In the code I posted, line 117 says this:

   echo "<b><i>$my_file</i></b> already exists.\n";

So your code must be different.  Let's do this...

Add error_reporting(E_ALL) to the top of the script.

Use var_dump($_FILES) to print out the values.

Use var_dump($my_uploaded_file) to print out the values.

Can you please post the code you're using so we can see what goes on before it gets to line 117?  Thanks, ~Ray
0
 
whspiderAuthor Commented:
this is the code am using.....but i did not change anything i only changed the file path and table name
<?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
 
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="members"; // Database name
$tbl_name="images";
 
// 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");
 
 
 
// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = '\test\upload';
 
// 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:
What are the values printed out by the var_dump() statements?
0
 
Ray PaseurCommented:
Another thought - do you need to use '\' instead of '/' in the file paths?  
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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