0

I'm trying to code a registration form. But I'm stuck at adding a borrowed code of image upload, resize, save and store its path in MySQL database. The error message is "Undefined index: fileimage" on the line where I have this code: if($_FILES['fileimage']['name']).

Here is the register.php:

<?php



    // include configuration file

    require("../includes/config.php");



    //Class import for image uploading

    include("../includes/upload_class.php");



    // if form was submitted

    if ($_SERVER["REQUEST_METHOD"] == "POST")

    {

        // validate submission

        if (empty($_POST["firstname"]))

        {

            apologize("Provide your first name.");

        }

        if (empty($_POST["lastname"]))

        {

            apologize("Provide your last name.");

        }

        if (empty($_POST["username"]))

        {

            apologize("Provide a username.");

        }

        if (empty($_POST["sex"]))

        {

            apologize("Select your sex.");

        }

        else if (empty($_POST["password"]))

        {

            apologize("Enter a password.");

        }

        else if (empty($_POST["confirmation"]))

        {

            apologize("Confirm your password.");

        }

        else if ($_POST["password"] != $_POST["confirmation"])

        {

            apologize("Password and confirmation do not match.");

        }

        if (empty($_POST["email"]))

        {

            apologize("Provide your email address");

        }



        //image uploading part

        if($_FILES['fileimage']['name'])

        {



            $max_size = 10000*10000; // the maximum size for uploading



            $my_upload = new file_upload;



            $my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)

            $my_upload->extensions = array(".png", ".jpeg", ".gif", ".jpg", ".jpeg"); // specify the allowed extensions here

            // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)

            $my_upload->max_length_filename = 1000; // change this value to fit your field length in your database (standard 100)

            $my_upload->rename_file = true;





            $my_upload->the_temp_file = $_FILES['fileimage']['tmp_name'];

            $my_upload->the_file = $_FILES['fileimage']['name'];

            $my_upload->http_error = $_FILES['fileimage']['error'];

            //$my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true

            //$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename

            //$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";

            if ($my_upload->upload())

            { // new name is an additional filename information, use this to rename the uploaded file

                $full_path = $my_upload->upload_dir.$my_upload->file_copy;

                $imagename = $my_upload->get_uploaded_file_info($full_path);

                // ... or do something like insert the filename to the database

            }



        }

        else

        {

             $imagename = "";

        }



      //End of the image uploading section



        if (!empty($_POST["username"]))

        {

            $result = query("INSERT INTO users(firstname, lastname, username, sex, hash, email, userimage) VALUES (?, ?, ?, ?, ?, ?, ?)",

            $_POST["username"],

            crypt($_POST["password"]));



            // if username is in database

            if ($result === false)

            {

                apologize("Username has been taken");

            }
            if ($_POST["email"] === false)
            {
                apologize("The email has already been taken.");
            }



            // find out user's ID

            $rows = query("SELECT LAST_INSERT_ID() AS id");

            $id = $rows[0]["id"];



            // remember user is logged in by storing user's ID in a session

            $_SESSION["id"] = $row["id"];



            // redirect to portfolio

            redirect("/");

        }

    }

    else

    {

        // else render form

        render("register_form.php", ["title" => "Register"]);

    }



?>

Here is the upload_class.php:

<?php

    class file_upload {



    var $the_file;

    var $the_temp_file;

    var $upload_dir;

    var $replace;

    var $do_filename_check;

    var $max_length_filename = 100;

    var $extensions;

    var $ext_string;

    var $language;

    var $http_error;

    var $rename_file; // if this var is true the file copy get a new name

    var $file_copy; // the new name

    var $message = array();

    var $create_directory = true;



    function file_upload() {

        $this->language = "en"; // choice of en, nl, es

        $this->rename_file = false;

        $this->ext_string = "";

    }

    function show_error_string() {

        $msg_string = "";

        foreach ($this->message as $value) {

            $msg_string .= $value."<br>\n";

        }

        return $msg_string;

    }

    function set_file_name($new_name = "") { // this "conversion" is used for unique/new filenames 

        if ($this->rename_file) {

            if ($this->the_file == "") return;

            $name = ($new_name == "") ? strtotime("now") : $new_name;

            $name = $name.$this->get_extension($this->the_file);

        } else {

            $name = $this->the_file;

        }

        return $name;

    }

    function upload($to_name = "") {

        $new_name = $this->set_file_name($to_name);

        if ($this->check_file_name($new_name)) {

            if ($this->validateExtension()) {

                if (is_uploaded_file($this->the_temp_file)) {

                    $this->file_copy = $new_name;

                    if ($this->move_upload($this->the_temp_file, $this->file_copy)) {

                        $this->message[] = $this->error_text($this->http_error);

                        if ($this->rename_file) $this->message[] = $this->error_text(16);

                        return true;

                    }

                } else {

                    $this->message[] = $this->error_text($this->http_error);

                    return false;

                }

            } else {

                $this->show_extensions();

                $this->message[] = $this->error_text(11);

                return false;

            }

        } else {

            return false;

        }

    }

    function check_file_name($the_name) {

        if ($the_name != "") {

            if (strlen($the_name) > $this->max_length_filename) {

                $this->message[] = $this->error_text(13);

                return false;

            } else {

                if ($this->do_filename_check == "y") {

                    if (preg_match("/^[a-z0-9_]*\.(.){1,5}$/i", $the_name)) {

                        return true;

                    } else {

                        $this->message[] = $this->error_text(12);

                        return false;

                    }

                } else {

                    return true;

                }

            }

        } else {

            $this->message[] = $this->error_text(10);

            return false;

        }

    }

    function get_extension($from_file) {

        $ext = strtolower(strrchr($from_file,"."));

        return $ext;

    }

    function validateExtension() {

        $extension = $this->get_extension($this->the_file);

        $ext_array = $this->extensions;

        if (in_array($extension, $ext_array)) { 

            // check mime type hier too against allowed/restricted mime types (boolean check mimetype)

            return true;

        } else {

            return false;

        }

    }

    // this method is only used for detailed error reporting

    function show_extensions() {

        $this->ext_string = implode(" ", $this->extensions);

    }

    function move_upload($tmp_file, $new_file) {

        umask(0);

        if ($this->existing_file($new_file)) {

            $newfile = $this->upload_dir.$new_file;

            if ($this->check_dir($this->upload_dir)) {

                if (move_uploaded_file($tmp_file, $newfile)) {

                    if ($this->replace == "y") {

                        //system("chmod 0777 $newfile"); // maybe you need to use the system command in some cases...

                        chmod($newfile , 0777);

                    } else {

                        // system("chmod 0755 $newfile");

                        chmod($newfile , 0755);

                    }

                    return true;

                } else {

                    return false;

                }

            } else {

                $this->message[] = $this->error_text(14);

                return false;

            }

        } else {

            $this->message[] = $this->error_text(15);

            return false;

        }

    }

    function check_dir($directory) {

        if (!is_dir($directory)) {

            if ($this->create_directory) {

                umask(0);

                mkdir($directory, 0777);

                return true;

            } else {

                return false;

            }

        } else {

            return true;

        }

    }

    function existing_file($file_name) {

        if ($this->replace == "y") {

            return true;

        } else {

            if (file_exists($this->upload_dir.$file_name)) {

                return false;

            } else {

                return true;

            }

        }

    }

    function get_uploaded_file_info($name) {

        $str = "File name: ".basename($name)."\n";

        $str .= "File size: ".filesize($name)." bytes\n";

        if (function_exists("mime_content_type")) {

            $str .= "Mime type: ".mime_content_type($name)."\n";

        }

        if ($img_dim = getimagesize($name)) {

            $str .= "Image dimensions: x = ".$img_dim[0]."px, y = ".$img_dim[1]."px\n";

        }

        return basename($name);

    }

    // this method was first located inside the foto_upload extension

    function del_temp_file($file) {

        $delete = @unlink($file); 

        clearstatcache();

        if (@file_exists($file)) { 

            $filesys = eregi_replace("/","\\",$file); 

            $delete = @system("del $filesys");

            clearstatcache();

            if (@file_exists($file)) { 

                $delete = @chmod ($file, 0775); 

                $delete = @unlink($file); 

                $delete = @system("del $filesys");

            }

        }

    }

    // some error (HTTP)reporting, change the messages or remove options if you like.

    function error_text($err_num) {

        switch ($this->language) {

            case "nl":

            $error[0] = "Foto succesvol kopieert.";

            $error[1] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";

            $error[2] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";

            $error[3] = "Fout bij het uploaden, probeer het nog een keer.";

            $error[4] = "Fout bij het uploaden, probeer het nog een keer.";

            $error[10] = "Selecteer een bestand.";

            $error[11] = "Het zijn alleen bestanden van dit type toegestaan: <b>".$this->ext_string."</b>";

            $error[12] = "Sorry, de bestandsnaam bevat tekens die niet zijn toegestaan. Gebruik alleen nummer, letters en het underscore teken. <br>Een geldige naam eindigt met een punt en de extensie.";

            $error[13] = "De bestandsnaam is te lang, het maximum is: ".$this->max_length_filename." teken.";

            $error[14] = "Sorry, het opgegeven directory bestaat niet!";

            $error[15] = "Uploading <b>".$this->the_file."...Fout!</b> Sorry, er is al een bestand met deze naam aanwezig.";

            $error[16] = "Het gekopieerde bestand is hernoemd naar <b>".$this->file_copy."</b>.";

            break;

            case "de":

            $error[0] = "Die Datei: <b>".$this->the_file."</b> wurde hochgeladen!"; 

            $error[1] = "Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Server-Konfiguration!"; 

            $error[2] = "Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Klassen-Konfiguration!"; 

            $error[3] = "Die hochzuladende Datei wurde nur teilweise &uuml;bertragen"; 

            $error[4] = "Es wurde keine Datei hochgeladen"; 

            $error[10] = "W&auml;hlen Sie eine Datei aus!."; 

            $error[11] = "Es sind nur Dateien mit folgenden Endungen erlaubt: <b>".$this->ext_string."</b>";

            $error[12] = "Der Dateiname enth&auml;lt ung&uuml;ltige Zeichen. Benutzen Sie nur alphanumerische Zeichen f&uuml;r den Dateinamen mit Unterstrich. <br>Ein g&uuml;ltiger Dateiname endet mit einem Punkt, gefolgt von der Endung."; 

            $error[13] = "Der Dateiname &uuml;berschreitet die maximale Anzahl von ".$this->max_length_filename." Zeichen."; 

            $error[14] = "Das Upload-Verzeichnis existiert nicht!"; 

            $error[15] = "Upload <b>".$this->the_file."...Fehler!</b> Eine Datei mit gleichem Dateinamen existiert bereits.";

            $error[16] = "Die hochgeladene Datei ist umbenannt in <b>".$this->file_copy."</b>.";

            break;

            //

            // place here the translations (if you need) from the directory "add_translations"

            //

            default:

            // start http errors

            $error[0] = "File: <b>".$this->the_file."</b> successfully uploaded!";

            $error[1] = "The uploaded file exceeds the max. upload filesize directive in the server configuration.";

            $error[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.";

            $error[3] = "The uploaded file was only partially uploaded";

            $error[4] = "No file was uploaded";

            // end  http errors

            $error[10] = "Please select a file for upload.";

            $error[11] = "Only files with the following extensions are allowed: <b>".$this->ext_string."</b>";

            $error[12] = "Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.";

            $error[13] = "The filename exceeds the maximum length of ".$this->max_length_filename." characters.";

            $error[14] = "Sorry, the upload directory doesn't exist!";

            $error[15] = "Uploading <b>".$this->the_file."...Error!</b> Sorry, a file with this name already exitst.";

            $error[16] = "The uploaded file is renamed to <b>".$this->file_copy."</b>.";



        }

        return $error[$err_num];

    }

}

?>
4
Contributors
10
Replies
62
Views
3 Years
Discussion Span
Last Post by mexabet
0

Undefined index usally mean the name attr is incorrect or missing when sending post. If not, you could try

if(isset($_FILE['fileimage']['name']){
// code
}

This will chekc if post has fileimage set apon submission.

0

@gabrielcastillo,
Thanks for your contribution. The form is as follows:

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

    <fieldset>

        <div class="form-group">

            <input autofocus class="form-control" name="firstname" placeholder="First Name" type="text"/>

        </div>

        <div class="form-group">

            <input autofocus class="form-control" name="lastname" placeholder="Last Name" type="text"/>

        </div>

        <div class="form-group">

            <input autofocus class="form-control" name="username" placeholder="Username" type="text"/>

        </div>

        <div class="form-group">

            <select autofocus class="form-control" name="sex" value="sex">

                <option value="Male" selected="selected">Male</option>

                <option value="Female">Female</option>

            </select>

        </div>

        <div class="form-group">

            <input class="form-control" name="password" placeholder="Password" type="password"/>

        </div>

        <div class="form-group">

            <input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>

        </div>

        <div class="form-group">

            <input autofocus class="form-control" name="email" placeholder="Email" type="text"/>

        </div>

        <div class="form-group">

            <input autofocus class="form-control" name="userimage" placeholder="Your Photo" type="file"/>

        </div>

        <div class="form-group">

            <button type="submit" class="btn btn-default">Register</button>

        </div>

    </fieldset>

</form>

<div>

    or <a href="login.php">log in</a>

</div>

<br/>
0

Example PHP Code
This script resize an Image into two 60px and 25px. Take a look at $newwidth you have to modify size values.

<?php 

 define ("MAX_SIZE","400");

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")

        $image =$_FILES["file"]["name"];
 $uploadedfile = $_FILES['file']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['file']['name']);
        $extension = getExtension($filename);
  $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif")) 
  {
echo ' Unknown Image extension ';
$errors=1;
  }
 else
{
   $size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
 echo "You have exceeded the size limit";
 $errors=1;
}

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);

