Jump to content

Uploading Files


bigjoe11a

Recommended Posts

When I try and upload a file. That values come back as empty. Any one have any ideas why this is happening. $newfile = $_FILES['file']['tmp_name']; echo 'File Name '. $newfile; // this returns an empty string. Joe

Link to comment
Share on other sites

Thanks. There's still no error getting returned. I use the class below and it's telling me there's nothing wrong. How ever the values are still empty and no results are getting sent back. Joe

<?phpclass UploadException extends Exception{    public function __construct($code) {        $message = $this->codeToMessage($code);        parent::__construct($message, $code);    }    private function codeToMessage($code)    {        switch ($code) {            case UPLOAD_ERR_INI_SIZE:                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";                break;            case UPLOAD_ERR_FORM_SIZE:                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";                break;            case UPLOAD_ERR_PARTIAL:                $message = "The uploaded file was only partially uploaded";                break;            case UPLOAD_ERR_NO_FILE:                $message = "No file was uploaded";                break;            case UPLOAD_ERR_NO_TMP_DIR:                $message = "Missing a temporary folder";                break;            case UPLOAD_ERR_CANT_WRITE:                $message = "Failed to write file to disk";                break;            case UPLOAD_ERR_EXTENSION:                $message = "File upload stopped by extension";                break;            default:                $message = "Unknown upload error";                break;        }        return $message;    }}// Use if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {//uploading successfully done} else {throw new UploadException($_FILES['file']['error']);}?>

Link to comment
Share on other sites

No. I use $_FILES['avatar']['name']; That was just the sample from the link you sent me

Link to comment
Share on other sites

