Jump to content

filesystem - get the image filename, then insert to database.


clearmind

Recommended Posts

Hello everybody!

 

I'm a newbie with PHP and i'm trying to build my first application.

It's a multipart data form,  with image upload functionality.

 

<form method="post" action="process.php" enctype="multipart/form-data">
  <label>Bus Name: </label>
  <input name="busname" id="name" type="text" maxlength="100" />
  <br />
<label>Bus Description: </label>
<textarea name="description" id="description" cols="45" rows="5"></textarea>
<br />
<label>select an image:</label>
<input type="file" id="file" name="file" />
<input type="submit" id="add" value="add" />
</form>

 

The data is submitted to "process.php" file:

include 'config.php';

/* File Upload */
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    if (file_exists("../upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . "  - file already exists. ";
  echo "please go back and select another image file." ;
  exit;
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "../upload/" . $_FILES["file"]["name"]);
      echo "image saved successfully</br>";
  echo $_FILES["file"]["name"] . '</br>';
      }
    }
  }
else
  {
  echo "Invalid file. Please go back and choose a valid image file!";

  exit;
  }
  

/* post variables */
if(isset($_POST['add']))
{
$username = $_POST['name'];
$password = $_POST['description'];
}
/* insert name and description */
$sql="INSERT INTO bus (name, description) VALUES ('$_POST[busname]','$_POST[description]')";
if (!mysql_query($sql))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

 

As you can see the values of "name" and "description", will be inserted to the database.

Also i want to get the image filename of the uploaded file into database. I'm gonna use it at a later time to link the uploaded image..

I'm trying to print the "$_FILES["file"]["name"]" but  i'm completely stuck..

Is there any way to do this??

 

Thanks in advance!

 

DATABASE:

-- Database: `busdb`
--

-- --------------------------------------------------------

--
-- Table structure for table `bus`
--

CREATE TABLE IF NOT EXISTS `bus` (
  `busID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(220) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(220) COLLATE utf8_unicode_ci NOT NULL,
  `image` varchar(220) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`busID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=29 ;

 

 

 

 

Here is a copy of the upload script I use on Funnyhq.com - It also creates a thumbnail, which is very handy :)

 

Take a look, maybe you can get it to work how you like.

 

if($_FILES['uploadedfile']['type'] == "image/jpeg" && $_FILES['uploadedfile']['size'] < 3000000)
{
// … accept the file
}
else
{
// The file was the wrong format or size
?>
<p>Error processing file.  It is the wrong format (.jpeg only) or too big.</p>
<?php
}
$target_folder = '../pictures/'; // This is the folder to which the images will be saved
$upload_image = $target_folder.basename($_FILES['uploadedfile']['name']); // The new file location
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_image)) 
{
// Successful move…now do the image manipulation
}
else
{
// There was a problem with the file and it wasn't moved to the server.
?>
<p>Error processing file.  It may be too large.</p>
<?php
}
$ran = rand () ;
$newname = $ran; // Get the supplied image name and sanitize it
$caption = $_POST['image_caption']; // Get the supplied caption and sanitize it
$thumbnail = $target_folder.$newname."_tn.jpg"; // Set the thumbnail name
$actual = $target_folder.$newname.".jpg"; // Set the actual image name
// Get new sizes
list($width, $height) = getimagesize($upload_image);
$newwidth = 80; // This can be a set value or a percentage of original size ($width)
$newheight = 80; // This can be a set value or a percentage of original size ($height)

// Load the images
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($upload_image);

// Resize the $thumb image.
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Save the new file to the location specified by $thumbnail
imagejpeg($thumb, $thumbnail, 100);
rename($upload_image, $actual);
};

 

After that, you can call the file name using $actual, so you can insert the value of $actual into your database under "filename" or whatever you use.

 

Ahh yes, this also assigns the picture a random name, such as 1913123.jpg ... don't know if you want that or not, but it's there.

Thanks for you suggestion Jax2! It may be useful indeed!

Also I think my current script has a lot of error reporting functionality

so i can't stop thinking the way to solve this problem in my current script..... :((

 

How can we assign the filename ( $_FILES["file"]["name"] ) into something else - suitable for inserting to database?

  • 4 weeks later...

There is one more issue for me to solve... Is it possible to include image resizing functionality within?

Should i use the

$file_name = trim($_FILES['file']['name']);// original name of file

,  or the actual image file name ($imfile?

I've searched through many resources including this one:

http://www.phpfreaks.com/forums/index.php/topic,294431.0.html

but i didn't make it through....

 

Also as i see in php manual would anyone suggest to use the "Imagick::resizeImage " function? (notice that my host supports ImageMagick)

Any idea anyone please!?

 

Here is a copy of the upload script I use on Funnyhq.com - It also creates a thumbnail, which is very handy :)

 

I know feel like uploading a .php file and tell my browser .php is an image with the header image/jpeg :D

 

Read: http://www.scanit.be/uploads/php-file-upload.pdf as your website (funnyhq.com) and now those that copied your code are in danger

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.