I have two problems with this code.
1. when i refresh the page it uploads the file again.
2. how to i validate the form if required fields are not filled ?
i have added the code validation but its not working and there are no errors.

<?php
if (isset($_POST['upload']))



  if ($_FILES['userfile']['size'] > 0) {

{
echo '<pre>'; 
print_r($_POST); 
echo '</pre>';
}

$allowed_filetypes = array(
      '.jpg',
      '.jpeg',
      '.png',
      '.gif'
    );

$requiredFields = array(
  'imagetitle',
  'pickdate',
  'option',
  'list1',
  'list2',
);

$errors = array();
foreach($_POST AS $key => $value)
{


    // is this a required field?
    if(in_array($key, $requiredFields) && $value == '') 

     $errors[] = "The field $key is required.";


}

    $max_filesize      = 1445760;
    $description       = $_POST['imagetitle'];
    $filename          = $_FILES['userfile']['name'];
    $ext               = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
    if (!in_array($ext, $allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
    if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');

    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];
    $date= $_POST['pickdate'];
    $fp       = fopen($tmpName, 'r');
    $content  = fread($fp, filesize($tmpName));
    $content  = addslashes($content);
    fclose($fp);
    if (!get_magic_quotes_gpc()) {
      $fileName = addslashes($fileName);
    } //!get_magic_quotes_gpc()

    include 'config.php';
    include 'opendb.php';
    $query = "INSERT INTO upload (column1,column2,column3,column4,column5,column6,) " . "VALUES ('$fileName', '$fileSize', '$fileType', '$content', '$date','$description')";
    mysql_query($query) or die('Error, query failed');
    include 'closedb.php';

    echo "<br>File $fileName uploaded<br>";

  } //isset($_POST['upload']) && $_FILES['userfile']['size'] > 0
  else {
    echo 'Please Upload an Image.';
  } //isset($_POST['upload'])

?>



<form action="uploadform.php" method="post" enctype="multipart/form-data">

 <br><br> 

Image Title:  <input type="text"    name="imagetitle"  ><br><br>
              <input type="hidden"  name="MAX_FILE_SIZE" value="2000000">
              <input type="file"    name="userfile"  id="userfile" ><br><br>
Choose Date:  <input type="date"    name="pickdate" > <br><br>



<input id="button_1" type="radio" name="option"  value="button1" /><label for="button_1" >Button 1</label>
<input id="button_2" type="radio" name="option"  value="button2" /><label for="button_2" >Button 2</label><br><br>

<select name="list1"> 
      <option value="">Select Options</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option> 
      <option value="option3">Option 3</option>
</select>
<br><br>
<select name="list2"> 
      <option value="">Select Type</option>
      <option value="type1">Option 1</option>
      <option value="type2">Option 2</option> 
      <option value="type3">Option 3</option>
</select>

<br><br>

        <input name="upload" type="submit" class="box" id="upload" value=" Upload " >



</form>

Recommended Answers

All 30 Replies

Member Avatar for diafol

This issue comes from having the form handling code in the same page as the form itself. If you place the form handling code in a separate file and then

header('Location: form.php');
exit; 

at the end of it, you should be OK. Change the form 'action' to the form handling file, e.g. 'formhandler.php'.

thnx now refresh dont upload the data
how can i correct the required field check if all fields are filled ?

Member Avatar for diafol

Set a session variable:

In form handler:

session_start();
$_SESSION['form_upload']['errors'] = NULL;


...All your code...

if($errors) $_SESSION['form_upload']['errors'] = $errors;
header("Location: form.php");
exit;

In your form page:

session_start();
$errorPrint = '';
if(isset($_SESSION['form_upload']['errors']) && $_SESSION['form_upload']['errors'])
{
    $errorPrint = $_SESSION['form_upload']['errors'];
    unset($_SESSION['form_upload']['errors']);
}

Then just do something with the $errorPrint array. There are quite a few ways to do this. REMEMBER to place session_start() at the very top of every page directly under the <?php tag

how can i display data after submission ?

as it redirects to form page. if i dont redirect to form page it can be refreshed to submit again. so how can i encounter this ?

I think Diafol have already given you what you need. Store the submitted information in session.

In fact, you can store them as an array. Below is a sample codes...

$upload_info = array($title, $description, $uploaded_file_name, $other_things_you_want);

$_SESSION['up_data'] = $upload_info;
header("Location: form.php");
exit;

on redirect, the user will land on the form.php. place session_start() on top of the page as suggested above.. we can access the information stored in the session.

echo 'Title : '. $_SESSION['updata'][0].'<br/>';
echo 'Description :'. $_SESSION['updata'][1].'<br/>';
echo 'Uploaded File: '. $_SESSION['updata'][2].'<br/>';

That's pretty much it.....................

Added Later:
You can also do the database insertion here if you desire to do so.

Set a session variable:

In form handler:

session_start();
$_SESSION['form_upload']['errors'] = NULL;
...All your code...
if($errors) $_SESSION['form_upload']['errors'] = $errors;
header("Location: form.php");
exit;

In your form page:

session_start();
$errorPrint = '';
if(isset($_SESSION['form_upload']['errors']) && $_SESSION['form_upload']['errors'])
{
    $errorPrint = $_SESSION['form_upload']['errors'];
    unset($_SESSION['form_upload']['errors']);
}

This code is not showing any errors even if i only upload image and dont fill the all other fields ,image still alone gets uploaded to database:(.It doesnot check that all fields are filled or not.I want to upload data when all fields are filled. Am i doing wrong in my code ?.
here is my code:

upload.php

<?php 
//session 
session_start();
$errorPrint = '';
if(isset($_SESSION['form_upload']['errors']) && $_SESSION['form_upload']['errors'])
{
    $errorPrint = $_SESSION['form_upload']['errors'];
    unset($_SESSION['form_upload']['errors']);
}

 ?>



<!DOCTYPE HTML> 
<html>
<head>
  <title>Upload Image form</title>
</head>
<body> 

<form action="formhandler.php" method="post" enctype="multipart/form-data">
 <br><br> 
Image Title:  <input type="text"    name="imagetitle"  ><br><br>
              <input type="hidden"  name="MAX_FILE_SIZE" value="2000000">
              <input type="file"    name="userfile"  id="userfile" ><br><br>
Choose Date:  <input type="date"    name="pickdate" > <br><br>
<input id="button_1" type="radio" name="option"  value="button1" /><label for="button_1" >Button 1</label>
<input id="button_2" type="radio" name="option"  value="button2" /><label for="button_2" >Button 2</label><br><br>
<select name="list1"> 
      <option value="">Select Options</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option> 
      <option value="option3">Option 3</option>
</select>
<br><br>

<select name="list2"> 
      <option value="">Select Type</option>
      <option value="type1">Option 1</option>
      <option value="type2">Option 2</option> 
      <option value="type3">Option 3</option>
</select>
<br><br>
        <input name="upload" type="submit" class="box"  id="upload" value=" Upload " >
</form>


</body>

</html>

formhander.php

<?php
//session 
session_start();
$_SESSION['form_upload']['errors'] = NULL;



$description=$fileSize=$filename=$date="";

if (isset($_POST['upload']))

 {

  if ($_FILES['userfile']['size'] > 0) 
  {


echo '<pre>'; // to get this work delete exit function at the  bottom
print_r($_POST); 
echo '</pre>';


$allowed_filetypes = array(
      '.jpg',
      '.jpeg',
      '.png',
      '.gif'
    );


    $max_filesize      = 1445760;
    $description       = $_POST['imagetitle'];
    $filename          = $_FILES['userfile']['name'];
    $ext               = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
    if (!in_array($ext, $allowed_filetypes))
      die('The file you attempted to upload is not allowed.');

    if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');

    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];
    $date= $_POST['pickdate'];

    $fp       = fopen($tmpName, 'r');
    $content  = fread($fp, filesize($tmpName));
    $content  = addslashes($content);
    fclose($fp);
    if (!get_magic_quotes_gpc()) {
      $fileName = addslashes($fileName);
    } //!get_magic_quotes_gpc()

    include 'config.php';
    include 'opendb.php';

    $query = "INSERT INTO upload (name, size, type, content ,date,description ) " . "VALUES ('$fileName', '$fileSize', '$fileType', '$content', '$date','$description')";
    mysql_query($query) or die('Error, query failed');

    include 'closedb.php';

    echo "<br>File $fileName uploaded<br>";


  }//isset($_POST['upload']) && $_FILES['userfile']['size'] > 0


  else {
    echo 'Please Upload an Image.';
  }


  } //isset($_POST['upload'])






echo "<h2>Your Input:</h2>";
echo "Title =".$description;
echo "<br>";
echo "Filename =".$filename;
echo "<br>";
echo "File size  =".$fileSize;
echo "<br>";
echo "Date =".$date;



if($errors) $_SESSION['form_upload']['errors'] = $errors;
header('Location: upload.php');
exit;


?>

and database

CREATE TABLE IF NOT EXISTS `upload` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `type` varchar(30) NOT NULL,
  `size` int(11) NOT NULL,
  `content` mediumblob NOT NULL,
  `date` date NOT NULL,
  `description` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Member Avatar for diafol

You don't echo anything in the formhandler page as it should not be displayed to the user - it's sole purpose is to process the data and to pass any feedback to the form page.

You don't seem to output $errorPrint anywhere in the form page, so you won't see anything,

You could do something like:

echo implode("<br />",$errorPrint);

wherever you need errors to be displayed in or close to the form.

Warning: implode(): Invalid arguments passed in \upload_new\upload.php on line 11

and also it it doesnot check the empty fields and upload the image .if i select image only and press upload , it uploads image and dont check for empty fields.please if you could check it on your compilers.

<?php 
//session 
session_start();
$errorPrint = '';
if(isset($_SESSION['form_upload']['errors']) && $_SESSION['form_upload']['errors'])
{
    $errorPrint = $_SESSION['form_upload']['errors'];
    unset($_SESSION['form_upload']['errors']);
}
echo implode("<br />",$errorPrint);
 ?>



<!DOCTYPE HTML> 
<html>
<head>
  <title>Upload Image form</title>
</head>
<body> 

<form action="formhandler.php" method="post" enctype="multipart/form-data">
 <br><br> 
Image Title:  <input type="text"    name="imagetitle"  ><br><br>
              <input type="hidden"  name="MAX_FILE_SIZE" value="2000000">
              <input type="file"    name="userfile"  id="userfile" ><br><br>
Choose Date:  <input type="date"    name="pickdate" > <br><br>
<input id="button_1" type="radio" name="option"  value="button1" /><label for="button_1" >Button 1</label>
<input id="button_2" type="radio" name="option"  value="button2" /><label for="button_2" >Button 2</label><br><br>
<select name="list1"> 
      <option value="">Select Options</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option> 
      <option value="option3">Option 3</option>
</select>
<br><br>

<select name="list2"> 
      <option value="">Select Type</option>
      <option value="type1">Option 1</option>
      <option value="type2">Option 2</option> 
      <option value="type3">Option 3</option>
</select>
<br><br>
        <input name="upload" type="submit" class="box"  id="upload" value=" Upload " >
</form>


</body>

</html>
Member Avatar for diafol

All the form handling / validation will be in the formhandler.php page which you don't show.

This:

echo implode("<br />",$errorPrint);

Would be better something, like this...

<?php if($errorPrint) echo implode("<br />",$errorPrint);?>
<form action="formhandler.php" method="post" enctype="multipart/form-data">

Diafol plz if you could verify my code on your side ,if its working properly and give me your code here. I am relatively new to this stuff , I am totally lost now.:(

Member Avatar for diafol

Sorry it took so long. OK, I didn't realise that you were a beginner, so I hope the following code is adequate. Please feel free to ask questions. I tested it as far as I could without creating a DB. All the errors worked!

UPLOAD.PHP
<?php 
//essential for passing session data between pages
session_start();

//initialize variables with default values blank
$errorPrint = '';   
$loadedPrint = '';

$description='';
$date ='';

//check to see if formhandler.php has got anything to say - it
//creates and fills the $_SESSION['form_upload'] variable
//so if it exists and isn't empty, then we've just been sent 
//here from formhandler.php - i.e. the form was submitted
//So, the 'if' code below shouldn't run when you simply load
//the page
if(isset($_SESSION['form_upload']) && $_SESSION['form_upload'])
{
    //If there are any errors, passed as an array, then let's 
    //make a nice bullet list of them
    //Also replace input values if errors
    if(isset($_SESSION['form_upload']['errors']) && !empty($_SESSION['form_upload']['errors']))
    { 
        $errorPrint = '<ul class="errors"><li>' . 
            implode('</li><li>', $_SESSION['form_upload']['errors']) . '</li></ul>';
        if(isset($_SESSION['form_upload']['saved_data']['description']))
            $description =  $_SESSION['form_upload']['saved_data']['description'];
        if(isset($_SESSION['form_upload']['saved_data']['date']))
            $date =  $_SESSION['form_upload']['saved_data']['date'];    
    }
    //If the upload etc was successful, then pass the info to
    //the $loadedPrint variable
    if(isset($_SESSION['form_upload']['loaded']) && $_SESSION['form_upload']['loaded']) 
        $loadedPrint = $_SESSION['form_upload']['loaded'];



    //Finally, we need to unset (kill off) the session variable 
    //from the form handler, otherwise we'll get the same error 
    //or loaded messages whenever we simply load the page without
    //form submit    
    unset($_SESSION['form_upload']);
}

?>
<!DOCTYPE HTML> 
<html>
<head>
  <title>Upload Image form</title>
</head>
<body> 
<!-- I won't comment on the form as it seems to have pretty much
 what you need, although radiobuttons usually have one item checked
 as default and you should let CSS deal with margins or block display
 as opposed to using <br /> for layout -->

<!-- you can use a div to hold any messages - it will be empty if
form is not submitted -->

<div id="messaging"><?php echo $errorPrint;   echo $loadedPrint;?></div>

<form method="post" action="formhandler.php" enctype="multipart/form-data">
    <br /><br /> 
    Image Title:  
    <input type="text" name="imagetitle" value="<?php echo $description;?>" >
    <br /><br />
    <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
    <input type="file" name="userfile"  id="userfile" ><br /><br />
    Choose Date:  
    <input type="date" name="pickdate" value="<?php echo $date;?>" >
    <br /><br />
    <input id="button_1" type="radio" name="option" value="button1" checked="checked" />
    <label for="button_1" >Button 1</label>
    <input id="button_2" type="radio" name="option" value="button2" />
    <label for="button_2" >Button 2</label>
    <br /><br />
    <select name="list1"> 
          <option value="">Select Options</option>
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option> 
          <option value="option3">Option 3</option>
    </select>
    <br /><br />
    <select name="list2"> 
          <option value="">Select Type</option>
          <option value="type1">Option 1</option>
          <option value="type2">Option 2</option> 
          <option value="type3">Option 3</option>
    </select>
    <br /><br />
    <input name="upload" type="submit" class="box"  id="upload" value="Upload" />
</form>
</body>
</html>
FORMHANDLER.PHP
<?php
session_start();
//Let's kill the session var it if it already exists for some reason
if(isset($_SESSION['form_upload'])) 
    unset($_SESSION['form_upload']);

//Initialize variables ready to accept data 
$errors = array();
$loaded = '';
$savedData = array();

//This handy function from 
//http://www.php.net/manual/en/features.file-upload.php#88591
function display_filesize($filesize){

    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('bytes','KB','MB');

    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    } 
    return round($filesize,2).' '.$prefix[$step];
    } else {
        return 'NaN';
    }  
}