$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

 if(isset($_POST['Submit']) && !$errors) 
 {
   // mysql_query("update SQL statement ");
  echo "Image Uploaded Successfully!";

 }
 ?>
0

Thanks, but I need to get the script I posted to work, as it works on a site I know.

0

Before addressing your problem, please allow me to point out minor problem with your class. It might be minor now because like you said it is working on the other site that you know, but it can be a major problem sooner than later.

The upload class was written for the old PHP version with backward compatibility for the PHP 4.x.x versions. I don't think there are many servers these days still running on 4.x.x version.

The solution is to rewrite it to PHP 5.x.x compliant class. I know some readers coming from other languages would say "What the _ell Veedeoo is talking about?". This may sound like a Bull _hit to a few practitioner of the laguage, but I am pretty sure it is not. I will not waste my precious time typing all these crapola just for the purpose of delivering my BS. I don't do that kind of stuffs. My time is important as much as I value the time of others reading my opinions, analysis and suggestions on the subject matter before me.

Classes written in PHP with backward compatibility was written similar to the class written in JAVA. There is no constructor. The constructor rules in the old PHP version was to create a method with the same name of the class itself.

The old way

class MyClass{

    var $var1;
    var $var2 = 'var two';
    var $var3;

    function MyClass(){
        $this->var1 = $var1;
        $this->var2 = $var2;
        }

