Jump to content

Question about uploading files using OOP


eldan88
Go to solution Solved by DHood,

Recommended Posts

Hi,

 

 Everytime I try uploading a file I get my custom error message that says "No file was uploaded" when I try uploading a file. Below is the code class I created to process that upload and below is that actual page that does the uploading. I have put the comment where i wrote the code for my custom error message keeps showing. 

 

Any suggestions? Thanks ::)

<?php
//$target_path = /Applications/XAMPP/xamppfiles/htdocs/photo_gallery/uploads

require_once('database.php');
require_once('database_object.php');
require_once('user.php');

class Photograph extends database_object  {
	protected static $table_name = "photographs";
	protected static $db_fields=array('id','filename','type','size','caption');
	public $id;
	public $filename;
	public $type;
	public $caption;
	public static $max_file_size = 1048576;
	
	private $tmp_path; // the temp path
	protected $upload_dir ="images"; // The upload directory
	protected $target_path = "/Applications/XAMPP/xamppfiles/htdocs/photo_gallery/uploads";
	public $errors = array(); // This will take all the errors that has happened while trying to upload the file. 
	
protected $upload_errors =  array(
UPLOAD_ERR_OK => "No Errors",
UPLOAD_ERR_INI_SIZE => "Larger than upload file size",
UPLOAD_ERR_FORM_SIZE => "Larger than from max upload size", 
UPLOAD_ERR_PARTIAL => "Partial upload",
UPLOAD_ERR_NO_FILE => "No File",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory",
UPLOAD_ERR_CANT_WRITE => "Can't Write to disk",
UPLOAD_ERR_EXTENSTON => "File Upload stopped by extension"
);
	

//Pass in $_FILE(['upload_file']) as an argument 

public function attach_file ($file) { 
	if(!$file || empty($file) || !is_array($file)) {
		$this->errors[] = "No file was uploaded"; // Always shows me this error when trying to upload
		return false; } elseif($file['error'] !=0) {
			//error: report what php says went wrong
			$this->errors[] = $this->upload_errors[$file['error']];
			return false;
		} // end of elseif
		else {
	$this->tmp_path = $file['temp_name'];
	$this->filename = basename($file['name']);
	$this->type = $file['type'];
	$this->size = $file['size'];
	return true;
	
		}// End of else statment
	
}// end of attach file function
	

Here is the actual page that I am trying to do the upload. 

<?php ob_start();
require_once('../../includes/functions.php');
require_once('../../includes/user.php');
require_once('../../includes/photograph.php');
require_once('../../includes/session.php');

//if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php 
$max_file_size = Photograph::$max_file_size;// 1048576

$message = "";
if(isset($_POST['submit'])) {
	$photo = new Photograph();
	$photo->caption = $_POST['caption'];
	$photo->attach_file($_FILES['file_upload']);
	if($photo->save()) {
	//Success
	$message = "Photograph upload successfully";
	} else {
		$message = join("<br />",$photo->errors);
	// Fail	
	}
}

?>

<?php include_layout_template('admin_header.php'); ?>
<h2> Photo Upload </h2>
<?php echo output_message($message); ?>
<form action="photo_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<p><input type="file" name="file_upload" /> 
<p> <input type="text" name="caption" value="" />
<input type="submit" name="submit" value="upload" />
</form>

<?php ob_end_flush(); ?>
<?php include_layout_template('admin_footer.php'); ?>
		

Link to comment
Share on other sites

You need to learn how to debug code. There is a single if() condition that would cause that error. That condition does three different checks against the value passed to the method. So, do a var_dump() of that value to see what is actually contains.

 