if (isset($_POST['upload']))
{
//Now get your other fields and trim off any spaces etc
    $description = trim($_POST['imagetitle']);
    $date = trim($_POST['pickdate']);

    //if the vars are empty ('') - then this is a problem if
    //they are required fields 
    if(!$description)
    {
        $errors[] = "A title for the image is required.";
    }else{
        $savedData['description'] = $description;   
    }
    if(!$date)
    {
        $errors[] = "A valid date is required.";
    }else{
        $savedData['date'] = $date; 
    }
}

//OK, if form is posted, let's do some processing :)
if (isset($_POST['upload']) && !$_FILES['userfile']['error'])
{
    //Our filters
    $allowed_filetypes = array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif'
    );

    //Useful... 
    $filename = $_FILES['userfile']['name'];
    $tmpfile = $_FILES['userfile']['tmp_name'];
    $filesize = $_FILES['userfile']['size'];


    $max_filesize = 1445760;


    //Test for the file type via a MIME TYPE test - NEVER a raw extension
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search($finfo->file($tmpfile), $allowed_filetypes, true))
    {
        $errors[] = 
            "The file format that you tried to upload is not allowed. We only accept: " . 
                implode(', ', array_keys($allowed_filetypes));
    }

    //Test for file size - although the file has already
    //been uploaded!! No matter, at least it won't be saved
    //as a retrievable image and thus suck all the energy
    //out of your site
    if($filesize > $max_filesize)
    {
        $errors[] = 
            "The image that you tried to upload (" . display_filesize($filesize) .
            ") was too big. The limit is " . display_filesize($max_filesize) . ".";
    }

    //Only proceed if there are no errors
    if(!$errors)
    {
        //Get the contents of the file to insert into DB
        $content = file_get_contents($tmpfile);

        //Set up an array of parameters to insert into the SQL
        $paramArray = array($filename,$filesize,$ext,$content,$date,$description);

        //Create the SQL prepared query with ? for placeholders
        $sql = "INSERT INTO `upload` (`name`, `size`, `type`, `content` ,`date` ,`description` ) VALUES (?, ?, ?, ?, ?, ?)";

        //Connect to DB via PDO - this can be done in an include file like your opendb.php file
        $db = new PDO("mysql:host=localhost;dbname=daniweb","root","");

        //OK now for the good stuff, prepare and execute!
        $stmt = $db->prepare($sql);
        $stmt->execute($paramArray);
        $count = $stmt->rowCount(); 
        if(!$count)
        {
            $errors[] = "The data could not be saved to the Database.";
        }else{

            $loaded = '<h2>Your Input:</h2>';
            $loaded .= "<p>Title = $description</p>";
            $loaded .= "<p>Filename = $filename</p>";
            $loaded .= "<p>File size = $filesize</p>";
            $loaded .= "<p>Date = $date</p>";
        }
    }
}else{
    $errors[] = "Nothing seems to have been uploaded";  
}