    function method1(){

       return $this->var2;

   }    
 }       

Class variable members are now called properties. These properties are defined with its appropriate visibility under the descretion of the programmer e.g. private, public, public static and protected. All methods are now defined with their apropriate visibilities.

The new way

class MyClass{

    private $var1;
    private $var2 = 'var two';
    private $var3 ;

    ## or
    /*
      private $var1, $var2, $var3;  
   */
   ## or 
   /*
       public $var1;
       public $var2;
       public $var3;
   */

   public function __construct(){
       $this->var1 = $var1;
       $this->var2 = $var2;

      }

   public function method1(){

       return $this->var2;

   }

   public static static_method(){

       return $this->var2;

  } 

}

Edited by veedeoo: info added.

0

this

 public static static_method(){
    return $this->var2;
    } 

should read

 public static function static_method(){
    return $this->var2;
    } 
0

@veedeoo,
You're totally correct; the class was written for a very old version of PHP, and the thought has always worried me. However, I'm not fluent enough to rewrite class.

Can you or any other person help me out, even if at a cost?

1

I don't charge people for providing them with the help I could possibly provide. However, you can donate for the cause of Daniweb.

Then you can post the source code here.

0

@veedeoo,
A million thanks for agreeing to help me out. I've just donated a little sum to the Daniweb cause. I downloaded the the latest upload_class.php from

http://www.finalwebsites.com/snippets.php?id=7 