    if(!$file || empty($file) || !is_array($file)) {
        var_dump($file); //Debug line
        $this->errors[] = "No file was uploaded"; // Always shows me this error when trying to upload

 

Then, if the value is not what you expect verify the value before it is passed into the function using the same process.

Link to comment
Share on other sites

You need to learn how to debug code. There is a single if() condition that would cause that error. That condition does three different checks against the value passed to the method. So, do a var_dump() of that value to see what is actually contains.

    if(!$file || empty($file) || !is_array($file)) {
        var_dump($file); //Debug line
        $this->errors[] = "No file was uploaded"; // Always shows me this error when trying to upload

Then, if the value is not what you expect verify the value before it is passed into the function using the same process.

 

Hey. I did a var_dump like you mentioned, however after I have uploaded the file, it doesn't show anything at all.

Link to comment
Share on other sites

One question only.

 

Is "/Applications" a web root directory or is a absolute path points to the web root?   

Jazzman,

 I'm really sorry, I am new at this. The website is hosted on my local machine. Not a remote serever. What do you mean by an "absolute path points to the web root?

 

"

Link to comment
Share on other sites

What - exactly - do you mean it doesn't show anything at all. Are you not getting the error message you were getting before?

 

I am getting the same error message, however var_dump doesn't show any value that is assigned to $files. I think there is something wrong with the last else statement on my attach_file method. Here is the full photograph class below, maybe you can help me find the issue?

<?php
//$target_path = /Applications/XAMPP/xamppfiles/htdocs/photo_gallery/uploads

require_once('database.php');
require_once('database_object.php');
require_once('user.php');

class Photograph extends database_object  {
	protected static $table_name = "photographs";
	protected static $db_fields=array('id','filename','type','size','caption');
	public $id;
	public $filename;
	public $type;
	public $caption;
	public static $max_file_size = 1048576;
	
	private $tmp_path; // the temp path
	protected $upload_dir ="images"; // The upload directory
	protected $target_path = "/Applications/XAMPP/xamppfiles/htdocs/photo_gallery/uploads";
	public $errors = array(); // This will take all the errors that has happened while trying to upload the file. 
	
protected $upload_errors =  array(
UPLOAD_ERR_OK => "No Errors",
UPLOAD_ERR_INI_SIZE => "Larger than upload file size",
UPLOAD_ERR_FORM_SIZE => "Larger than from max upload size", 
UPLOAD_ERR_PARTIAL => "Partial upload",
UPLOAD_ERR_NO_FILE => "No File",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory",
UPLOAD_ERR_CANT_WRITE => "Can't Write to disk",
UPLOAD_ERR_EXTENSTON => "File Upload stopped by extension"
);
	

//Pass in $_FILE(['upload_file']) as an argument 


	 public function attach_file($file) {
		// Perform error checking on the form parameters
		if(!$file || empty($file) || !is_array($file)) {
		  // error: nothing uploaded or wrong argument usage
		  $this->errors[] = "No file was uploaded.";
		  return false;
		}elseif($file['error'] != 0) {
		  // error: report what PHP says went wrong
		  $this->errors[] = $this->upload_errors[$file['error']];
		  return false;
		} // end of elseif
		
		
		else {
	$this->tmp_path = $file['tmp_name'];
	$this->filename = basename($file['name']);
	$this->type = $file['type'];
	$this->size = $file['size'];
	return true;
	
		}// End of else statment
	
}// end of attach file function
	
public function save() {
	// A new record won't have an id yet
	if(isset($this->id)) {
		// Really just to update the caption
	parent::update(); 	
	} else {
		if(!empty($this->errors)) { return false;}
		if(strlen($this->caption) >= 255) {
			$this->errors[] = "The caption can only be 255 charachter long";
			return false;
			}
			
			if(empty($this->filename) || empty($this->temp_path)) {
			$this->errors[] = "The file name is not available";
			return false;	
			}
			
			
			
			if(file_exists($target_path)) {
				$this->errors = "This {$this->filename} already exists!";
				return false; 
			}
			
			if(move_uploaded_file($this->temp_path,$this->target_path)) {
			// Success	
			if(parent::create()) {
				//We are done with the temp path thats why it isn't there anymore. 
			unset($this->temp_path);
			return true;	
				
			}
			} else {
				$this->errors[] = "The file upload failed, possibly due to incorrect permessons on the upload folder";
				return false;
			}
		 
			 
		
		}// end of else statement
	}// End of function save
	
} // End of class


?>

 

Link to comment
Share on other sites

since the $_POST array is apparently set, it's highly unlikely that the $_FILES array will be empty unless your form is invalid or uploads are not enabled on the server.

 

have you successfully uploaded ANY file on this server?

 

what does the output from a phpinfo() statement show for the file_uploads setting?

 

does your form page have other forms on it, possibly breaking the <form> tag you did show? what is the complete 'view source' of the form page?

Link to comment
Share on other sites

Jazzman,

 I'm really sorry, I am new at this. The website is hosted on my local machine. Not a remote serever. What do you mean by an "absolute path points to the web root?

 

"

 

Just create a simple file for instance - test.php inside the /uploads folder and put down next:

 

// current directory

echo getcwd() . "\n";

 

Because, I'm thinking that the path to this folder is incorrect. 

 

What is the web root directory on the machine? Is it a htdocs or something else?

 

Also, what permissions has this folder? 

 

Do you know how to check this?

Link to comment
Share on other sites

What - exactly - do you mean it doesn't show anything at all. Are you not getting the error message you were getting before?

 

Phsyco,

 

I found out what the issue was! It was a small typo. I had a condition that had the following

if(empty($this->filename) || empty($this->temp_path)) {

            $this->errors[] = "The file name is not available";

            return false;    

            }

 

The attribute above "$temp_path" was misspelled. It was missing the "e". I corrected it and that solved the issue.

 

After that worked, I encountered another problem. I am trying to create an entry in my database, on the details of $_FILES.

 

I tried using the parent::create() method  on my photograph class i mentioned on my last post, after the file has been successully moved.

but then I got an error with the following..

Fatal error: Access to undeclared static property: database_object::$db_fields in /Applications/XAMPP/xamppfiles/htdocs/photo_gallery/includes/database_object.php on line 70

 

What does that mean?

 

The create() method is called from my parent class database_object. I put a comment where line 70 is. The comment reads "Line 70" Any ideas on how to fix this? Thanks

 

Database object parent class:

<?php 

class database_object {
	
    
    public static function find_all() {
		return self::find_by_sql("SELECT * FROM users");
  }
  
  
  public  function find_by_id($id=0)  { // Takes an ID as an argument
    $result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1"); 
		return !empty($result_array) ? array_shift($result_array): false;
  }
  
  public static function find_by_sql($sql="") {
    global $database; // Brings in the $database instanitated object. 
    $result_set = $database->query($sql); // Runs the query on the $sql argument
    $object_array = array(); // Initilizes an object_array
    while ($row = $database->fetch_array($result_set)) {
      $object_array[] = self::instantiate($row); // Take the inisiated row and assignes it to $object_array
    }
    return $object_array; 
  }

	
		private static function instantiate($record) {
		// Could check that $record exists and is an array
    $object = new self; // Instanciates the user calss to $object
		// Simple, long-form approach:
		// $object->id 				= $record['id'];
		// $object->username 	= $record['username'];
		// $object->password 	= $record['password'];
		// $object->first_name = $record['first_name'];
		// $object->last_name 	= $record['last_name'];
		
		// More dynamic, short-form approach:
		foreach($record as $attribute=>$value){
		  if($object->has_attribute($attribute)) {
		    $object->$attribute = $value;
		  }
		}
		return $object;
	}
	
	private function has_attribute($attribute) {
	  // get_object_vars returns an associative array with all attributes 
	  // (incl. private ones!) as the keys and their current values as the value
	  $object_vars = get_object_vars($this);
	  // We don't care about the value, we just want to know if the key exists
	  // Will return true or false
	  return array_key_exists($attribute, $object_vars);
	}
public function save() {
isset ($this->id) ? $this->update() : $this->create();	
	
}

protected function sanitzed_attriubutes() {
	global $database;
	$clean_attributes = array();
	foreach ($this->attributes() as $key => $value) {
		$clean_attributes[$key] = $database->escape_value($value);
	}
}


protected function attributes() { //Line 70
	$attributes = array();
	foreach(self::$db_fields as $field) {
		if(property_exists($this, $field)) {
			$attributes[$field] = $this->$field;
		}
	}
	return $attributes;
	
}

public function create() {
global $database; 
$attriubutes = $this->sanitzed_attriubutes();
$sql = "INSERT INTO ".self::table_name." (";
$sql .= join(", ", array_keys($attriubutes));
$sql .= ") VALUES ('";
$sql .= join(", ", array_values($attriubutes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true; 	
	
} else {
	
	return false;
}
   
   
   
   }
  
 public function update() {
	global $database; 
	$attributes = $this->sanitzed_attriubutes(); // First we assign the attributes() functions to the $attriubutes variable. 
    //Then we run a foreach on the attriubutes
	foreach ($attributes as $key=>$value) {
	   	$attribute_pairs[] = "{$key}='{$value}'";
	}
	
	$sql = "UPDATE ".self::table_name." SET ";
	$sql .= join(", ", $attribute_pairs);
	$sql .= " WHERE id=" . $this->id; 
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false;
	
	
   }
   
 public function delete() {
   global $database;
	$sql = "DELETE FROM ".self::table_name. " WHERE id=". $this->id . " LIMIT 1";
	$database->query($sql);
	return ($database->affected_rows() == 1) ? true : false; 
	 
   }
   
}// End of Database class
   ?>
   
	
Link to comment
Share on other sites

It means exactly what it says. Do you know what static means? What a property is? What undefined means? If not, you need to do some research. Did you write the code?

Yes i know what all of that means. I just don't know what  "Access to undeclared static property" Its the first  first time I see a message like this.

 

I got the code from a tutorial. The tutorial originally had the database_object all rolled up into the photograph object. I am trying to separate and have the database function in the database_object class, and trying to make it work. Just tying to figure out what it means by "undeclared."

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.