if(isset($errors) && $errors) $_SESSION['form_upload']['errors'] = $errors;
if(isset($loaded) && $loaded) $_SESSION['form_upload']['loaded'] = $loaded;
if(isset($savedData) && $savedData) $_SESSION['form_upload']['saved_data'] = $savedData;
header('Location: untitled.php');
exit;
?>

Sorry, it's a bit late and I think I may have over-egged it a bit. But anyway, have a play with it.

Error

Fatal error: Class 'finfo' not found in \upload_new\formhandler.php on line 60

Solution to above error:

http://goo.gl/KmjAqg

Finally its working now.

diafol thnx so much <3 for the hard work .I got everything :).

WoW this explanation and programming <3. Love it. I know whats happening in code :D as long its working i am happy :D. You are great teacher.

Member Avatar for diafol

Kind words :)
The important thing with programming is that when you learn something new, you then go on to develop it further or use it in a different context. That way you begin to see "patterns" and ways to approach common problems become easier. Good luck with it.

Thanks for the guidance and motivation.I started doing php and mysql like 2 weeks ago.It feels good to be around Pro's.I will keep working on it and will modify it further to see how things go and add some stuff later into it :p.I got most of the things :). Php is addiction :D.

Member Avatar for diafol

Php is addiction :D.

You're right there!