However, I think the code need to be updated to the PHP 5.5 version. As follows is the upload_class.php:

<?php 

/*

Easy PHP Upload - version 2.33

A easy to use class for your (multiple) file uploads



Copyright (c) 2004 - 2011, Olaf Lederer

All rights reserved.



Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:



    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

    * 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.

    * Neither the name of the finalwebsites.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.



THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.



_________________________________________________________________________

available at http://www.finalwebsites.com/snippets.php?id=7

Comments & suggestions: http://www.finalwebsites.com/blog/submit-a-question/



*************************************************************************/



class file_upload {



    var $the_file;

    var $the_temp_file;

    var $the_mime_type; // new in 2.33

    var $upload_dir;

    var $replace;

    var $do_filename_check;

    var $max_length_filename = 100;

    var $extensions;

    var $valid_mime_types = array('.gif'=>'image/gif', '.jpg'=>'image/jpeg', '.jpeg'=>'image/jpeg', '.png'=>'image/png'); // new in 2.33 (search google for a complete list)

    var $ext_string;

    var $language;

    var $http_error;

    var $rename_file; // if this var is true the file copy get a new name

    var $file_copy; // the new name

    var $message = array();

    var $create_directory = true;

    /* 

    ver. 2.32 

    Added vars for file and directory permissions, check also the methods move_upload() and check_dir().

    */

    var $fileperm = 0644;

    var $dirperm = 0755; 



    function file_upload() {

        $this->language = 'en'; // choice of en, nl, es

        $this->rename_file = false;

        $this->ext_string = '';

    }

    function show_error_string($br = '<br />') {

        $msg_string = '';

        foreach ($this->message as $value) {

            $msg_string .= $value.$br;

        }

        return $msg_string;

    }

    function set_file_name($new_name = '') { // this 'conversion' is used for unique/new filenames 

        if ($this->rename_file) {

            if ($this->the_file == '') return;

            $name = ($new_name == '') ? strtotime('now') : $new_name;

            sleep(3);

            $name = $name.$this->get_extension($this->the_file);

        } else {

            $name = str_replace(' ', '_', $this->the_file); // space will result in problems on linux systems

        }

        return $name;

    }

    function upload($to_name = '') {

        $new_name = $this->set_file_name($to_name);

        if ($this->check_file_name($new_name)) {

            if ($this->validateExtension()) {

                if (is_uploaded_file($this->the_temp_file)) {

                    $this->file_copy = $new_name;

                    if ($this->move_upload($this->the_temp_file, $this->file_copy)) {

                        $this->message[] = $this->error_text($this->http_error);

                        if ($this->rename_file) $this->message[] = $this->error_text(16);

                        return true;

                    }

                } else {

                    $this->message[] = $this->error_text($this->http_error);

                    return false;

                }

            } else {

                $this->show_extensions();

                $this->message[] = $this->error_text(11);

                return false;

            }

        } else {

            return false;

        }

    }

    function check_file_name($the_name) {

        if ($the_name != '') {

            if (strlen($the_name) > $this->max_length_filename) {

                $this->message[] = $this->error_text(13);

                return false;

            } else {

                if ($this->do_filename_check == 'y') {

                    if (preg_match('/^[a-z0-9_]*\.(.){1,5}$/i', $the_name)) {

                        return true;

                    } else {

                        $this->message[] = $this->error_text(12);

                        return false;

                    }

                } else {

                    return true;

                }

            }

        } else {

            $this->message[] = $this->error_text(10);

            return false;

        }

    }

    function get_extension($from_file) {

        $ext = strtolower(strrchr($from_file,'.'));

        return $ext;

    }

    /* New in version 2.33 */

    function validateMimeType() {

        $ext = $this->get_extension($this->the_file);

        if ($this->the_mime_type == $this->valid_mime_types[$ext]) {

            return true;

        } else {

            $this->message[] = $this->error_text(18);

            return false;

        }

    }

    /* Added here the mime check in ver. 2.33 */

    function validateExtension() {

        $extension = $this->get_extension($this->the_file);

        $ext_array = $this->extensions;

        if (in_array($extension, $ext_array)) {

            if (!empty($this->the_mime_type)) {

                if ($this->validateMimeType()) {

                    return true;

                } else {

                    return false;

                }

            } else {

                return true;

            }

        } else {

            return false;

        }

    }

