TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Accessing Variables from Conf file to Upload Class (http://www.talkphp.com/absolute-beginners/2298-accessing-variables-conf-file-upload-class.html)

Gareth 02-20-2008 09:20 PM

Accessing Variables from Conf file to Upload Class
 
Hey.

I am integrating a members system into an uploading system.
The upload system runs off a class, which does everything (i.e. show the form, upload file, shows paths etc).

Now, in the member system, I have set $_SESSION['member_id'] to the ID of the user that logged in. I set a var $vID = $_SESSION['member_id'] so that I can echo the member's id out anywhere.

So, at the moment I have the uploading set up so that it also inserts data into a database, named sui_images. This includes normal stuff like id, name, date uploaded, ip etc but more importantly the member's id, so that when I make a "manage uploaded images" page I can show the logged in user all his images by stating WHERE member_id = $vID.

I link to the config file in both the class (upload.class.php) and upload.php, have set at the top public $vID and then in my MySQL query set it so that it inserts the Member's ID into the database.

But it doesn't!

I don't know too much about classes/ functions, but is there anything I have to do to be able to access the variables in conf_global.php?

Any help would be much appreciated.

Gareth

SOCK 02-20-2008 10:13 PM

I'm getting an idea of what you're talking about, but the best thing to do would be post the relevant code, esp. your class definition that uses the $vID variable. You're saying that you've set a public $vID var in your class, but where is it set? Is it being set in the 'conf_global.php' script? If so, you need a way to carry that over into the class scope. Using $_SESSION['member_id'] directly inside the class would probably be the best way, as it's a superglobal and has global scope.

Gareth 02-20-2008 11:41 PM

snip!
Thank you to SOCK for sorting this out with me!

SOCK 02-21-2008 03:25 AM

Ok, it's as I thought. You expect that your 'conf_global.php' script makes those variables global. Then you attempt to access it in your class as part of the SQL statement, additionally creating a class data member (variable) with the same name.

You could technically use the global keyword in front of all the variables you want to access globally, but I recommend against this practice. With the exception of the superglobals and possibly a database handler, I avoid global vars like the plague.

The $vID variable in your 'conf_global.php' script has scope within only that script or within any script that includes it. This is what you might consider 'script scope' (if there is such a thing). It can be accessed directly within the script, or calling script, but not within any function or class. It is not a global variable.

The sui::$vID class variable is similar; it only exists within the scope of that class, and must be referred to as $this->vID within any class method. So your uploadfile() method can access the sui::$vID variable, but only as $this->vID. It has scope within any method using the $this keyword ($this represents the currently instantiated object, in other words, this one). I notice you're referring to the other class data member 'path' in the correct manner.

Now, if you're not confused by this point, read on. :-)

The $_SESSION superglobal array has universal scope. It can be accessed within any script, function or class method. If this were my class, I would probably do this:
PHP Code:

class sui {

  
// protected data member to store the path
  
protected $path'http://localhost/sui_adv/uploads/';

  
// protected data member to store the member_id value 
  
protected $vID

  
// our constructor
  // allow overwrite the path value
  
__construct($pathNULL) {

    
// initiate the class member 'vID' to a default state
    // namely, the member_id value stored in the session
    
$this->vID $_SESSION['member_id'];

    
// if the 'path' variable must be altered, do so here
    
if ( $path != NULL ) {
        
$this->path$path;
    }

  }



Notice how I changed the script to include a constructor method (any non-statically called class should have a constructor, even if it's empty) and give you the ability to change the 'path' member as an argument to the constructor. In other words, you could do this and keep the default path:
PHP Code:

$myFileObject= new sui(); 

.. or instantiate the object like so and have it alter the path dynamically:
PHP Code:

$myFileObject= new sui('http://yourserver.com/path'); 

One of the main principals of class design is to keep things portable and not be locked into any one structure. It should be flexible enough that you can use it on any system and not worry about the default path being 'http://localhost/some/path/'.

Also take note of the fact that I'm defining these data members as protected. Good practice dictates that you always start with the most restricted access you can live with, and in most cases, protected works well. In addition, defining the variables with the 'var' keyword just doesn't fly anymore; use one of the visibility keywords.

PHP Manual : Language Reference | Variables | Variable scope

Classes and Objects in PHP 5

Hope this helps! Let me know if anything isn't clear.

Gareth 02-21-2008 01:01 PM

WOW SOCK, you are a legend. You own! A few questions:

1. So the constructor basically allows the variables to be used?
2. The constructor should be function __construct(), should it not (after looking at the links you gave)?
3. Should I use a __destructor at the end?

Well, I've just tried it and it works! Thank you SO much!

SOCK 02-21-2008 02:55 PM

I'm glad it worked out.

1) The constructor essentially 'sets up' the object with any default values or calls any methods that are crucial to the object's existence. So if you do have data members you need to set to a default state, or a class method that needs to perform a certain task prior to using the object, this is the place to do it. Constructors are OOP basics.

2) Yes. PHP v5 introduced the __construct() method as the default constructor. Prior to v5, it was the same name as the class (which is pretty normal for OOP). So in other words, these two are the same:

v4
PHP Code:

class MyTestClass {
  
// v4 data member, public by default
  
var $testme;

  
// v4 constructor
  
function MyTestClass($t) {
    
$this->testme $t;
  }


and v5
PHP Code:

class MyTestClass {
  
// v5 data member, setting visibility
  
protected $testme;

  
// v5 constructor
  
function __construct($t) {
    
$this->testme $t;
  }


As I stated before, you should always have a constructor on non-statically called classes, it's just good practice.

3) Not necessarily. Destructors are used for specific tasks when 'destroying' the object (when the script ends or when you specifically unset the object variable). It's like a constructor in reverse. You probably won't find it all that useful until you are well into OOP programming.

If you haven't already, I'd advise reading up more on objects and OOP in general. Just check Wikipedia for OOP or Google.

Gareth 02-21-2008 11:23 PM

Hey Sock, do you have an IM? It works fine on localhost, but when I upload it to a shared hosting it comes up with the following error:

http://www.imgbite.com/uploads/66799_uploadit_error.gif

Located at: Upload It!

the php at the moment (uploadit.class.php)

PHP Code:

<?php

    
require_once("conf_global.php");

    class 
sui {                                                            
        
          protected 
$path'http://localhost/sui_adv/uploads/';
        protected 
$vID
      
    function 
__construct($path NULL) {

        
$this->vID $_SESSION['member_id'];

        if ( 
$path != NULL ) {
            
$this->path $path;
        }
    
      }

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

    
function uploadfile($filename$filesize$filewidth$fileheight$fileext$tmpname$dir$max_height$max_width$max_size){

        
$allowed = array("jpg","png","gif");                                                                    

        if(!
in_array($fileext,$allowed)){                                
                     echo 
"File type not supported: $fileext";        
                }

             else{

                if(
$filewidth>$max_width){                            
                    echo 
"Image width is over the limit";            
                }

            elseif(
$fileheight>$max_height){                        
                    echo 
"Image height is over the limit";            
                }

                else{

            if(
$filesize>$max_size){                                
                    echo 
"Image size is over the limit";    
                }

            else{                        

            
$rand rand(1000,100000);            
            
$newfilename urlencode($filename);
            
$newname $rand."_".$newfilename;        
            
$bb $this->path.$rand."_".$newfilename;    
            
$memberID $this->vID;
            
            
$html "<img src=$bb alt=\"Simply Upload It\" />";    

                if(
copy($tmpname$dir.$newname)){                                                    
                        
                        
$date date("jS M Y");
                        
$time date("g:i a");    
                        
                        
$query "    INSERT INTO 
                                        sui_images 
                                  (    id,
                                      member_id,
                                      name,
                                    date,
                                    time)
                                    
                                    VALUES (
                                    '',
                                    '
$memberID',
                                    '
$newname',
                                    '
$date',
                                    '
$time')";
                                    
                        if(
mysql_query($query)){
                                                    
                        echo 
"
                        <p><a href=\"
$bb\"><img src=\"$bb\" border=\"0\" width=\"100\" height=\"100\" /></a></p>

                        <p><strong>Direct Link</strong> <br />
                        <input type=\"text\" size=\"70\" value=\"
$bb\" /></p>

                        <p><strong>BBCode</strong><br />
                        <input type=\"text\" size=\"70\" value=\"[img]"
.$bb."[/img]\" /></p>

                        <p><strong>HTML</strong><br />
                        <input type=text size=70 value='
$html' /></p>

                        <a href=\"index.php\">Upload again!</a>
                        "
;                                                
                        
                        }
                        
                        else{
                            echo 
"Error in adding image to Database <br />".mysql_error();
                            }
                        
                        }
                                                
                    else{                
                        echo 
"The copy was not successful";            
                        }
                    }
                    }
                }
    }                            

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

    
function uploadform($directory){                
        if(isset(
$_POST['upload'])){            

            if(!
is_dir($directory)){                            
                echo 
"Sorry, $directory was not found on the server.";
            }

        else{
               
$img_max_height "10000";                        
            
$img_max_width "10000";
            
$img_max_size "800000";
            
$image_name addslashes($_FILES['file']['name']);
            
$image_size $_FILES['file']['size'];
            
$image_dimensions getimagesize($_FILES['file']['tmp_name']);
            
$image_width $image_dimensions[0];
            
$image_height $image_dimensions[1];
            
$image_extention explode(".",$image_name);
            
$extention strtolower($image_extention[count($image_extention)-1]);
            
$image_tmp_name $_FILES['file']['tmp_name'];

        
$this->uploadfile($image_name,$image_size,$image_width,$image_height,$extention$image_tmp_name$directory$img_max_height$img_max_width$img_max_size);
            }                                                     
        }

        else{                                            
            return 
"
    <form enctype=\"multipart/form-data\" method=\"post\" action=\"
$_SERVER[PHP_SELF]\">
        <input type=\"file\" class=\"file\" name=\"file\" />
        <input type=\"submit\" name=\"upload\" value=\"Upload\" id=\"submit\" />
    </form>"
;
            }

        }                                                            

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

    
}                                                        

?>


Salathe 02-22-2008 12:19 AM

Is your server still running PHP4? If so, the protected keyword isn't available.

SOCK 02-22-2008 12:33 AM

Quote:

Originally Posted by Gareth (Post 11235)
Hey Sock, do you have an IM? It works fine on localhost, but when I upload it to a shared hosting it comes up with the following error:

So you're running PHP 5 and your host is using PHP 4. You need to be aware of these things before you start coding!!

Use this script on both your localhost server and your host's server:
PHP Code:

<?php phpinfo();?>

Absolutely imperative you go in knowing what version and functionality the target host has!!

Gareth 02-22-2008 01:11 AM

It has both! I just forgot to enter the htaccess code on the host :P

SOCK 02-22-2008 01:27 AM

Ah. Good job.^^:-D


All times are GMT. The time now is 09:52 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0