Jump to content

Var Error In A Class


GD77
Go to solution Solved by GD77,

Recommended Posts

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

 

At the time you declare the variable/property, you cannot assign it a variable value. Only fixed values, like a constant, number, string, empty array, or an array containing fixed values can be used in the declaration line. To assign a variable value, you need to assign it using php code in the constructor or in a class method.

 

Edit: Also, you should not use the var keyword in php5. You should only use public, protected, and private. Php5 treats the var keyword as public.

Edited by PFMaBiSmAd
more info
Link to comment
Share on other sites

ok this is what I m trying to do... the script works fine outside a class Function, once inside a class... nothing.. cold DEAD and no errors I know it must be something stupid yet can t see it :sweat:

 

function img_Check() {
if(isset($_POST['btn_sub'])){

 $image=$_FILES['image']['name'];

 if(file_exists($this->dire.$image)){
  echo "shitz"; echo $image;echo "<br>"; echo $this->dire;
 }else{
  if (!empty($image) && $image!==NULL){
   $filename = stripslashes($_FILES['image']['name']);
   $extension = getExtension($filename);
   $extension1 = strtolower($extension);

  if (($extension1 !== "jpg") && ($extension1 !== "jpeg") && ($extension1 !== "png") && ($extension1 !== "gif")){
   echo '<h1>Unknown extension!</h1>';
   $err_img=true;
   }else{
 $size=filesize($_FILES['image']['tmp_name']);
 if ($size > MAX_SIZE*1024){
 echo '<h1>You have exceeded the size limit!</h1>';
 $err_img=true;
 }else{
  //we will give an unique name, for example the time in unix time format
  $image_name=strtolower($image);
  //the new name will be containing the full path where will be stored (images folder)
  $newname=$this->dire.$image_name;
  //we verify if the image has been uploaded, and print error instead
  $copied = copy($_FILES['image']['tmp_name'], $newname);
  list($width, $height) = getimagesize($dire.$image);

  echo $image." width=".$width." height=".$height;

  if (!$copied){ echo '<h1>Copy unsuccessfull!</h1>';
  $err_img=true;
  }
 }
   }
  }
 }
}
}/*END Fn img_Check*/

Link to comment
Share on other sites

Further to the above reply, you only use the public, var (php4), protected, and private keywords when defining CLASS variables/properties. You don't use them for variables you use inside of a class function/method, that are local only to that function/method.

 

Your $image=$_FILES['image']['name']; php statement isn't defining a class variable/property. It's a php assignment statement inside your img_Check() function.

 

If you actually wanted the $image variable to be a CLASS variable/property, you would define it and reference it as follows -

 

public $image;

 

$this->image = $_FILES['image']['name'];

Edited by PFMaBiSmAd
fixed wording
Link to comment
Share on other sites