    // this method is only used for detailed error reporting

    function show_extensions() {

        $this->ext_string = implode(' ', $this->extensions);

    }

    function move_upload($tmp_file, $new_file) {

        if ($this->existing_file($new_file)) {

            $newfile = $this->upload_dir.$new_file;

            if ($this->check_dir($this->upload_dir)) {

                if (move_uploaded_file($tmp_file, $newfile)) {

                    umask(0);

                    chmod($newfile , $this->fileperm);

                    return true;

                } else {

                    return false;

                }

            } else {

                $this->message[] = $this->error_text(14);

                return false;

            }

        } else {

            $this->message[] = $this->error_text(15);

            return false;

        }

    }

    function check_dir($directory) {

        if (!is_dir($directory)) {

            if ($this->create_directory) {

                umask(0);

                mkdir($directory, $this->dirperm);

                return true;

            } else {

                return false;

            }

        } else {

            return true;

        }

    }

    function existing_file($file_name) {

        if ($this->replace == 'y') {

            return true;

        } else {

            if (file_exists($this->upload_dir.$file_name)) {

                return false;

            } else {

                return true;

            }

        }

    }

    /*

    ver. 2.32 

    Method get_uploaded_file_info(): Replaced old \n line-ends with the PHP constant variable PHP_EOL

    */

    function get_uploaded_file_info($name) {

        $str = 'File name: '.basename($name).PHP_EOL;

        $str .= 'File size: '.filesize($name).' bytes'.PHP_EOL;

        if (function_exists('mime_content_type')) {

            $str .= 'Mime type: '.mime_content_type($name).PHP_EOL;

        }

        if ($img_dim = getimagesize($name)) {

            $str .= 'Image dimensions: x = '.$img_dim[0].'px, y = '.$img_dim[1].'px'.PHP_EOL;

        }

        return $str;

    }

    // this method was first located inside the foto_upload extension

    function del_temp_file($file) {

        $delete = @unlink($file); 

        clearstatcache();

        if (@file_exists($file)) { 

            $filesys = eregi_replace('/','\\',$file); 

            $delete = @system('del $filesys');

            clearstatcache();

            if (@file_exists($file)) { 

                $delete = @chmod ($file, 0644); 

                $delete = @unlink($file); 

                $delete = @system('del $filesys');

            }

        }

    }

    // this function creates a file field and if $show_alternate is true it will show a text field if the given file already exists

    // there is also a submit button to remove the text field value 

    /*

    ver. 2.32 

    Method create_file_field(): Minor code clean up (better code formatting and replaced double with single quotes)

    */

    function create_file_field($element, $label = '', $length = 25, $show_replace = true, $replace_label = 'Replace old file?', $file_path = '', $file_name = '', $show_alternate = false, $alt_length = 30, $alt_btn_label = 'Delete image') {

        $field = '';

        if ($label != '') $field = '

            <label>'.$label.'</label>';

        $field = '

            <input type="file" name="'.$element.'" size="'.$length.'" />';

        if ($show_replace) $field .= '

            <span>'.$replace_label.'</span>

            <input type="checkbox" name="replace" value="y" />';

        if ($file_name != '' && $show_alternate) {

            $field .= '

            <input type="text" name="'.$element.'" size="'.$alt_length.'" value="'.$file_name.'" readonly="readonly"';

            $field .= (!@file_exists($file_path.$file_name)) ? ' title="'.sprintf($this->error_text(17), $file_name).'" />' : ' />';

            $field .= '

            <input type="checkbox" name="del_img" value="y" />

            <span>'.$alt_btn_label.'</span>';

        } 

        return $field;

    }

    // some error (HTTP)reporting, change the messages or remove options if you like.

    /* ver 2.32 

    Method error_text(): Older Dutch language messages are re-written, thanks Julian A. de Marchi. Added HTTP error messages (error 6-7 introduced with newer PHP versions, error no. 5 doesn't exists) 

    */