BTW - just a thought - storing images as blob data can be a real pain. A common alternative is to upload the image to an 'upload' directory and just store the filename in the db table. Then when you retrieve it:

SELECT ..., `filename` FROM table

Retrieve data in $row variable

<img src="upload/<?php echo $row['filename'];?>" />

Easy. You don't have to mess with base64 and all that nonsense :)

Easy doesn't always mean 'best' though. If you're using "data-uri" have a read of this:

http://en.wikipedia.org/wiki/Data_URI_scheme

Ya i opened up an image in mysql db and image was not showing up properly instead it had some strange values and characters like in your link.ok i know post variable has alot of info about the file.
$content = file_get_contents($tmpfile);
this line has my image right ?
now how will i save this image to upload/ ?. please help me.

Member Avatar for diafol

You want to save the image to a folder and just the filename to db instead of saving the image itself to the db?

If so, you need to move the uploaded image:

move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/'.$newname);

Search for move_uploaded_file()

yes file names in database and file to folder,

please can you tell me what that $newname for , will have to save image with new name or what ?

Member Avatar for diafol

Up to you what you name the file to be stored, usually we use this...

$newname = $_FILES['userfile']['name'];

A problem with this is that duplicate files can be overwritten. So you could check with a if(file_exists(...)) first.

Or you could use your own unique name ...something like...