function img_Check() {
if(isset($_POST['btn_sub'])){
 $this->image = $_FILES['image']['name'];

 if(file_exists($this->dire.$this->image)){
  echo "shitz"." / ".$this->image." / ".$this->dire;
  }else{
   if (!empty($this->image) && $this->image!==NULL){
 $this->filename = stripslashes($_FILES['image']['name']);
 $this->extension = $this->getExtension($this->filename);
 $this->extension = strtolower($this->extension);

 if (($this->extension !== "jpg") || ($this->extension !== "jpeg") || ($this->extension !== "png") || ($this->extension !== "gif")){
  echo '<h1>Unknown extension!</h1>';
  return $err_img=true;
  }else{
   $this->size=filesize($_FILES['image']['tmp_name']);
   if ($this->size > $this->MAX_SIZE*1024){
    echo '<h1>You have exceeded the size limit!</h1>';
    return $err_img=true;
    }else{
	 //we will give an unique name, for example the time in unix time format
	 $this->image_name=strtolower($this->image);
	 //the new name will be containing the full path where will be stored (images folder)
	 $this->newname=$this->dire.$this->image_name;
	 //we verify if the image has been uploaded, and print error instead
	 $this->copied = copy($_FILES['image']['tmp_name'], $newname);

	 list($this->width, $this->height) = getimagesize($this->dire.$this->image);

	 echo $this->image." width=".$this->width." height=".$this->height;

	 if (!$this->copied){
	  echo '<h1>Copy unsuccessfull!</h1>';
	  return $err_img=true;
	 }
    }
  }
   }
  }
}

 

BTW m calling the img_Check() inside another Fn $this->img_Check();

whether I called it or no or just used the script in another function ... still get no response nothing no matter what

Link to comment
Share on other sites

ok Fixed thanks a lot :

PFMaBiSmAd

 

here s the main issues:

 

1- enctype='multipart/form-data' was type='...'

2- As ou mentioned dropped the var... and used private.. then used $this->image Don t know why did not see that I m using it in other Functions

3- $_FILES['img_Up']['name'].... was using 'image' and it is img_UP from the form input name.

4- this is the code if anyone else needed it.

function img_Check() {
if(isset($_POST['btn_sub'])){
 $this->image = $_FILES['img_Up']['name'];

 if(file_exists($this->dire.$this->image)){
  echo "Image Already Exists"." / ".$this->image." / ".$this->dire;
  }else{
   if (!empty($this->image) && $this->image !== NULL){
 $this->filename = $_FILES['img_Up']['name'];
 $this->extension = $this->getExtension($this->filename);
 $this->extension = strtolower($this->extension);

 if (($this->extension !== "jpg") && ($this->extension !== "jpeg")){
  echo '<h1>Unknown extension!</h1>';
  return $err_img=true;
  }else{
   $this->size=filesize($_FILES['image']['tmp_name']);
   if ($this->size > $this->MAX_SIZE*1024){
    echo '<h1>You have exceeded the size limit!</h1>';
    return $err_img=true;
    }else{
	 //we will give an unique name, for example the time in unix time format
	 $this->image_name=strtolower($this->image);
	 //the new name will be containing the full path where will be stored (images folder)
	 $this->newname=$this->dire.$this->image_name;
	 //we verify if the image has been uploaded, and print error instead
	 $this->copied = copy($_FILES['img_Up']['tmp_name'], $this->newname);

	 list($this->width, $this->height) = getimagesize($this->dire.$this->image);

	 echo $this->image." width=".$this->width." height=".$this->height;

	 if (!$this->copied){
	  echo '<h1>Copy unsuccessfull!</h1>';
	  return $err_img=true;
	 }
    }
  }
   }
  }
}

 

one more thing please... is their away to keep the file name in the upload input tag like doing in other type of inputs? while validating other parts of the form

Link to comment
Share on other sites

There are numerous problems with your code, starting with the fact that I got a parse error when I copied it. You're missing a closing bracket at the end, a situation brought by poor indenting and unnecessarily nesting code.

You have utilized the "exit early" principle a few times in the code, but still nested the alternative code path in a completely superfluous else-block. There's also the case of not validating that you're actually working with a picture, the random order of which you're checking things, code which has nothing to do with the image (or it's checking) at all, seemingly random return values, the unused assignments in the return statements, rampant use of class members and more.

 

In short, your code is a complete mess, and the fact that it's working* is pure coincidence.

 

That's why I've taken the liberty to clean up your code a bit, but there's still some more work needed on it.

public function img_Check () {
   $this->filename = $_FILES['img_Up']['name'];

   $this->size = filesize ($_FILES['image']['tmp_name']);
   if ($this->size > $this->MAX_SIZE * 1024) {
       $this->error = 'You have exceeded the size limit!';
       return false;
   }

   $this->image = $_FILES['img_Up']['name'];

   if (file_exists ($this->dire . $this->image)) {
       $this->error = "Image Already Exists" . " / " . $this->image . " / " . $this->dire;
       return false;
   }

   if (empty ($this->image) || $this->image === NULL) {
       $this->error = 'No valid image found.';
       return false;
   }

   $this->extension = $this->getExtension ($this->filename);
   $this->extension = strtolower ($this->extension);

   if (($this->extension !== "jpg") && ($this->extension !== "jpeg")) {
       $this->error = 'Unknown extension!';
       return true;
   }

   // CF: Validate that the file given is indeed a picture.
   list ($this->width, $this->height) = getimagesize ($this->dire . $this->image);
   if (!$this->width) {
       $this->error = 'Not a valid picture';
       return false;
   }

   // CF: Comment does not correlate to reality.
   // We will give an unique name, for example the time in unix time format
   $this->image_name = strtolower ($this->image);

   // The new name will be containing the full path where will be stored (images folder)
   $this->newname = $this->dire . $this->image_name;

   // We verify if the image has been uploaded, and print error instead
   if (!$this->copied = move_uploaded_file ($_FILES['img_Up']['tmp_name'], $this->newname)) {
       $this->error = 'Could not copy image.';
       return false;
   }

   // CF: Why is this here, what does it do?
   $this->attributes = $this->image . " width=" . $this->width . " height=" . $this->height;

   return true;
}

 

In addition to the comments I've added in the code, you also need to:

  • Re-examine your use of class members ($this->variable). If the variable is not used outside of the function, then it should not be a class member. Also, all class members should be defined at the top of the class definition, with proper scoping.
  • Add checks for errors in the uploading itself, and not just of the max file size is too big.
  • Rewrite all of your code to stop using echo (and similar) in the middle of a class method. This is horribly horribly wrong when working with OOP. Take an example from the error member I've added to your code, and research proper OOP syntax.
  • Start to plan your code before you begin writing code, and pay attention to everything you do.
  • Read this post.

 

*Your code may not actually be working, but only seem that way because of your lack of understanding. As noted in the articles I linked to in my post I linked you to at the bottom here.

Edited by Christian F.
Link to comment
Share on other sites

I get when u said don t use echo or print inside a Method but what you ll do when u need to use a form inside and you don t want to use include()... so their s no way to totally avoid the use of print or echo inside of a Method unless you can suggest other way.

Link to comment
Share on other sites

I get when u said don t use echo or print inside a Method but what you ll do when u need to use a form inside and you don t want to use include()... so their s no way to totally avoid the use of print or echo inside of a Method unless you can suggest other way.

 

CF already showed you how. As you can see he populates $this->error with the exact error message. To display it simply:

 

if ($myClass->error) {
   echo $myClass->error;
}

 

A few frameworks provide classes that you can use to do these tidy tasks for you, for example Zend has a Transfer object to download or upload a file. An off-the-bat example would be:

 

namespace MyApp;

use Zend\File\Transfer\Transfer;

class FileUploadService
{
 const UPLOAD_FILE = 'file';
 const UPLOAD_IMAGE = 'image';

 public function phpFilesArrayUpload($name, $destination, $type = self::UPLOAD_FILE)
 {
   if (!is_string($name)) {
     throw new InvalidArgumentException(__CLASS__ ."::". __METHOD__ ." expected a string, got ". gettype($name));
   }

   if (!isset($_FILES[$name])) {
     throw new InvalidArgumentException("Invalid upload name '$name' specified");
   }

   try {
     $transfer = new Transfer();
     $transfer->setDestination($destination);

     if ($type === self::UPLOAD_FILE) {
       //$transfer->setValidator(); ..
     } else if ($type === self::UPLOAD_IMAGE) {
       //$transfer->setValidator(); ..
     }

     return $transfer->receive($_FILES[$name]);
   } catch (Exception $e) {
     throw new DomainException($e->getMessage(), 0, $e);
   }
 }
}

 

Usage would be like this:

 

try {
 $service = new FileUploadService();
 $service->phpFilesArrayUpload('img_Up', 'path/to/upload/to', $service::UPLOAD_IMAGE);
} catch (Exception $e) {
 echo $e->getMessage();
}

Link to comment
Share on other sites

list ($this->width, $this->height) = getimagesize($this->dire.$this->image);

 

Warning: getimagesize(......) [function.getimagesize]: failed to open stream: No such file or directory in...

 

how to fix this since the img is not uploading or moved the the dir... it s normal to get that error and when I remove $this->dir from getimagesize() you ll still get that warning

Link to comment
Share on other sites

Forgot to change that when I moved it, apparently. It's now pointing to location where the file will reside after it's been moved, but the move doesn't happen until later. Just update the path to the correct location, and you're set.

Also, you should probably add a check to see if the file actually exists, before trying to open it. Should help prevent that warning, should the file be non-existent for some reason.

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.