    function error_text($err_num) {

        switch ($this->language) {

            case 'nl':  

            $error[0] = 'Bestand <b>'.$this->the_file.'</b> staat nu op de server.';

            $error[1] = 'Dit bestand is groter dan de toegestaane upload bestandgrootte in de server configuratie.';

            $error[2] = 'Dit bestand is groter dan de MAX_FILE_SIZE parameter welke in de html formulier werdt gespecificiëerd.';

            $error[3] = 'De upload is helaas mislukt.  Slechts een deel van het bestand is bij de server aangekomen.  Probeer het opnieuw.';

            $error[4] = 'De upload is helaas mislukt.  Geen betrouwbare verbinding met de server kwam tot stand.  Probeer het opnieuw.';

            $error[6] = 'De map voor tijdelijke opslag ontbreekt. ';

            $error[7] = 'Het schrijven op de server is mislukt. ';

            $error[8] = 'Een PHP extensie is gestopt tijdens het uploaden. ';

            // end  http errors

            $error[10] = 'Selecteer een bestand om te uploaden.';

            $error[11] = 'Uitsluitend bestanden van de volgende types zijn toegestaan: <b>'.$this->ext_string.'</b>';

            $error[12] = 'Helaas heeft het gekozen bestand karakters die niet zijn toegestaan. Gebruik uitsluitend cijfers, letters, en onderstrepen. <br>Een geldige naam eindigt met een punt met daarop volgend het extensietype.';

            $error[13] = 'De bestandsnaam is echter te lang, en mag een maximum van '.$this->max_length_filename.' tekens bevatten.';

            $error[14] = 'De gekozen map werdt niet gevonden.';

            $error[15] = 'Een bestand met dezelfde naam ('.$this->the_file.') bestaat al op de server.  Probeer opnieuw met een andere naam.';

            $error[16] = 'Op de server werdt het bestand hernoemd tot <b>'.$this->file_copy.'</b>.';

            $error[17] = 'Het bestand %s bestaat niet.';

            $error[18] = 'De soort bestand (mime type) is niet toegestaan.'; // new ver. 2.33

            break;

            case 'de':

            $error[0] = 'Die Datei: <b>'.$this->the_file.'</b> wurde hochgeladen!'; 

            $error[1] = 'Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Server-Konfiguration!'; 

            $error[2] = 'Die hochzuladende Datei ist gr&ouml;&szlig;er als der Wert in der Klassen-Konfiguration!'; 

            $error[3] = 'Die hochzuladende Datei wurde nur teilweise &uuml;bertragen'; 

            $error[4] = 'Es wurde keine Datei hochgeladen';

            $error[6] = 'Der tempor&auml;re Dateiordner fehlt';

            $error[7] = 'Das Schreiben der Datei auf der Festplatte war nicht m&ouml;glich.';

            $error[8] = 'Eine PHP Erweiterung hat w&auml;hrend dem hochladen aufgeh&ouml;rt zu arbeiten. '; 



            $error[10] = 'W&auml;hlen Sie eine Datei aus!.'; 

            $error[11] = 'Es sind nur Dateien mit folgenden Endungen erlaubt: <b>'.$this->ext_string.'</b>';

            $error[12] = 'Der Dateiname enth&auml;lt ung&uuml;ltige Zeichen. Benutzen Sie nur alphanumerische Zeichen f&uuml;r den Dateinamen mit Unterstrich. <br>Ein g&uuml;ltiger Dateiname endet mit einem Punkt, gefolgt von der Endung.'; 

            $error[13] = 'Der Dateiname &uuml;berschreitet die maximale Anzahl von '.$this->max_length_filename.' Zeichen.'; 

            $error[14] = 'Das Upload-Verzeichnis existiert nicht!'; 

            $error[15] = 'Upload <b>'.$this->the_file.'...Fehler!</b> Eine Datei mit gleichem Dateinamen existiert bereits.';

            $error[16] = 'Die hochgeladene Datei ist umbenannt in <b>'.$this->file_copy.'</b>.';

            $error[17] = 'Die Datei %s existiert nicht.';

            $error[18] = 'Der Datei Typ (mime type) ist nicht erlaubt.'; // new ver. 2.33

            break;

            //

            // place here the translations (if you need) from the directory 'add_translations'

            //

            default:

            // start http errors

            $error[0] = 'File: <b>'.$this->the_file.'</b> successfully uploaded!';

            $error[1] = 'The uploaded file exceeds the max. upload filesize directive in the server configuration.';

            $error[2] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.';

            $error[3] = 'The uploaded file was only partially uploaded';

            $error[4] = 'No file was uploaded';

            $error[6] = 'Missing a temporary folder. ';

            $error[7] = 'Failed to write file to disk. ';

            $error[8] = 'A PHP extension stopped the file upload. ';



            // end  http errors

            $error[10] = 'Please select a file for upload.';

            $error[11] = 'Only files with the following extensions are allowed: <b>'.$this->ext_string.'</b>';

            $error[12] = 'Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.';

            $error[13] = 'The filename exceeds the maximum length of '.$this->max_length_filename.' characters.';

            $error[14] = 'Sorry, the upload directory does not exist!';

            $error[15] = 'Uploading <b>'.$this->the_file.'...Error!</b> Sorry, a file with this name already exitst.';

            $error[16] = 'The uploaded file is renamed to <b>'.$this->file_copy.'</b>.';

            $error[17] = 'The file %s does not exist.';

            $error[18] = 'The file type (mime type) is not valid.'; // new ver. 2.33

        }

        return $error[$err_num];

    }

}

