Upload a Photo - Class help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wibblywobbly
Forum Newbie
Posts: 17
Joined: Mon Oct 19, 2009 10:11 am

Upload a Photo - Class help

Post by wibblywobbly »

Hi Guys!

Thing have been going well for me, learning procedural PHP coding, but I don't want to go any further without putting it into Object Orientated Programming format.

I'm working on a new Class that lets the user upload an image with a description onto the server. The function gives the image a unique name and puts it in the folder /images/photos. The image name is also written into a mysql database along with the user's description, posted from a form.

Any advice or thoughts would be really helpful, and my biggest problems are to do with using OOP.

The main thing I want to achieve is, there is an echo="$message"; command at the bottom of the user's page. I want this to say either "Image uploaded successfully", "Please provide a description" or "No file was selected to be uploaded".

I have the whole thing fundamentally working, so any suggestions to help me finish this would be fantastic!

Here we go...

Code: Select all

 <?php
//connect to my database using a "DB" class
require_once("DB.php");
 
// Here's the new class "Photos"
class Photos{
 
    private $db;
    private $success = false;
 
    public function __construct()
    {
        //connect to the database
        $this->db = new DB();
    }
 
    //the new function begins...
    public function InsertPhoto($description, $image = array())
    {
        try{
                // check there is a file to upload
                if("" != $image['picture']['name'] && 0 != $image['picture']['size']){
                // name the image after the time uploaded and its original name
                $imgName = time() . basename($image['picture']['name']);
                }else{
                // Here I get lost, I want to exit the script and set the "$message" to "please select a photo to upload"
                }
 
                $sql = "INSERT INTO photos VALUES(NULL, '{$description}', '{$imgName}')";
                $result = $this->db->connection->query($sql);
                if(!$result){
                    throw new Exception($sql);
                }else{
                // finish the file upload
                $target = "../images/photos/" . $imgName;
                move_uploaded_file($image['picture']['tmp_name'], $target);
 
                // set success to true
                $this->success = true;
                     }
        }catch(Exception $e){
            echo("Insert query failed: " . $e->getMessage());
        }
    }
 
    public function getSuccess()
    {
        return $this->success;
    }
}
?>
 
<?php
 
//here is the Page using the class
 
if("Upload" == $_POST['submit']){
    // check the user has filled in the description box
    if("" != $_POST['description']){
 
    $photoInsert = new Photos();
    $photoInsert->InsertPhoto($_POST['description'], $_FILES);
    if($photoInsert->getSuccess()){
        //set the "$message" to "your photo has sucessfully been uploaded"
    }else{
        //sticky form to keep the values of the form
        $description = $_POST['description'];
        $message = "Required Field(s) are still empty";
    }
    }
}
 
?>
 
 
<form action="<?php echo($_SERVER['PHP_SELF']);?>" method="post" enctype="multipart/form-data">
        <ol>
            <li>
                <label for="description">Description:</label>
                <textarea name="description" id="description" rows="7" cols="30"><?php echo($description); ?></textarea>
            </li>
 
            <li>
                <label for="picture">Image:</label>
                <input type="file" name="picture" id="picture" />
            </li>
 
            <li class="last_item">
                <input type="submit" value="Upload" name="submit" class="button" />
            </li>
        </ol>
</form>
 
<?php
// finally here is the message I'm having difficulty with.
// All it has to say is "Please fill out the description field"
//"Please select a photo from your computer to upload"
//and
//Photo successfully uploaded!
 
if($message){
    echo("{$message}");
}
?>
 
badben
Forum Newbie
Posts: 4
Joined: Fri Oct 16, 2009 11:57 am
Location: Lancashire, UK

Re: Upload a Photo - Class help

Post by badben »

I have written a secure php file upload function here that will fit well into your class. More importantly it validates that the file is of the cortrect type, the right extension and can also validate that it is an image that is being uploaded.

the code is at http://www.tidy-designs.co.uk/secure-fi ... -using-php

I have tweaked this slightly for your application as follows:

Code: Select all

<?php
//connect to my database using a "DB" class
require_once("DB.php");
 
// Here's the new class "Photos"
class Photos{
 
    private $db;
 
    public function __construct()
    {
        //connect to the database
        $this->db = new DB();
    }
    
    function BuildMessage($result) {
        
        $message = '';
        
        if (is_array($result)) {
        
            foreach ($result as $msg) {
                $message .= '<span class="error">'.$msg.'</span>'."\n";
            }
        } else {
            $message = "Image uploaded successfully".$result;
        }
        
        return $message;
    }
 
