Copy link to clipboard
Copied
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>
Copy link to clipboard
Copied
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.
Copy link to clipboard
Copied
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;
}
?>
Copy link to clipboard
Copied
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?
Copy link to clipboard
Copied
Horsemad Gilly wrote:
yes I am trying to store the filename,
I haven't tested this, but it should work in principle.
In the list of properties at the top of your Gp1_Upload class definition, add the following:
protected $_filenames = array();
Amend the processFile() method like this:
protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
$OK = $this->checkError($filename, $error);
if ($OK) {
// add current filename to array of names
$this->_filenames[] = $filename;
// end of new code
$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";
}
}
}
}
Also create a public method to retrieve the array of filenames:
public getFilenames() {
return $this->_filenames;
}
You can then use the getFilenames() method to retrieve an array of the names of uploaded files. Even if you upload only one file, getFilenames() will still return an array. Use a loop to extract the names.
Copy link to clipboard
Copied
Hi David
Thank you very much for your help. I had continued to work on the code and had worked out how to input the image path into the database but it was using the original filename, so when every it is changed it did not work. The code in my page at that point was the following,
<?php // 2. NEW USER REGISTRATION<br />
include_once ("includes/form_functions.inc.php");
$max = 100000;
$destination = 'uploads/';
// START FORM PROCESSING FOR A NEW REGISTRATION
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('org_name');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$required_numberfields = array('user_id');
$errors = array_merge($errors, check_number_fields($required_numberfields, $_POST));
$fields_with_lengths = array('org_name' => 36, 'org_website' => 100, 'org_contact' => 40, 'org_conemail' => 80, 'org_contel' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
/*Here I am using trim as well as ucwords, this function converts the first letter of each work into a capital letter, I am using this only on the
firstname and surname to ensure that the data is how I want it as it is going into the database, The better the data is preformated the better the data
swill be within the database.*/
$org_name = trim(strtolower(mysql_prep($_POST['org_name'])));
$org_website = trim(strtolower(mysql_prep($_POST['org_website'])));
$org_contact = trim(strtolower (mysql_prep($_POST['org_contact'])));
$org_conemail = trim(strtolower (mysql_prep($_POST['org_conemail'])));
$org_contel = strtolower (mysql_prep($_POST['org_contel']));
$userid = $_POST['user_id'];
$org_uploadcapt = $_POST['org_uploadcapt'];
$image = $_FILES['image'];
/*Here is the code that takes the variable captured from the input form and matches it up with the appropriate field in the database. An important point with insertion is that the variables are in the same order as the mysql field names, there will be an error if the number of variables does not match the number of field names. Note that there is no entry for the user id as this is an auto increment file within mysql and so is not needed to be entered*/
if ( empty($errors) ) {
$sql = "INSERT INTO organiser
(org_name, org_website, org_contact, org_conemail, org_contel, user_id, org_uploadurl, org_uploadcapt)
VALUES
('{$org_name}', '{$org_website}', '{$org_contact}', '{$org_conemail}', '{$org_contel}', '{$userid}', '{$destination}".$image['name']."', '{$org_uploadcapt}' )";
$result = mysql_query($sql, $connection);
if ($result) {
$message = "The organiser was successfully created.<br />";
} else {
$message = "I am sorry but the organiser could not be added.";
$message .= "<br />" . mysql_error();
}
} else {
/* this counts the number of errors and informs the user of how many fields were
incorrectly entered*/
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
} else { // Form has not been submitted.
$org_name = "";
$org_website = "";
$org_contact = "";
$org_conemail = "";
$org_contel = "";
$userid = "";
$org_uploadcapt = "";
}
//THE FOLLOWING CODE IS FOR THE UPLOADING OF IMAGES AND FILES
// set the max upload size in bytes
if (isset ($_POST ['submit']))
{
//define the path to the upload folder
// Use This On The Local Hosting Machine
//$destination = 'C:/upload_test/';
// Use This On The Live Server
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
?>
<title>Horse Events</title>
<?php include_once("includes/meta.inc.php");?>
<?php include_once("includes/cssfavgoogle.inc.php");?>
<link href="css/adminpanel.css" rel="stylesheet" type="text/css" />
<style>
input[type="number"] {
width:40px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="admincontent">
<form id="newvenue" action="neworganiser.php" method="post" enctype="multipart/form-data" >
<?php if (!empty ($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<?php if (!empty ($errors)) {display_errors($errors); } ?>
<?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>';
}
?>
<br />
<table id="neweventdisplay" cellpadding="5" border="0">
<tr>
<td></td>
<td><input type="hidden" name="user_id" value="<?php echo $url_userid ['user_id']; ?>" /></td>
</tr>
<tr>
<td> <span class="compuls">*</span></td>
<td>Organisers Name</td>
<td><input class="input80px" id="org_name" name="org_name" type="text" />
</td>
</tr>
<tr>
<td><span class="compuls">*</span></td>
<td>Their Website</td>
<td><input class="input80px" id="org_website" name="org_website" type="text" /></td>
</tr>
<tr>
<td><span class="compuls">*</span></td>
<td>Organisers Contact</td>
<td><input id="org_contact" name="org_contact" type="text" />eg: Mrs Jean Kelly</td>
</tr>
<tr>
<td><span class="compuls">*</span></td>
<td>Contact Email</td>
<td><input class="input80px" id="org_conemail" name="org_conemail" type="text" />
</td>
</tr>
<tr>
<td><span class="compuls">*</span></td>
<td>Contact Tel No.</td>
<td><input id="org_contel" name="org_contel" 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="Add Your Organiser"></td>
</tr>
<tr>
<td class="heading"> </td>
<td></td>
</tr>
</table>
<a class="delete" href="controlpanel.php">Cancel</a>
</form>
</div>
I have added the code you kindly forwarded but am getting an error, I am still trying to learn the basics of php and am unsure of what to do next, my php Upload.php now looks like
<?php
class Gp1_Upload{
protected $_uploaded = array();
protected $_destination;
protected $_max = 100000;
protected $_messages = array();
protected $_permitted = array('image/gif',
'image/jpeg',
'image/pjpeg',
'image/png');
protected $_renamed = false;
protected $_filenames = array();
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 getMaxSize() {
return number_format($this->_max/100000, 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";
}
}
}
}
public getFilenames() {
return $this->_filenames;
}
}
?>
The error is Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE.
I have not worked with oop before and have only very briefly looked at the principle was on my foundation degree.
Copy link to clipboard
Copied
The error is here:
public getFilenames() {
return $this->_filenames;
}
It should be:
public function getFilenames() {
return $this->_filenames;
}
That's the danger of writing code directly in a forum without testing it.
Copy link to clipboard
Copied
Hi David
Thank you so much for that, it works fab.
Thanks again, I find it so difficult to source good support and help whilst
learning, so I really appreciate your time.
Regards
Gilly
Copy link to clipboard
Copied
I try to help out when I can, but I've been very busy of late, so cannot devote as much time to the forums as I used to. I'll mark this thread as assumed answered.