$newname = strtolower($safe_username) . '_' . date() . '.' .$ext;

Which could give you a unique name like...

diafol_1398862852.jpg

Usernames are not always the best things to include in a filename though as they can contain illegal characters. A fix could be to 'slugify', but that may lead to username collision (users diafol#666 and diafol%666 would end up as the same: diafol666). However filenames should still be unique due to the 'date' part. The chances of users with identical 'slugs' posting an image at the exact same time is pretty remote.

An alternative could be to store a hash:

$newname = md5(time()) . '.' . $ext;

e.g.

fcf311992bd59dacc6875fe65d1ff629.jpg    

$newname = strtolower($safe_username) . '_' . date() . '.' .$ext;
this is pretty legit . i will go with this one, seems cool :p.Should i make folder one folder for all images or something else, as upload/ folder will be quite big after month or so. i dont know what hosting providers say about it.

I have saved that to upload directoy but its giving me this error.

i have added this code to save path and new file name:

$upload_path = 'uploads/';
$newname = $_FILES['images']['name'];

if there are no error they moved the data to upload folder.and removed content column and value key from insert.

$paramArray = array($filename,$filesize,$ext,$date,$description);
 if(!is_writable($upload_path))
    die('You cannot upload to the specified directory, please CHMOD it to 777.');
 $move = move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$newname);
    if($move)

Error === >>> The data could not be saved to the Database.