I know where the error is, that it's not an error. This is the 1st time I tried to use a class to upload files. and well that doesn't seem to work for some reason.

 class Profiles{ private $_imageName; function __contruct(){$this->_imageName = $_FILES['fileimage']['name'];}

This seems to return a empty value. Any ideas.

Link to comment
Share on other sites

If it's empty, then the value doesn't exist in the array. That means either there was an upload error, you're not using the right name for the file, or the form wasn't set up correctly. Check the $_FILES array like I showed above to see what has been submitted. The PHP manual I linked to earlier explains how to set up the form (make sure you use an enctype), and the common pitfalls page lists various PHP settings that affect uploads.

Link to comment
Share on other sites

That's just what I'm trying to tell you. The $_FILES array(0 is returning the uploaded file. and the file gets uploaded. The problem as I explained above. Is the class that I use. The class is not working like it should.

Link to comment
Share on other sites

I wanted to let you know that I did fix the problem. The problem was in the class. For some reason the private variables is where the problem is. See my samples below This code doesn't work

 class Profiles { private $_imageName;  function __construct(){ $this->_imageName = $_FILES['image']['name'];} //This returns an empty value } 

How ever the code below does work

 class Profiles { private $_fileName; public $imageName; function __construct(){$this->imageName = $_FILES['image']['name'];$this->_fileName = $this->imageName;} //This returns the file name } 

So I don't under stand why I have to code it like this. I all so had the same problem when trying to remove a file from a folder using a private variable.I had to set a public variable and then use that to remove the file from the folder. So it is confusing me. How ever I do have it working.

Link to comment
Share on other sites

Well you saw the samples above and Yes. They are all used in the Class it self. and Not out side the class. This is why I'm confused about this.

Link to comment
Share on other sites

Sorry about that, I should have. having 5 pc's drives me nuts some times. I use each pc for some thing different. The class is below.

<?phpclass Profile{    private $_errors;    private $_allowedext;          public $todayIs;       //File temp vars    public $fileName;    public $tempName;    public $fileSize;    public $fileError;    public $imagePath;	       //image info       private $_imageTemp;    private $_imageName;    private $_rootDir;    private $_newName;    private $_ext;    private $_DestPath;    private $_SourcePath;    private $_imageError;    private $_fileSize;    private $_defaultImage;        //user info    private $_uage;       private $_birthdate;    private $_birthsign;    private $_homepage;    private $_location;    private $_icq;    private $_msn;    private $_yahoo;    private $_country;    private $_hobbies;    private $_music;    private $_id;    private $_token;       function __construct($var = array())    {	    $this->_errors = array();	    $this->_allowedext = array(".jpg",".png",".jpeg", ".gif");	    $this->_defaultImage = 'default.jpg';	    $this->todayIs = mktime();	   	    //If image was added			   		    $this->fileName = $_FILES['imagefile']['name'];		    $this->fileTemp = $_FILES['imagefile']['tmp_name'];		    $this->fileSize = $_FILES['imagefile']['size'];		    $this->fileError = $_FILES['imagefile']['error'];	   		    $this->_imageName = $this->fileName;		    $this->_imageSize = $this->fileSize;		    $this->_imageTemp = $this->fileTemp;		    $this->_imageError = $this->fileError;							   	    $this->_RootDir = 'images/avatar/';	    $this->imagePath = $this->_RootDir;	   	   	    $this->_ext = strchr($this->_imageName, ".");			   	    $this->_newName = $this->RandString(10).strtolower($this->_ext);		  	    $this->_DestPath = $this->_RootDir . $this->_newName;	   	    //Users input	    $this->_uage = $_POST['uage'];	    $this->_birthdate = $_POST['birthdate'];	    $this->_birthsign =  $this->filter($_POST['birthsign']);	    $this->_homepage = $this->filter($_POST['homepage']);	    $this->_location = $this->filter($_POST['location']);	    $this->_icq = $this->filter($_POST['icqid']);	    $this->_msn = $this->filter($_POST['msnid']);	    $this->_yahoo = $this->filter($_POST['yahooid']);	    $this->_country = $this->filter($_POST['country']);	    $this->_hobbies = $this->filter($_POST['hobbies']);	    $this->_music = $this->filter($_POST['music']);	   	    $this->_token = $_POST['token'];	    $this->_id = $_SESSION[SESS_USERID];    }             private function _DbConnect()    {	   	    mysql_connect(db_host, db_user, db_pass) or die(mysql_error());	    mysql_select_db(db_name) or die(mysql_error());    }   	 function process()    {	    try	    {  		   		    if(!$this->IsTokenValid())			    throw new Exception('Invalid Form Submission.');					   		    if(!empty($this->_imageName)) {		   			    if(!$this->IsImageValid())				    throw new Exception ('Image is not a valid ext.');			   		   			    if(!$this->UploadImage())				    throw new Exception('Error uploading your avatar.');		   			    if(!$this->SaveImage())				    throw new Exception('Error saving your avatar');			   		    }		   		    if(!$this->Save())			    throw new Exception('Error Saving profile.');		   		    if(!$this->UpdateProfileDate())			    throw new Exception('Error updating profile date.');		   		   		    return true;	   	    }	    catch(Exception $e)	    {		    $this->_errors[] = $e->getMessage();		    return false;	    }    }       function IsTokenValid()    {	  return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 0 : 1;       }       function IsImageValid()    {	    //checks to see if the files ext is in then allowed array, if true, then return true	    return in_array($this->_ext, $this->_allowedext) ? 1 : 0;			       }          function UploadImage()    {  		   @move_uploaded_file($this->_imageTemp, $this->_DestPath);		  		   if (!$this->_imageError === UPLOAD_ERR_OK) {			    throw new UploadException($this->_imageError);			    return false;		   } else {			    return true;		   }		   //return file_exists($this->_DestPath) ? 1 : 0;		      }          function SaveImage()    {	  		  //Get the users current avatar		  $result = mysql_query("select avatar from ".db_prefix."profiles WHERE uid='{$this->_id}'");		  $image = mysql_fetch_array($result);		  //compare it with the default, As long as they don't match. Delete the old one		  if($image['avatar'] != $this->_defaultImage) {		    unlink($this->imagePath.$image['avatar']);		  }		  //Then update the database	 		  mysql_query("UPDATE ".db_prefix."profiles SET avatar='{$this->_newName}' WHERE uid='{$this->_id}'") or die(mysql_error());			  if(mysql_affected_rows() < 1) {			    $this->_errors[] = 'Theres an error updating your Avatar. : ';			    return false;			  } else			    return true;			     }   	   	 public function filter($var)    {	    return preg_replace('/[^a-zA-Z0-9\s]/','',$var);	       }	      function Save()    {	    self::_DbConnect();													  	    mysql_query("UPDATE ".db_prefix."profiles SET age='{$this->_uage}', birthdate='{$this->_birthdate}', birthsign='{$this->_birthsign}', homepage='{$this->_homepage}', location='{$this->_location}', icq='{$this->_icq}', msn='{$this->_msn}', yahoo='{$this->_yahoo}', country='{$this->_country}', hobbies='{$this->_hobbies}', music='{$this->_music}', updated='".mktime()."' WHERE uid={$this->_id}") or die(mysql_error());	   	    if(mysql_affected_rows() < 1) {		    $this->_errors[] = 'Theres an error updating your profile. : '. mysql_error();		    return false;	    }	    return true;    }       function ShowErrors()    {	    echo '<h4>Errors</h4>';	   	    foreach($this->_errors as $key=>$value)	    echo $value.'<br />';    }       function RandString($length)    {	    $string = "";	    $characters = "1234567890abcdefghijklmnopqrstuvwxyz";	   	    for($x = 0;$x<$length;$x++) {	    $string .= $characters[mt_rand(0,strlen($characters) -1)];	    }	    return $string;    }       function UpdateProfileDate()    {	    self::_DbConnect();	   	    mysql_query("UPDATE ".db_prefix."profiles SET updated='{$this->todayIs}'") or die(mysql_error());	   	    if(mysql_affected_rows() < 1) {		    $this->_errors[] = 'Theres an error updating your profile date. : ';		    return false;	    }	    return true;    }       function ShowResults()    {	    if(!empty($this->_imageName)) {		    echo 'Image File Name : '.$this->_imageName.'<br />';	   		    echo 'Image Size : '.$this->_imageSize.' bytes<br />';		    echo 'Any Errors : '.$this->_imageError.'<br />';	    }    }}?> 

Link to comment
Share on other sites

I'm getting all empty values back from all of them . If you look in the constructer. The 6th line down is where it starts at. .

Link to comment
Share on other sites

							$this->fileName = $_FILES['imagefile']['name'];					$this->fileTemp = $_FILES['imagefile']['tmp_name'];					$this->fileSize = $_FILES['imagefile']['size'];					$this->fileError = $_FILES['imagefile']['error'];		  					$this->_imageName = $this->fileName;					$this->_imageSize = $this->fileSize;					$this->_imageTemp = $this->fileTemp;					$this->_imageError = $this->fileError; 

If I try to use a private variable on this. I get a empty value returned. If I use it like this private $_imageName $this->_imageName = $_FILES['image']['name']; Then I get an empty string value back from the variable

Link to comment
Share on other sites

Sorry, You must have missed that part. Look all the way down at the bottom. Show_results(); This shows the results after the class has been completed. There all so the profile.php page that runs it when the user clicks a button to update their profile.

$profile = new Profile();if($profile->process())echo 'Update completed'else$profile->ShowErrors(); $profile->ShowResults();

Link to comment
Share on other sites

Well it does, I went a head and posted them below for you

function ShowErrors()    {		    echo '<h4>Errors</h4>';		   		    foreach($this->_errors as $key=>$value)		    echo $value.'<br />';    }function ShowResults()    {		    if(!empty($this->_imageName)) {				    echo 'Image File Name : '.$this->_imageName.'<br />';		  				    echo 'Image Size : '.$this->_imageSize.' bytes<br />';				    echo 'Any Errors : '.$this->_imageError.'<br />';		    }    }

Link to comment
Share on other sites

No, it doesn't. "show_errors" and "show_results" are not the same as "ShowErrors", and "ShowResults". If you take my advice and add the error checking code you'll notice PHP telling you exactly that. I'm trying to get you to look at the code more closely and to pay attention to error messages, even showing them if they aren't shown by default.

Link to comment
Share on other sites

Ok, now I see where your confused at. I just type them in wrong, That's all., It does work.

$profile = new Profile();if($profile->process())echo 'Update completed'else$profile->ShowErrors(); $profile->ShowResults();

What I'm confused about is that I have to use public variables in my class and not private variables when getting $_FILES[] info.

Link to comment
Share on other sites

You don't need to use public variables if you're accessing them from inside the class. Private variables are available inside the class, and only inside the class. Public variables are available both from inside the class and from accessing the properties from the object. If you want to access the properties on the object then you need to use public members. If you want to access a private member from the object then you need to have a public method which returns the private variable.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...