473,574 Members | 9,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP Upload ! Storing Image data in MySQL

Hello there,

I am at my wit's end ! I have used the following script succesfully to
upload an image to my web space. But what I really want to be able to do is
to update an existing record in a table in MySQL with the path & filename to
the image.

I have successfully uploaded and performed an update query on the database,
but the problem I have is I cannot retain the primary key field in a
variable which is then used in a SQL update statement to ensure that I
update the correct field in the MySQL table. I have not included the code
for the SQL update.

To summarise I guess what I am trying to do is create a page for updating
produuct data on an ecommerce site. So the Promary key is the Product Number
and I need to store the image filename in the products table.

Any Help will be gratefuly received. I am sure this is a very very simple
question to an experienced PHP programmer, I just cant get my head around
it all at the minute !

Thanks in advance Dave Griffin.

Script:
<html>
<head><title>Up load</title></head>
<body>

<?php

require("fileup load-class.php");

#--------------------------------#
# Variables
#--------------------------------#

// The path to the directory where you want the
// uploaded files to be saved. This MUST end with a
// trailing slash unless you use $path = ""; to
// upload to the current directory. Whatever directory
// you choose, please chmod 777 that directory.

$path = "uploads/";

// The name of the file field in your form.

$upload_file_na me = "userfile";

// ACCEPT mode - if you only want to accept
// a certain type of file.
// possible file types that PHP recognizes includes:
//
// OPTIONS INCLUDE:
// text/plain
// image/gif
// image/jpeg
// image/png

// Accept ONLY gifs's
#$acceptable_fi le_types = "image/gifs";

// Accept GIF and JPEG files
$acceptable_fil e_types = "image/gif|image/jpeg|image/pjpeg";

// Accept ALL files
#$acceptable_fi le_types = "";

// If no extension is supplied, and the browser or PHP
// can not figure out what type of file it is, you can
// add a default extension - like ".jpg" or ".txt"

$default_extens ion = "";

// MODE: if your are attempting to upload
// a file with the same name as another file in the
// $path directory
//
// OPTIONS:
// 1 = overwrite mode
// 2 = create new with incremental extention
// 3 = do nothing if exists, highest protection

$mode = 2;
#--------------------------------#
# PHP
#--------------------------------#
if (isset($_REQUES T['submitted'])) {
/*
A simpler way of handling the submitted upload form
might look like this:

$my_uploader = new uploader('en'); // errors in English

$my_uploader->max_filesize(3 0000);
$my_uploader->max_image_size (800, 800);
$my_uploader->upload('userfi le', 'image/gif', '.gif');
$my_uploader->save_file('upl oads/', 2);

if ($my_uploader->error) {
print($my_uploa der->error . "<br><br>\n ");
} else {
print("Thanks for uploading " . $my_uploader->file['name'] .
"<br><br>\n ");
}
*/

// Create a new instance of the class
$my_uploader = new uploader($_POST['language']); // for error messages in
french, try: uploader('fr');

// OPTIONAL: set the max filesize of uploadable files in bytes
$my_uploader->max_filesize(1 5000);

// OPTIONAL: if you're uploading images, you can set the max pixel
dimensions
$my_uploader->max_image_size (800, 800); // max_image_size( $width, $height)

// UPLOAD the file
if ($my_uploader->upload($upload _file_name, $acceptable_fil e_types,
$default_extens ion)) {
$my_uploader->save_file($pat h, $mode);
}

if ($my_uploader->error) {
echo $my_uploader->error . "<br><br>\n ";

} else {
// Successful upload!
print($my_uploa der->file['name'] . " was successfully uploaded! <a
href=\"" . $_SERVER['PHP_SELF'] . "\">Try Again</a><br>");

// Print all the array details...
//print_r($my_upl oader->file);

// ...or print the file
if(stristr($my_ uploader->file['type'], "image")) {
echo "<img src=\"" . $path . $my_uploader->file['name'] . "\"
border=\"0\" alt=\"\">";
} else {
$fp = fopen($path . $my_uploader->file['name'], "r");
while(!feof($fp )) {
$line = fgets($fp, 255);
echo $line;
}
if ($fp) { fclose($fp); }
}
}
}


#--------------------------------#
# HTML FORM
#--------------------------------#
?>
<form enctype="multip art/form-data" action="<?= $_SERVER['PHP_SELF']; ?>"
method="POST">
<input type="hidden" name="submitted " value="true">

Upload this file:<br>
<input name="<?= $upload_file_na me; ?>" type="file">
<br><br>

