Skip to main content
Known Participant
June 10, 2011
Question

Storing Uploaded Image Path into Mysql

  • June 10, 2011
  • 1 reply
  • 2776 views

Hi I am developing a cms and am using the code David gives in his book PHP Solutions,  everything works fine but I can't work out how to extract the uploaded path so that it is stored in my table.

Help would be really appreciated, I am making good progress in learning the php especially with David's books but am still struggling when it comes to having to customized the code.

The code for the upload.php is as follows,

<?php
class Gp1_Upload{
   
  protected $_uploaded = array();
  protected $_destination;
  protected $_max = 51200;
  protected $_messages = array();
  protected $_permitted = array('image/gif',
                                'image/jpeg',
                                'image/pjpeg',
                                'image/png');
  protected $_renamed = false;

  public function __construct($path) {
    if (!is_dir($path) || !is_writable($path)) {
      throw new Exception("$path must be a valid, writable directory.");
    }
    $this->_destination = $path;
    $this->_uploaded = $_FILES;
  }
 
  public function getuploadpath (){
     
  }

  public function getMaxSize() {
    return number_format($this->_max/1024, 1) . 'kB';
  }

  public function setMaxSize($num) {
    if (!is_numeric($num)) {
      throw new Exception("Maximum size must be a number.");
    }
    $this->_max = (int) $num;
  }

  public function move($overwrite = false) {
    $field = current($this->_uploaded);
    if (is_array($field['name'])) {
      foreach ($field['name'] as $number => $filename) {
        // process multiple upload
        $this->_renamed = false;
        $this->processFile($filename, $field['error'][$number], $field['size'][$number], $field['type'][$number], $field['tmp_name'][$number], $overwrite);   
      }
    } else {
      $this->processFile($field['name'], $field['error'], $field['size'], $field['type'], $field['tmp_name'], $overwrite);
    }
  }

  public function getMessages() {
    return $this->_messages;
  }
 
  protected function checkError($filename, $error) {
    switch ($error) {
      case 0:
        return true;
      case 1:
      case 2:
        $this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
        return true;
      case 3:
        $this->_messages[] = "Error uploading $filename. Please try again.";
        return false;
      case 4:
        $this->_messages[] = 'No file selected.';
        return false;
      default:
        $this->_messages[] = "System error uploading $filename. Contact webmaster.";
        return false;
    }
  }

  protected function checkSize($filename, $size) {
    if ($size == 0) {
      return false;
    } elseif ($size > $this->_max) {
      $this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
      return false;
    } else {
      return true;
    }
  }
 
  protected function checkType($filename, $type) {
    if (empty($type)) {
      return false;
    } elseif (!in_array($type, $this->_permitted)) {
      $this->_messages[] = "$filename is not a permitted type of file.";
      return false;
    } else {
      return true;
    }
  }

  public function addPermittedTypes($types) {
    $types = (array) $types;
    $this->isValidMime($types);
    $this->_permitted = array_merge($this->_permitted, $types);
  }

  protected function isValidMime($types) {
    $alsoValid = array('image/tiff',
                       'application/pdf',
                       'text/plain',
                       'text/rtf');
      $valid = array_merge($this->_permitted, $alsoValid);
    foreach ($types as $type) {
      if (!in_array($type, $valid)) {
        throw new Exception("$type is not a permitted MIME type");
      }
    }
  }

  protected function checkName($name, $overwrite) {
    $nospaces = str_replace(' ', '_', $name);
    if ($nospaces != $name) {
      $this->_renamed = true;
    }
    if (!$overwrite) {
      $existing = scandir($this->_destination);
      if (in_array($nospaces, $existing)) {
        $dot = strrpos($nospaces, '.');
        if ($dot) {
          $base = substr($nospaces, 0, $dot);
          $extension = substr($nospaces, $dot);
        } else {
          $base = $nospaces;
          $extension = '';
        }
        $i = 1;
        do {
          $nospaces = $base . '_' . $i++ . $extension;
        } while (in_array($nospaces, $existing));
        $this->_renamed = true;
      }
    }
    return $nospaces;
  }

  protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
    $OK = $this->checkError($filename, $error);
    if ($OK) {
      $sizeOK = $this->checkSize($filename, $size);
      $typeOK = $this->checkType($filename, $type);
      if ($sizeOK && $typeOK) {
        $name = $this->checkName($filename, $overwrite);
        $success = move_uploaded_file($tmp_name, $this->_destination . $name);
        if ($success) {
            $message = "$filename uploaded successfully";
            if ($this->_renamed) {
              $message .= " and renamed $name";
            }
            $this->_messages[] = $message;
        } else {
          $this->_messages[] = "Could not upload $filename";
        }
      }
    }
  }


}
?>