Form Handler.php

<?php
session_start();
//Let's kill the session var it if it already exists for some reason
if(isset($_SESSION['form_upload'])) 
    unset($_SESSION['form_upload']);
//Initialize variables ready to accept data 
$errors = array();
$loaded = '';
$savedData = array();
//This handy function from 
//http://www.php.net/manual/en/features.file-upload.php#88591
function display_filesize($filesize){
    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('bytes','KB','MB');
    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    } 
    return round($filesize,2).' '.$prefix[$step];
    } else {
        return 'NaN';
    }  
}
if (isset($_POST['upload']))
{
//Now get your other fields and trim off any spaces etc
    $description = trim($_POST['imagetitle']);
    $date = trim($_POST['pickdate']);
    //if the vars are empty ('') - then this is a problem if
    //they are required fields 
    if(!$description)
    {
        $errors[] = "A title for the image is required.";
    }else{
        $savedData['description'] = $description;   
    }
    if(!$date)
    {
        $errors[] = "A valid date is required.";
    }else{
        $savedData['date'] = $date; 
    }
}
//OK, if form is posted, let's do some processing :)
if (isset($_POST['upload']) && !$_FILES['image']['error'])
{
    //Our filters
    $allowed_filetypes = array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif'
    );
    //Useful... 
    $filename = $_FILES['image']['name'];
    $tmpfile = $_FILES['image']['tmp_name'];
    $filesize = $_FILES['image']['size'];
    $max_filesize = 1445760;
    **$upload_path = 'uploads/';
    $newname = $_FILES['images']['name'];**

    //Test for the file type via a MIME TYPE test - NEVER a raw extension
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search($finfo->file($tmpfile), $allowed_filetypes, true))
    {
        $errors[] = 
            "The file format that you tried to upload is not allowed. We only accept: " . 
                implode(', ', array_keys($allowed_filetypes));
    }
    //Test for file size - although the file has already
    //been uploaded!! No matter, at least it won't be saved
    //as a retrievable image and thus suck all the energy
    //out of your site
    if($filesize > $max_filesize)
    {
        $errors[] = 
            "The image that you tried to upload (" . display_filesize($filesize) .
            ") was too big. The limit is " . display_filesize($max_filesize) . ".";
    }
    //Only proceed if there are no errors
    if(!$errors)
    {
        //Get the contents of the file to insert into DB
        //$content = file_get_contents($tmpfile);
        //Set up an array of parameters to insert into the SQL
        $paramArray = array($filename,$filesize,$ext,$date,$description);
       ** if(!is_writable($upload_path))
             die('You cannot upload to the specified directory, please CHMOD it to 777.');
                    $move = move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$newname);

                  if($move)
        //Create the SQL prepared query with ? for placeholders
        $sql = "INSERT INTO `upload` (`name`, `size`, `type`,`date` ,`description` ) VALUES (?, ?, ?, ?, ?)";**
        //Connect to DB via PDO - this can be done in an include file like your opendb.php file
        $db = new PDO("mysql:host=localhost;dbname=eployee","root","");
        //OK now for the good stuff, prepare and execute!
        $stmt = $db->prepare($sql);
        $stmt->execute($paramArray);
        $count = $stmt->rowCount(); 
        if(!$count)
        {
            $errors[] = "The data could not be saved to the Database.";
        }else{
            $loaded = '<h2>Your Input:</h2>';
            $loaded .= "<p>Title = $description</p>";
            $loaded .= "<p>Filename = $filename</p>";
            $loaded .= "<p>File size = $filesize</p>";
            $loaded .= "<p>Date = $date</p>";
           ** $loaded .= "<p>Image <img src='uploads/'.$newname''> </p>";** // image display 

        }
    }
}else{
    $errors[] = "Nothing seems to have been uploaded";  
}
if(isset($errors) && $errors) $_SESSION['form_upload']['errors'] = $errors;
if(isset($loaded) && $loaded) $_SESSION['form_upload']['loaded'] = $loaded;
if(isset($savedData) && $savedData) $_SESSION['form_upload']['saved_data'] = $savedData;
header('Location: upload.php');
exit;
?>
Member Avatar for diafol
$db = new PDO("mysql:host=localhost;dbname=eployee","root","");

Should that be 'employee'?

its eployee :d , i mistakenly created eployee now using eployee as name :p

upload.php

its same except just the name from userfile to image in input file tag.