Error Messages:<br>
<select name="language" >
<option value="en">Engl ish</option>
<option value="fr">Fren ch</option>
<option value="de">Germ an</option>
<option value="nl">Dutc h</option>
<option value="it">Ital ian</option>
<option value="fi">Finn ish</option>
<option value="es">Span ish</option>
<option value="no">Norw egian</option>
<option value="da">Dani sh</option>
</select>
<br><br>

<input type="submit" value="Upload File">
</form>
<hr>

<?php
if (isset($accepta ble_file_types) && trim($acceptabl e_file_types)) {
print("This form only accepts <b>" . str_replace("|" , " or ",
$acceptable_fil e_types) . "</b> files\n");
}
?>

</body>
</html>

and the included file :

<?php
/**
*
* class uploader
*
* Copyright 1999, 2002, 2003 David Fox, Dave Tufts
* Language specific error messaging:
* [fr] Frank from http://www.ibigin.com - initial code and French text
* [de] lmg from http://www.kishalmi.net - German text
* [nl] Andre, a.********@stud ent.utwente.nl - Dutch text
* [it] Enrico Valsecchi http://www.hostyle.it <ad***@hostyle. it> -
Italian text
* [fi] Dotcom Media Solutions, http://www.dotcom.ms - Finnish text
* [es] Alejandro Ramirez <al**@cinengano s.com> - Spanish text
* [no] Sigbjorn Eide <se***@tiscali. no> - Norwegian text
* [da] Thomas Hannibal http://hannibalsoftware.dk/ - Danish Text
*
* Usage, setup, and license at the bottom of this page (README)
*
* @version: 2.15
* @last_update: 2004-02-18
* @description: PHP file upload class
* @requires: PHP 4.1 or higher
*
* @changes: v2.15 - Added Danish (da) error messaging
* @changes: v2.14 - Edited acceptable_file _types checks to be more
lenient
* @changes: v2.13 - Added Spanish (es) and Norwegian (no) error
messaging, converted all non-valid HTML language chars to named entities
* @changes: v2.12 - Added Finnish (fi) error messaging
* @changes: v2.11 - Fixed bug if $this->save_file::$pa th is ""
* @changes: v2.10 - Added var $path to class definition
* @changes: v2.9 - Updated error_message[5] for NL (Dutch)
* @changes: v2.8 - Cleaned up Italian error messaging (thanks to
Maurizio Lemmo - http://www.tenzione.it/ )
* @changes: v2.7 - Added new error code [5] to save_file() method,
fixed minor bug if unable to write to upload directory
* @changes: v2.6 - Added $this->acceptable_fil e_types. Fixed minor
bug fix in upload() - if file 'type' is null
* @changes: v2.5.2 - Added Italian (it) error messgaing
* @changes: v2.5.1 - Added German (de) and Dutch (nl) error messgaing
* @changes: v2.4 - Added error messgae language preferences
* @changes: v2.3.1 - Bugfix for upload $path in $this->save_file()
* @changes: v2.3 - Initialized all variables (compatibale with PHP
error notices)
* @changes: v2.2 - Changed ereg() to stristr() whenever possible
*
*
* METHODS:
* uploader() - constructor, sets error message language preference
* max_filesize() - set a max filesize in bytes
* max_image_size( ) - set max pixel dimenstions for image uploads
* upload() - checks if file is acceptable, uploads file to server's
temp directory
* save_file() - moves the uploaded file and renames it depending on the
save_file($over write_mode)
*
* cleanup_text_fi le() - (PRIVATE) convert Mac and/or PC line breaks to
UNIX
* get_error() - (PRIVATE) gets language-specific error message
*
* Error code: available in English (en), French (fr), German (de), Dutch
(nl), Italian (it)
* [0] - "No file was uploaded"
* [1] - "Maximum file size exceeded"
* [2] - "Maximum image size exceeded"
* [3] - "Only specified file type may be uploaded"
* [4] - "File already exists" (save only)
* [5] - "Permission denied. Unable to copy file"
*
*/
class uploader {

var $file;
var $path;
var $language;
var $acceptable_fil e_types;
var $error;
var $errors; // Depreciated (only for backward compatability)
var $accepted;
var $max_filesize;
var $max_image_widt h;
var $max_image_heig ht;
/**
* object uploader ([string language]);
*
* Class constructor, sets error messaging language preference
*
* @param language (string) defaults to en (English).
*
* @examples: $f = new uploader(); // English error messages
* $f = new uploader('fr'); // French error messages
* $f = new uploader('de'); // German error messages
* $f = new uploader('nl'); // Dutch error messages
* $f = new uploader('it'); // Italian error messages
* $f = new uploader('fi'); // Finnish error messages
* $f = new uploader('es'); // Spanish error messages
* $f = new uploader('no'); // Norwegian error messages
* $f = new uploader('da'); // Danish error messages
*
*/
function uploader ( $language = 'en' ) {
$this->language = strtolower($lan guage);
$this->error = '';
}
/**
* void max_filesize ( int size);
*
* Set the maximum file size in bytes ($size), allowable by the object.
* NOTE: PHP's configuration file also can control the maximum upload size,
which is set to 2 or 4
* megs by default. To upload larger files, you'll have to change the
php.ini file first.
*
* @param size (int) file size in bytes
*
*/
function max_filesize($s ize){
$this->max_filesize = (int) $size;
}
/**
* void max_image_size ( int width, int height );
*
* Sets the maximum pixel dimensions. Will only be checked if the
* uploaded file is an image
*
* @param width (int) maximum pixel width of image uploads
* @param height (int) maximum pixel height of image uploads
*
*/
function max_image_size( $width, $height){
$this->max_image_widt h = (int) $width;
$this->max_image_heig ht = (int) $height;
}
/**
* bool upload (string filename[, string accept_type[, string extension]]);
*
* Checks if the file is acceptable and uploads it to PHP's default upload
diretory
*
* @param filename (string) form field name of uploaded file
* @param accept_type (string) acceptable mime-types
* @param extension (string) default filename extenstion
*
*/
function upload($filenam e='', $accept_type='' , $extention='') {

$this->acceptable_fil e_types = trim($accept_ty pe); // used by error
messages

if (!isset($_FILES ) || !is_array($_FIL ES[$filename]) ||
!$_FILES[$filename]['name']) {
$this->error = $this->get_error(0) ;
$this->accepted = FALSE;
return FALSE;
}

// Copy PHP's global $_FILES array to a local array
$this->file = $_FILES[$filename];
$this->file['file'] = $filename;

// Initialize empty array elements
if (!isset($this->file['extention'])) $this->file['extention'] = "";
if (!isset($this->file['type'])) $this->file['type'] = "";
if (!isset($this->file['size'])) $this->file['size'] = "";
if (!isset($this->file['width'])) $this->file['width'] = "";
if (!isset($this->file['height'])) $this->file['height'] = "";
if (!isset($this->file['tmp_name'])) $this->file['tmp_name'] = "";
if (!isset($this->file['raw_name'])) $this->file['raw_name'] = "";

// test max size
if($this->max_filesize && ($this->file["size"] > $this->max_filesize )) {
$this->error = $this->get_error(1) ;
$this->accepted = FALSE;
return FALSE;
}

if(stristr($thi s->file["type"], "image")) {

/* IMAGES */
$image = getimagesize($t his->file["tmp_name"]);
$this->file["width"] = $image[0];
$this->file["height"] = $image[1];

// test max image size
if(($this->max_image_widt h || $this->max_image_heig ht) &&
(($this->file["width"] > $this->max_image_widt h) || ($this->file["height"] >
$this->max_image_heig ht))) {
$this->error = $this->get_error(2) ;
$this->accepted = FALSE;
return FALSE;
}
// Image Type is returned from getimagesize() function
switch($image[2]) {
case 1:
$this->file["extention"] = ".gif"; break;
case 2:
$this->file["extention"] = ".jpg"; break;
case 3:
$this->file["extention"] = ".png"; break;
case 4:
$this->file["extention"] = ".swf"; break;
case 5:
$this->file["extention"] = ".psd"; break;
case 6:
$this->file["extention"] = ".bmp"; break;
case 7:
$this->file["extention"] = ".tif"; break;
case 8:
$this->file["extention"] = ".tif"; break;
default:
$this->file["extention"] = $extention; break;
}
} elseif(!ereg("( \.)([a-z0-9]{3,5})$", $this->file["name"]) &&
!$extention) {
// Try and autmatically figure out the file type
// For more on mime-types:
http://httpd.apache.org/docs/mod/mod_mime_magic.html
switch($this->file["type"]) {
case "text/plain":
$this->file["extention"] = ".txt"; break;
case "text/richtext":
$this->file["extention"] = ".txt"; break;
default:
break;
}
} else {
$this->file["extention"] = $extention;
}

// check to see if the file is of type specified
if($this->acceptable_fil e_types) {
if(trim($this->file["type"]) && (stristr($this->acceptable_fil e_types,
$this->file["type"]) || stristr($this->file["type"],
$this->acceptable_fil e_types)) ) {
$this->accepted = TRUE;
} else {
$this->accepted = FALSE;
$this->error = $this->get_error(3) ;
}
} else {
$this->accepted = TRUE;
}

return (bool) $this->accepted;
}
/**
* bool save_file ( string path[, int overwrite_mode] );
*
* Cleans up the filename, copies the file from PHP's temp location to
$path,
* and checks the overwrite_mode
*
* @param path (string) File path to your upload directory
* @param overwrite_mode (int) 1 = overwrite existing file
* 2 = rename if filename already exists (file.txt becomes
file_copy0.txt)
* 3 = do nothing if a file exists
*
*/
function save_file($path , $overwrite_mode ="3"){
if ($this->error) {
return false;
}

if (strlen($path)> 0) {
if ($path[strlen($path)-1] != "/") {
$path = $path . "/";
}
}
$this->path = $path;
$copy = "";
$n = 1;
$success = false;

if($this->accepted) {
// Clean up file name (only lowercase letters, numbers and underscores)
$this->file["name"] = ereg_replace("[^a-z0-9._]", "", str_replace(" ",
"_", str_replace("%2 0", "_", strtolower($thi s->file["name"]))));

// Clean up text file breaks
if(stristr($thi s->file["type"], "text")) {
$this->cleanup_text_f ile($this->file["tmp_name"]);
}

// get the raw name of the file (without its extenstion)
if(ereg("(\.)([a-z0-9]{2,5})$", $this->file["name"])) {
$pos = strrpos($this->file["name"], ".");
if(!$this->file["extention"]) {
$this->file["extention"] = substr($this->file["name"], $pos,
strlen($this->file["name"]));
}
$this->file['raw_name'] = substr($this->file["name"], 0, $pos);
} else {
$this->file['raw_name'] = $this->file["name"];
if ($this->file["extention"]) {
$this->file["name"] = $this->file["name"] . $this->file["extention"];
}
}

switch((int) $overwrite_mode ) {
case 1: // overwrite mode
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"]))
{
$success = true;
} else {
$success = false;
$this->error = $this->get_error(5) ;
}
break;
case 2: // create new with incremental extention
while(file_exis ts($this->path . $this->file['raw_name'] . $copy .
$this->file["extention"])) {
$copy = "_copy" . $n;
$n++;
}
$this->file["name"] = $this->file['raw_name'] . $copy .
$this->file["extention"];
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"]))
{
$success = true;
} else {
$success = false;
$this->error = $this->get_error(5) ;
}
break;
default: // do nothing if exists, highest protection
if(file_exists( $this->path . $this->file["name"])){
$this->error = $this->get_error(4) ;
$success = false;
} else {
if (@copy($this->file["tmp_name"], $this->path . $this->file["name"]))
{
$success = true;
} else {
$success = false;
$this->error = $this->get_error(5) ;
}
}
break;
}

if(!$success) { unset($this->file['tmp_name']); }
return (bool) $success;
} else {
$this->error = $this->get_error(3) ;
return FALSE;
}
}
/**
* string get_error(int error_code);
*
* Gets the correct error message for language set by constructor
*
* @param error_code (int) error code
*
*/
function get_error($erro r_code='') {
$error_message = array();
$error_code = (int) $error_code;

switch ( $this->language ) {
// French (fr)
case 'fr':
$error_message[0] = "Aucun fichier n'a &eacute;t&eacut e; envoy&eacute;";
$error_message[1] = "Taille maximale autoris&eacute; e
d&eacute;pass&e acute;e. Le fichier ne doit pas &ecirc;tre plus gros que " .
$this->max_filesize/1000 . " Ko (" . $this->max_filesize . " octets).";
$error_message[2] = "Taille de l'image incorrecte. L'image ne doit pas
d&eacute;pass er " . $this->max_image_widt h . " pixels de large sur " .
$this->max_image_heig ht . " de haut.";
$error_message[3] = "Type de fichier incorrect. Seulement les fichiers
de type " . str_replace("|" , " or ", $this->acceptable_fil e_types) . " sont
autoris&eacute; s.";
$error_message[4] = "Fichier '" . $this->path . $this->file["name"] . "'
d&eacute;j&aacu te; existant, &eacute;craseme nt interdit.";
$error_message[5] = "La permission a ni&eacute;. Incapable pour copier
le fichier &aacute; '" . $this->path . "'";
break;

// German (de)
case 'de':
$error_message[0] = "Es wurde keine Datei hochgeladen";
$error_message[1] = "Maximale Dateigr&ouml;ss e &uuml;berschrit ten. Datei
darf nicht gr&ouml;sser als " . $this->max_filesize/1000 . " KB (" .
$this->max_filesize . " bytes) sein.";
$error_message[2] = "Maximale Bildgr&ouml;sse &uuml;berschrit ten. Bild
darf nicht gr&ouml;sser als " . $this->max_image_widt h . " x " .
$this->max_image_heig ht . " pixel sein.";
$error_message[3] = "Nur " . str_replace("|" , " oder ",
$this->acceptable_fil e_types) . " Dateien d&uuml;rfen hochgeladen werden.";
$error_message[4] = "Datei '" . $this->path . $this->file["name"] . "'
existiert bereits.";
$error_message[5] = "Erlaubnis hat verweigert. Unf&amul;hig, Akte zu '"
.. $this->path . "'";
break;

// Dutch (nl)
case 'nl':
$error_message[0] = "Er is geen bestand geupload";
$error_message[1] = "Maximum bestandslimiet overschreden. Bestanden
mogen niet groter zijn dan " . $this->max_filesize/1000 . " KB (" .
$this->max_filesize . " bytes).";
$error_message[2] = "Maximum plaatje omvang overschreven. Plaatjes mogen
niet groter zijn dan " . $this->max_image_widt h . " x " .
$this->max_image_heig ht . " pixels.";
$error_message[3] = "Alleen " . str_replace("|" , " of ",
$this->acceptable_fil e_types) . " bestanden mogen worden geupload.";
$error_message[4] = "Bestand '" . $this->path . $this->file["name"] . "'
bestaat al.";
$error_message[5] = "Toestemmin g is geweigerd. Kon het bestand niet naar
'" . $this->path . "' copieren.";
//$error_message[5] = "Toestemmin g ontkende. Onbekwaam dossier aan '" .
$this->path . "'";
break;

// Italian (it)
case 'it':
$error_message[0] = "Il file non e' stato salvato";
$error_message[1] = "Il file e' troppo grande. La dimensione massima del
file e' " . $this->max_filesize/1000 . " Kb (" . $this->max_filesize . "
bytes).";
$error_message[2] = "L'immagine e' troppo grande. Le dimensioni massime
non possono essere superiori a " . $this->max_image_widt h . " pixel di
larghezza per " . $this->max_image_heig ht . " d'altezza.";
$error_message[3] = "Il tipo di file non e' valido. Solo file di tipo "
.. str_replace("|" , " o ", $this->acceptable_fil e_types) . " sono
autorizzati.";
$error_message[4] = "E' gia' presente un file con nome " . $this->path .
$this->file["name"];
$error_message[5] = "Permesso negato. Impossibile copiare il file in '"
.. $this->path . "'";
break;

// Finnish
case 'fi':
$error_message[0] = "Tiedostoa ei l&amul;hetetty. ";
$error_message[1] = "Tiedosto on liian suuri. Tiedoston koko ei saa olla
yli " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . "
tavua).";
$error_message[2] = "Kuva on liian iso. Kuva ei saa olla yli " .
$this->max_image_widt h . " x " . $this->max_image_heig ht . "
pikseli&amul;." ;
$error_message[3] = "Vain " . str_replace("|" , " tai ",
$this->acceptable_fil e_types) . " tiedostoja voi tallentaa kuvapankkiin.";
$error_message[4] = "Tiedosto '" . $this->path . $this->file["name"] .
"' on jo olemassa.";
$error_message[5] = "Ei k&amul;ytt&ouml ;oikeutta. Tiedostoa ei voi
kopioida hakemistoon '" . $this->path . "'";
break;

// Spanish
case 'es':
$error_message[0] = "No se subi&oacute; ning&uacute;n archivo.";
$error_message[1] = "Se excedi&oacute; el tama&ntilde;o m&aacute;ximo
del archivo. El archivo no puede ser mayor a " . $this->max_filesize/1000 .
" KB (" . $this->max_filesize . " bytes).";
$error_message[2] = "Se excedieron las dimensiones de la imagen. La
imagen no puede medir m&aacute;s de " . $this->max_image_widt h . " (w) x " .
$this->max_image_heig ht . " (h) pixeles.";
$error_message[3] = "El tipo de archivo no es v&aacute;lido . S&oacute;lo
los archivos " . str_replace("|" , " o ", $this->acceptable_fil e_types) . "
son permitidos.";
$error_message[4] = "El archivo '" . $this->path . $this->file["name"] .
"' ya existe.";
$error_message[5] = "Permiso denegado. No es posible copiar el archivo a
'" . $this->path . "'";
break;

// Norwegian
case 'no':
$error_message[0] = "Ingen fil ble lastet opp.";
$error_message[1] = "Max filst&oslash;rr else ble oversteget. Filen kan
ikke v¾re st&oslash;rre ennn " . $this->max_filesize/1000 . " KB (" .
$this->max_filesize . " byte).";
$error_message[2] = "Max bildest&oslash; rrelse ble oversteget. Bildet
kan ikke v¾re st&oslash;rre enn " . $this->max_image_widt h . " x " .
$this->max_image_heig ht . " piksler.";
$error_message[3] = "Bare " . str_replace("|" , " tai ",
$this->acceptable_fil e_types) . " kan lastes opp.";
$error_message[4] = "Filen '" . $this->path . $this->file["name"] . "'
finnes fra f&oslash;r.";
$error_message[5] = "Tilgang nektet. Kan ikke kopiere filen til '" .
$this->path . "'";
break;

// Danish
case 'da':
$error_message[0] = "Ingen fil blev uploaded";
$error_message[1] = "Den maksimale filst¿rrelse er overskredet. Filerne
mO ikke v¾re st¿rre end " . $this->max_filesize/1000 . " KB (" .
$this->max_filesize . " bytes).";
$error_message[2] = "Den maksimale billedst¿rrelse er overskredet.
Billeder mO ikke v¾re st¿rre end " . $this->max_image_widt h . " x " .
$this->max_image_heig ht . " pixels.";
$error_message[3] = "Kun " . str_replace("|" , " or ",
$this->acceptable_fil e_types) . " kan uploades.";
$error_message[4] = "Filen '" . $this->path . $this->file["name"] . "'
eksisterer allerede.";
$error_message[5] = "Adgang n¾gtet! Er ikke i stand til at kopiere filen
til '" . $this->path . "'";
break;
// English
default:
$error_message[0] = "No file was uploaded";
$error_message[1] = "Maximum file size exceeded. File may be no larger
than " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . "
bytes).";
$error_message[2] = "Maximum image size exceeded. Image may be no more
than " . $this->max_image_widt h . " x " . $this->max_image_heig ht . "
pixels.";
$error_message[3] = "Only " . str_replace("|" , " or ",
$this->acceptable_fil e_types) . " files may be uploaded.";
$error_message[4] = "File '" . $this->path . $this->file["name"] . "'
already exists.";
$error_message[5] = "Permission denied. Unable to copy file to '" .
$this->path . "'";
break;
}

// for backward compatability:
$this->errors[$error_code] = $error_message[$error_code];

return $error_message[$error_code];
}
/**
* void cleanup_text_fi le (string file);
*
* Convert Mac and/or PC line breaks to UNIX by opening
* and rewriting the file on the server
*
* @param file (string) Path and name of text file
*
*/
function cleanup_text_fi le($file){
// chr(13) = CR (carridge return) = Macintosh
// chr(10) = LF (line feed) = Unix
// Win line break = CRLF
$new_file = '';
$old_file = '';
$fcontents = file($file);
while (list ($line_num, $line) = each($fcontents )) {
$old_file .= $line;
$new_file .= str_replace(chr (13), chr(10), $line);
}
if ($old_file != $new_file) {
// Open the uploaded file, and re-write it with the new changes
$fp = fopen($file, "w");
fwrite($fp, $new_file);
fclose($fp);
}
}

}
/*
<readme>

fileupload-class.php can be used to upload files of any type
to a web server using a web browser. The uploaded file's name will
get cleaned up - special characters will be deleted, and spaces
get replaced with underscores, and moved to a specified
directory (on your server). fileupload-class.php also does its best to
determine the file's type (text, GIF, JPEG, etc). If the user
has named the file with the correct extension (.txt, .gif, etc),
then the class will use that, but if the user tries to upload
an extensionless file, PHP does can identify text, gif, jpeg,
and png files for you. As a last resort, if there is no
specified extension, and PHP can not determine the type, you
can set a default extension to be added.

SETUP:
Make sure that the directory that you plan on uploading
files to has enough permissions for your web server to
write/upload to it. (usually, this means making it world writable)
- cd /your/web/dir
- chmod 777 <fileupload_dir >

The HTML FORM used to upload the file should look like this:
<form method="post" action="upload. php" enctype="multip art/form-data">
<input type="file" name="userfile" >
<input type="submit" value="Submit">
</form>
USAGE:
// Create a new instance of the class
$my_uploader = new uploader;

// OPTIONAL: set the max filesize of uploadable files in bytes
$my_uploader->max_filesize(9 0000);

// OPTIONAL: if you're uploading images, you can set the max pixel
dimensions
$my_uploader->max_image_size (150, 300); // max_image_size( $width, $height)

// UPLOAD the file
$my_uploader->upload("userfi le", "", ".jpg");

// MOVE THE FILE to its final destination
// $mode = 1 :: overwrite existing file
// $mode = 2 :: rename new file if a file
// with the same name already
// exists: file.txt becomes file_copy0.txt
// $mode = 3 :: do nothing if a file with the
// same name already exists
$my_uploader->save_file("/your/web/dir/fileupload_dir" , int $mode);

// Check if everything worked
if ($my_uploader->error) {
echo $my_uploader->error . "<br>";

} else {
// Successful upload!
$file_name = $my_uploader->file['name'];
print($file_nam e . " was successfully uploaded!");

}

</readme>
<license>

///// fileupload-class.php /////
Copyright (c) 1999, 2002, 2003 David Fox, Angryrobot Productions
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. Neither the name of author nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

DISCLAIMER:
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.

</license>

*/
?>

Jul 17 '05 #1
3 11749
dave wrote:
Hello there,

I am at my wit's end ! I have used the following script succesfully to
upload an image to my web space. But what I really want to be able to do is
to update an existing record in a table in MySQL with the path & filename to
the image.
How about storing the actual image in your db? (I'm just asking here,
hoping someone else will have views on this. Same conclusion for
PostgreSQL?)

I'm not primarily a using PHP/MySQL, but it's fair to assume that the
web-server won't do a lot worse at caching image data than the file
system? Of course there's some overhead on the db connection, but.
I have successfully uploaded and performed an update query on the database,
but the problem I have is I cannot retain the primary key field in a
variable which is then used in a SQL update statement to ensure that I
update the correct field in the MySQL table. I have not included the code
for the SQL update.

To summarise I guess what I am trying to do is create a page for updating
produuct data on an ecommerce site. So the Promary key is the Product Number
and I need to store the image filename in the products table.


Didn't bother reading the code, sorry, but your problem is simply losing
track of some variable during page transitions while you do image
uploads or whatever else?

The best fix is probably storing the product id in a session variable
while all the image upload stuff is going on.

You could also pass it along as a parameter to any of the file upload
pages as well, either by embedding it in the forms as a hidden field, or
as a parameter in the urls. Problem is this would clutter up your image
upload logic, so stick with sessions.
Jul 17 '05 #2
On 18/11/04 3:17 pm, in article cn**********@ti tan.btinternet. com, "dave"
<da**@sdhandlin g.co.uk> wrote:
Hello there,

I am at my wit's end ! I have used the following script succesfully to
upload an image to my web space. But what I really want to be able to do is
to update an existing record in a table in MySQL with the path & filename to
the image.

I have successfully uploaded and performed an update query on the database,
but the problem I have is I cannot retain the primary key field in a
variable which is then used in a SQL update statement to ensure that I
update the correct field in the MySQL table. I have not included the code
for the SQL update.

To summarise I guess what I am trying to do is create a page for updating
produuct data on an ecommerce site. So the Promary key is the Product Number
and I need to store the image filename in the products table.

Any Help will be gratefuly received. I am sure this is a very very simple
question to an experienced PHP programmer, I just cant get my head around
it all at the minute !

Thanks in advance Dave Griffin.


I could be barking up completely the wrong tree here but is all the code
that was here yours?

I had something like this with a system I wrote for a customer to add
vacancies to a table for their site. They could upload a MS Word doc with
an application form or job description. This all worked fine with it
putting the file name into the table.

The problem came when they wanted to edit one. I had to look at the form
they filled in, check to see if the 'file' field was blank or not and then
act accordingly. I'm pretty new to PHP and it took me ages to work out.
I'm just in the process of doing something similar for a customer who wants
a simple photo gallery on the site with the ability to edit entries as well.

The upshot is, the code you had was WAY ahead of my ability. If it's your
own and you're determined to make it work then I can't help. If it's
someone else's code and your only aim is to end up with something that will
do what you want then I can help. My code will be a billion miles from the
most elegant code in the world but it works for me.

Let me know if you want what I've done.

Andy

Jul 17 '05 #3
"Andy Jacobs" <oc*@redcatmedi a.net> wrote in message
news:BDC2D25A.3 320%oc*@redcatm edia.net...
On 18/11/04 3:17 pm, in article cn**********@ti tan.btinternet. com, "dave"
<da**@sdhandlin g.co.uk> wrote:
Hello there,

I am at my wit's end ! I have used the following script succesfully to
upload an image to my web space. But what I really want to be able to do is to update an existing record in a table in MySQL with the path & filename to the image.

I have successfully uploaded and performed an update query on the database, but the problem I have is I cannot retain the primary key field in a
variable which is then used in a SQL update statement to ensure that I
update the correct field in the MySQL table. I have not included the code for the SQL update.

To summarise I guess what I am trying to do is create a page for updating produuct data on an ecommerce site. So the Promary key is the Product Number and I need to store the image filename in the products table.

Any Help will be gratefuly received. I am sure this is a very very simple question to an experienced PHP programmer, I just cant get my head around it all at the minute !

Thanks in advance Dave Griffin.

I could be barking up completely the wrong tree here but is all the code
that was here yours?

I had something like this with a system I wrote for a customer to add
vacancies to a table for their site. They could upload a MS Word doc with
an application form or job description. This all worked fine with it
putting the file name into the table.

The problem came when they wanted to edit one. I had to look at the form
they filled in, check to see if the 'file' field was blank or not and then
act accordingly. I'm pretty new to PHP and it took me ages to work out.
I'm just in the process of doing something similar for a customer who

wants a simple photo gallery on the site with the ability to edit entries as well.
The upshot is, the code you had was WAY ahead of my ability. If it's your
own and you're determined to make it work then I can't help. If it's
someone else's code and your only aim is to end up with something that will do what you want then I can help. My code will be a billion miles from the most elegant code in the world but it works for me.

Let me know if you want what I've done.

Andy


I wish I could say it was all my own code !! But its not, I would be very
grateful if you could let me see your code.

I may have confused the issue when trying to explain in my original post so
here's a summary of what I am trying to achieve !

I have product details stored in a table called products.

The page I am trying to create receives the URL variable Prodcut_ID which a
SELECT Query uses in its WHERE clause to return only the details of the
record with the matching product_id.

I then want to upload an image to my webspace and update a field in the
Product table with the image filename.

The bit I am struggling with is when the form is submitted , the image
uploads and the page refreshes and I always loose the product_id and
therfore my sql statement fails as it has an unaasigned variable.

I am thinking that a session variable would do the job, but I am having
difficulties ! doing this in PHP, as I am used to ASP. My host does not
support ASP Upload ! Hence the reason I am using PHP.

Any help is gratefully received !

Dave
Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
9290
by: bissatch | last post by:
Hi, I am trying to write script that is run when a form is submitted. The form contains an image input field and when submitted, the image is uploaded, resized and added as binary information to a db table. Please note, I am using a PostgreSQL database I have written all the code out below that deals with the submission processing:
13
2341
by: Neo Geshel | last post by:
I have examined about 80+ different upload scripts on the 'net, both in VB and C#, and none seem to do what I need them to do. Perhaps someone here can point me somewhere that Google hasn't reached yet (I have gone all the way to page 50 on Google's results!!). Here are my requirements: • I have a DataGrid. Everything will be done from...
3
2967
by: samoore | last post by:
Can you upload an image using a windows app. I either want to upload the image to a database or just a folder, but all of my searches show that you have to use a web app. I want to do this with a win app. Any help would be appreciated. Samoore33
0
1189
by: Danny Boy | last post by:
I'm sorry to burst in here like a cheap Charlie, but I'm at wit's end. For two days, I have been looking for a simple script, perhaps supported by MySQL or storing the data in flat pages. I really don't care so much. It should work like a very basic guestbook with this image attachment option: User enters page. User writes his name in...
3
1718
by: mishrarajesh44 | last post by:
hiiii, i am making addressbook, which will include name,mobile,address, photo, and want to save in mysql databqse all data and only the name of image file. i want that by clicking the submit buttton the data will be added to mysql database and image will b uploaded simulataneously, i know the code for both image upload & dataadding in...
3
4409
by: premprakashbhati | last post by:
hi, good evening.. i am going to upload an image in a web form .....for that iam using HTML input(file) control and one web control button i.e., Upload_Button() here is the code ...its work fine when iam using a normal web page... but can't in content page.... Code in Master Page <%@ Master Language="C#" AutoEventWireup="true"...
8
9842
johngault
by: johngault | last post by:
I've been working with this PHP page for several days now and I'm stumped. The page is supposed to allow the user to upload up to six images for their profile. When the user adds an image it (the page coding) does verify file size, if correct it places it on the server in the users folder and with the correct names and extension, creates the...
1
2246
by: ririe | last post by:
Hi. I have a problem here. I want to upload a file together with its semester. So I create two field. One for the semester and one for the file to be uploaded. But the script doesn't work. I don't know why. However, if I try to upload the file without the semester field, the script is working. May be the problem comes from the semester field. This...
1
4871
by: chennaibala | last post by:
can any one send me mutiple image upload program and save the file name with extension in mysql table.we must cheak uploaded file type like bmp or any image file while uploading. i develop program,which can upload many file in folder.problem is,am unable to save my file name in to database.because i used same name for all input file type as...
0
8081
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8258
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8119
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6482
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5322
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3759
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2254
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1082
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.