    function InsertPhoto ($file_field = null, $check_image = false, $random_name = false, $description = null) {
       
        //Config Section
       print_r($_FILES[$file_field]);
        //Set file upload path
        $path = '../images/photos/'; //with trailing slash
        //Set max file size in bytes
        $max_size = 1000000;
        //Set default file extension whitelist
        $whitelist_ext = array('jpg','png','gif');
        //Set default file type whitelist
        $whitelist_type = array('image/jpeg', 'image/png','image/gif');
 
        //The Validation
 
        // Create an array to hold any error messages
        $error = array();
       
        if (!$file_field) {
                $error[] = "Please specify a valid form field name";           
        }
 
        if (!$path) {
                $error[] = "Please specify a valid upload path";               
        }
        
        if (!$description) {
                $error[] = "Please provide a description for the image";
        }
       
        if (count($error)>0) {
                return $error;
        }
 
        //Make sure that there is a file
        if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
         
                // Get filename
                $file_info = pathinfo($_FILES[$file_field]['name']);
                $name = $file_info['filename'];
                $ext = $file_info['extension'];
               
                //Check file has the right extension           
                if (!in_array($ext, $whitelist_ext)) {
                        $error[] = "Invalid file Extension";
                }
               
                //Check that the file is of the right type
                if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
                        $error[] = "Invalid file Type";
                }
               
                //Check that the file is not too big
                if ($_FILES[$file_field]["size"] > $max_size) {
                        $error[] = "File is too big";
                }
               
                //If $check image is set as true
                if ($check_image) {
                        if      (!getimagesize($_FILES[$file_field]['tmp_name'])) {
                                $error[] = "Uploaded file is not a valid image";
                        }
                }
               
                //Create full filename including path
                if ($random_name) {
                        // Generate random filename
                        $tmp = str_replace(array('.',' '), array('',''), microtime());
                       
                        if (!$tmp || tmp == '') {
                                $error[] = "File must have a name";
                        }
                       
                        $newname = $tmp.'.'.$ext;
                                       
                } else {
                        $newname = $name.'.'.$ext;
                }
               
                //Check if file already exists on server
                if (file_exists($path.$newname)) {
                        $error[] = "A file with this name already exists";
                }
               
                if (count($error)>0) {
                        //The file has not correctly validated
                        return $error;
                }
 
                if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
                           //Success
                           
                            $sql = "INSERT INTO photos VALUES(NULL, '".$description."', '".$path.$newname."')";
                            $result = $this->db->connection->query($sql);
                            if(!$result){
                                $error[] = "Unable to update database";
                            }
                           return $path.$newname;
                } else {
                           $error[] = "Server Error!";
                }
         
        } else {
                $error[] = "No file uploaded";
                return $error;
        }      
       
    }
 
}
?>
 
<?php
 
//here is the Page using the class
 
if("Upload" == $_POST['submit']){
 
    $photoInsert = new Photos();
    $image = $photoInsert->InsertPhoto('picture', true, true, $_POST['description']);
    print_r($image);
    $message = $photoInsert->BuildMessage($image);    
}
 
?>
 
 
<form action="<?php echo($_SERVER['PHP_SELF']);?>" method="post" enctype="multipart/form-data">
        <ol>
            <li>
                <label for="description">Description:</label>
                <textarea name="description" id="description" rows="7" cols="30"><?php echo($description); ?></textarea>
            </li>
 
            <li>
                <label for="picture">Image:</label>
                <input type="file" name="picture" id="picture" />
            </li>
 
            <li class="last_item">
                <input type="submit" value="Upload" name="submit" class="button" />
            </li>
        </ol>
</form>
 
<?php
// finally here is the message I'm having difficulty with.
// All it has to say is "Please fill out the description field"
//"Please select a photo from your computer to upload"
//and
//Photo successfully uploaded!
 
if($message){
    echo $message;
}
?>
wibblywobbly
Forum Newbie
Posts: 17
Joined: Mon Oct 19, 2009 10:11 am

Re: Upload a Photo - Class help

Post by wibblywobbly »

Ben!

This is really helpful. Putting file type limitations in and size restrictions was going to be my next step, so this is brilliant. I have it working, I can't pretend I know exactly how it works yet, so I need to spend some time studying.

Next stage is going to be building an amend function and a delete function, but this has been very generous of you. All the best!
Post Reply