ills the $_SESSION['form_upload'] variable
//so if it exists and isn't empty, then we've just been sent 
//here from formhandler.php - i.e. the form was submitted
//So, the 'if' code below shouldn't run when you simply load
//the page
if(isset($_SESSION['form_upload']) && $_SESSION['form_upload'])
{
    //If there are any errors, passed as an array, then let's 
    //make a nice bullet list of them
    //Also replace input values if errors
    if(isset($_SESSION['form_upload']['errors']) && !empty($_SESSION['form_upload']['errors']))
    { 
        $errorPrint = '<ul class="errors"><li>' . 
            implode('</li><li>', $_SESSION['form_upload']['errors']) . '</li></ul>';
        if(isset($_SESSION['form_upload']['saved_data']['description']))
            $description =  $_SESSION['form_upload']['saved_data']['description'];
        if(isset($_SESSION['form_upload']['saved_data']['date']))
            $date =  $_SESSION['form_upload']['saved_data']['date'];    
    }
    //If the upload etc was successful, then pass the info to
    //the $loadedPrint variable
    if(isset($_SESSION['form_upload']['loaded']) && $_SESSION['form_upload']['loaded']) 
        $loadedPrint = $_SESSION['form_upload']['loaded'];
    //Finally, we need to unset (kill off) the session variable 
    //from the form handler, otherwise we'll get the same error 
    //or loaded messages whenever we simply load the page without
    //form submit    
    unset($_SESSION['form_upload']);
}
?>
<!DOCTYPE HTML> 
<html>
<head>
  <title>Upload Image form</title>
</head>
<body> 
<!-- I won't comment on the form as it seems to have pretty much
 what you need, although radiobuttons usually have one item checked
 as default and you should let CSS deal with margins or block display
 as opposed to using <br /> for layout -->
<!-- you can use a div to hold any messages - it will be empty if
form is not submitted -->
<div id="messaging"><?php echo $errorPrint;   echo $loadedPrint;?></div>
<form method="post" action="formhandler.php" enctype="multipart/form-data">
    <br /><br /> 
    Image Title:  
    <input type="text" name="imagetitle" value="<?php echo $description;?>" >
    <br /><br />
    <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
    <input type="file" name="image"  id="userfile" ><br /><br />
    Choose Date:  
    <input type="date" name="pickdate" value="<?php echo $date;?>" >
    <br /><br />
    <input id="button_1" type="radio" name="option" value="button1" checked="checked" />
    <label for="button_1" >Button 1</label>
    <input id="button_2" type="radio" name="option" value="button2" />
    <label for="button_2" >Button 2</label>
    <br /><br />
    <select name="list1"> 
          <option value="">Select Options</option>
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option> 
          <option value="option3">Option 3</option>
    </select>
    <br /><br />
    <select name="list2"> 
          <option value="">Select Type</option>
          <option value="type1">Option 1</option>
          <option value="type2">Option 2</option> 
          <option value="type3">Option 3</option>
    </select>
    <br /><br />
    <input name="upload" type="submit" class="box"  id="upload" value="Upload" />
</form>
</body>
</html>
Member Avatar for diafol

Well, there definitely seems to be a problem with the database saving the record.

Ok time for some surgery!

Where you have this line:

$sql = "INSERT INTO `upload` (`name`, `size`, `type`,`date` ,`description` ) VALUES (?, ?, ?, ?, ?)";**

Directly below it, enter this code:

list($name, $size,$type,$date,$description) = $paramArray;
$sql = "INSERT INTO `upload` (`name`, `size`, `type`,`date` ,`description` ) VALUES ('$name', $size, '$type', '$date', '$description')"
echo $sql;
exit;

Look at the query to see if it's oK. Just a warning - the input data is not escaped, so ensure there are no quotes in the data! Now copy the text from the screen and run it in the SQL window of phpMyAdmin. See if there are any errors.

I ran code in phpmyadmin its running fine there .

after adding code to my formhander.php

Now code looks like this :

if($move)
            //Create the SQL prepared query with ? for placeholders
            $sql = "INSERT INTO `upload` (`name`, `size`, `type`,`date` ,`description` ) VALUES (?, ?, ?, ?, ?)";
            list($name, $size,$type,$date,$description) = $paramArray;
    $sql = "INSERT INTO `upload` (`name`, `size`, `type`,`date` ,`description` ) VALUES ('$name', $size, '$type', '$date', '$description')";
    echo $sql;
    exit;

getting these warnings.

  1. Notice: Undefined index: images in \upload_new\formhandler.php on line 60
    2.Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in \upload_new\formhandler.php on line 89
    3.Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpB9E1.tmp' to 'uploads/' in \upload_new\formhandler.php on line 89

file is neither upload to db nor to uploads/ folder, but it has uploaded succes , where did it do ? LOL