The code for my form page is this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
//THE FOLLOWING CODE IS FOR THE UPLOADING OF IMAGES AND FILES
// set the max upload size in bytes
$max = 51200;
if (isset ($_POST ['submit']))
            {

            //define the path to the upload folder
            $destination = 'uploads/';
            require_once('classes/Upload.php');
            try {
           
                $upload = new Gp1_Upload($destination);
                $upload->setMaxSize($max);
                $upload->move();
                $result = $upload->getMessages();
            } catch (Exception $e) {
                echo $e->getMessage();
    }
    }
// END OF UPLOADING OF IMAGES AND FILES
?>
<form id="newvenue" action="" method="post" enctype="multipart/form-data" >
      <?php
           // THIS CODE DISPLAYS ERROR MESSAGES FOR THE FILE UPLOADS
          if (isset($result)){
          echo '<ul>';
          foreach ($result as $message){
              echo "<li>$message</li>";
          }
          echo '</ul>';
          }
       ?>
  <table id="neweventdisplay" cellpadding="5"  border="0">
    <tr>
  <td></td>
  <td><input type="hidden" name="user_id"  value="" /></td>
  </tr>
  <tr>
  <td></td>
    <td>Organisers Name</td>
    <td><input class="input80px" id="org_name" name="org_name" type="text" /> </td>
  </tr>
  <tr>
  <td></td>
  <td><label for="image">Upload image:</label></td>
  <td><p>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input type="file" name="image" id="image" />
</p></td>
</tr>
  <tr>
  <td></td>
  <td>Details about your upload</td>
  <td><input class="input80px" id="org_uploadcapt" name="org_uploadcapt" type="text"  /></td>
</tr>
  <tr>
  <td></td>
  <td><input type="submit" name="submit" id="submit" value="upload"></td>
  </tr>
  <tr>
  <td class="heading"> </td>
  <td></td>
  </tr>
</table>
</form>
<prep>
<?php
if (isset ($_POST ['submit'])){
    print_r($_FILES);}
    ?>
    </prep>
</body>
</html>

This topic has been closed for replies.

1 reply

Lon_Winters
Inspiring
June 12, 2011

Does it store the uploaded filenames? If so, that is the correct way to do it. When you go to access that file, from a link or whatever, that's where you enter the path as it can change depending on where the page is.

Known Participant
June 12, 2011

yes I am trying to store the filename,  I am trying to work out where in my current code that I add in the necessary.  The following code is just a basic upload form and script which works but I want to use the code previously give.

<?php
// Start a session for displaying any form errors
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Dream in code tutorial</title>

    </head>

    <body>   
        <div>
                <?php
                if (isset($_SESSION['error']))
                {
                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
                    unset($_SESSION['error']);
                }
                ?>
                <form action="upload.php" method="post" enctype="multipart/form-data">
                <p>
                    <label>First Name</label>
                    <input type="text" name="fname" /><br />

                    <label>Last Name</label>
                    <input type="text" name="lname" /><br />

                    <label>Upload Image</label>
                    <input type="file" name="image" /><br />
                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
                    <input type="submit" id="submit" value="Upload" />
                </p>
                </form>
        </div>
    </body>
</html>

PHP SCRIPT SAVED AS  UPLOAD.PHP

<?php
// Start a session for error reporting
session_start();

// Call our connection file
require_once("includes/connection.inc.php");

mysql_select_db ($db_name) or die ("Unable to select dtabase: " . mysql_error());


// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
    // This is an array that holds all the valid image MIME types
    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");

    if (in_array($file['type'], $valid_types))
        return 1;
    return 0;
}

// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
    echo "<pre>";
    print_r($array);
    echo "</pre>";
}

// Set some constants

// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";

// Get our POSTed variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$image = $_FILES['image'];

// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$image['name'] = mysql_real_escape_string($image['name']);

// Build our target path full string.  This is where the file will be moved do
// i.e.  images/picture.jpg
$TARGET_PATH .= $image['name'];

// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name'] == "" )
{
    $_SESSION['error'] = "All fields are required";
    header("Location: index.php");
    exit;
}

// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
    header("Location: index.php");
    exit;
}

// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
    $_SESSION['error'] = "A file with that name already exists";
    header("Location: index.php");
    exit;
}

// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
    // NOTE: This is where a lot of people make mistakes.
    // We are *not* putting the image into the database; we are putting a reference to the file's location on the server
    $sql = "insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image['name'] . "')";
    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
    header("Location: images.php");
    exit;
}
else
{
    // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
    // Make sure you chmod the directory to be writeable
    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";
    header("Location: index.php");
    exit;
}
?>

Lon_Winters
Inspiring
June 12, 2011

The typical way most file upload scriptsmwork is you use a file field which allows the user to browse for the file and select it. When the form is submitted, it uploads the file to a predetermined location. If you also include an insert or update record behavior, you simply include that field as any other field. The upload scrip should be able to just parse the filenames itself as the value for the field, not the fll path to where the file was stored on the users computer. How much of this exactly do you have working at this point - does the file get uploaded? Are you able to store the other form fields without problem?