?>

Here is the register.php:

<?php



    // include configuration file

    require ("../includes/config.php");



    //Class import for image uploading

    //classes is the map where the class file is stored (one above the root)

    include ("../classes/upload/upload_class.php");



    // if form was submitted

    if ($_SERVER["REQUEST_METHOD"] == "POST")

    {

        // validate submission

        if (empty($_POST["firstname"]))

        {

            apologize("Provide your first name.");

        }

        if (empty($_POST["lastname"]))

        {

            apologize("Provide your last name.");

        }

        if (empty($_POST["username"]))

        {

            apologize("Provide a username.");

        }

        if (empty($_POST["usersex"]))

        {

            apologize("Select your sex.");

        }

        else if (empty($_POST["password"]))

        {

            apologize("Enter a password.");

        }

        else if (empty($_POST["confirmation"]))

        {

            apologize("Confirm your password.");

        }

        else if ($_POST["password"] != $_POST["confirmation"])

        {

            apologize("Password and confirmation do not match.");

        }

        if (empty($_POST["email"]))

        {

            apologize("Provide your email address");

        }



        // file upload part

        $max_size = 1024*250; // the max. size for uploading



        $my_upload = new file_upload;



        $my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)

        $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here

        // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)

        $my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)

        $my_upload->rename_file = true;



        if(isset($_POST['Register'])) {

            $my_upload->the_temp_file = $_FILES['upload']['tmp_name'];

            $my_upload->the_file = $_FILES['upload']['name'];

            $my_upload->http_error = $_FILES['upload']['error'];

            $my_upload->replace = "y";

            $my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename

        if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file

            query(sprintf("INSERT INTO file_table SET file_name = '%s'", $my_upload->file_copy));

        }

        }



        // end of file upload part



        if (!empty($_POST["username"]))

        {

            $result = query("INSERT INTO users (firstname, lastname, username, usersex, hash, email, userimage) VALUES (?, ?, ?, ?, ?, ?, ?)",

            $_POST["firstname"],

            $_POST["lastname"],

            $_POST["username"],

            $_POST["usersex"],

            crypt($_POST["password"]),

            $_POST["email"]);



            // if username is in database

            if ($result === false)

            {

                apologize("Username has been taken");

            }

            if ($_POST["email"] === false)

            {

                apologize("The email has already been taken.");

            }



            // find out user's ID

            $rows = query("SELECT LAST_INSERT_ID() AS id");

            $id = $rows[0]["id"];



            // remember user is logged in by storing user's ID in a session

            $_SESSION["id"] = $row["id"];



            // redirect to portfolio

            redirect("/");

        }

    }

    else

    {

        // else render form

        render("register_form.php", ["title" => "Register"]);

    }



?>

Please, be advised that the register.php has some nice-working, custom PHP functions like render, apologize and query. I would want to resize the image (160px x 160px) before saving it. The original image needs to be deleted from the server. The path to each image needs to be saved in the database and linked to right user. I've already created users and file_table DB tables, but I need guidance on how to associate a user to his/her photo.

I reiterate my appreciations for your kind help.

Edited by mexabet: corrected something

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.