Member Avatar for diafol

OK, this works for me...

<?php
session_start();
//Let's kill the session var it if it already exists for some reason
if(isset($_SESSION['form_upload'])) 
    unset($_SESSION['form_upload']);

//Initialize variables ready to accept data 
$errors = array();
$loaded = '';
$savedData = array();

//Use this hardcoded username for now - ideally this would
//come from your SESSION username variable when user logged
//on. In addition it should be slugified or urlencoded to
//ensure a valid filename

$username = 'diafol';
$uploadDirectory = 'upload/';

//This handy function from 
//http://www.php.net/manual/en/features.file-upload.php#88591
function display_filesize($filesize){

    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('bytes','KB','MB');

    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    } 
    return round($filesize,2).' '.$prefix[$step];
    } else {
        return 'NaN';
    }  
}

if (isset($_POST['upload']))
{
//Now get your other fields and trim off any spaces etc
    $description = trim($_POST['imagetitle']);
    $date = trim($_POST['pickdate']);

    //if the vars are empty ('') - then this is a problem if
    //they are required fields 
    if(!$description)
    {
        $errors[] = "A title for the image is required.";
    }else{
        $savedData['description'] = $description;   
    }
    if(!$date)
    {
        $errors[] = "A valid date is required.";
    }else{
        $savedData['date'] = $date; 
    }
}

//OK, if form is posted, let's do some processing :)
if (isset($_POST['upload']) && !$_FILES['userfile']['error'])
{
    //Our filters
    $allowed_filetypes = array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif'
    );

    //Useful... 

    $tmpfile = $_FILES['userfile']['tmp_name'];
    $filesize = $_FILES['userfile']['size'];

    $max_filesize = 1445760;

    //Test for the file type via a MIME TYPE test - NEVER a raw extension
    //Create the custom filename to store in the 'upload/' directory

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search($finfo->file($tmpfile), $allowed_filetypes, true))
    {
        $errors[] = 
            "The file format that you tried to upload is not allowed. We only accept: " . 
                implode(', ', array_keys($allowed_filetypes));
    }else{
        $filename = $username . '_' . date('U') . '.' . $ext;
    }

    //Test for file size - although the file has already
    //been uploaded!! No matter, at least it won't be saved
    //as a retrievable image and thus suck all the energy
    //out of your site
    if($filesize > $max_filesize)
    {
        $errors[] = 
            "The image that you tried to upload (" . display_filesize($filesize) .
            ") was too big. The limit is " . display_filesize($max_filesize) . ".";
    }

    //Only proceed if there are no errors
    if(!$errors)
    {
        //Copy the file to the upload directory...
        if (file_exists("upload/" . $filename)) {
            $errors[] = "The file: $filename already exists. Cannot overwrite.";
        } else {
            if(!move_uploaded_file($tmpfile, $uploadDirectory . $filename))
            {
                $errors[] = "The file: $filename could not be uploaded at this time.";
            }else{

                //Set up an array of parameters to insert into the SQL
                $paramArray = array($filename,$filesize,$ext,$date,$description);

                //Create the SQL prepared query with ? for placeholders
                $sql = "INSERT INTO `upload` (`name`, `size`, `type`, `date` ,`description` ) VALUES (?, ?, ?, ?, ?)";

                //Connect to DB via PDO - this can be done in an include file like your opendb.php file
                $db = new PDO("mysql:host=localhost;dbname=daniweb","root","");

                //OK now for the good stuff, prepare and execute!
                $stmt = $db->prepare($sql);

                $stmt->execute($paramArray);
                $count = $stmt->rowCount(); 
                if(!$count)
                {
                    $errors[] = "The data could not be saved to the Database.";
                }else{

                    $loaded = '<h2>Your Input:</h2>';
                    $loaded .= "<p>Title = $description</p>";
                    $loaded .= "<p>Filename = $filename</p>";
                    $loaded .= "<p>File size = $filesize</p>";
                    $loaded .= "<p>Date = $date</p>";
                }
            }
        }
    }
}else{
    $errors[] = "Nothing seems to have been uploaded";  
}

if(isset($errors) && $errors) $_SESSION['form_upload']['errors'] = $errors;
if(isset($loaded) && $loaded) $_SESSION['form_upload']['loaded'] = $loaded;
if(isset($savedData) && $savedData) $_SESSION['form_upload']['saved_data'] = $savedData;
header('Location: upload.php');
exit;
?>

There's quite a few nested conditionals here - not great, but prevents db manipulation if upload fails.

Thnx so much diafol it worked this time. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.