..:: MX Studio Fóruns ::..: erro na classe de upload - ..:: MX Studio Fóruns ::..

Jump to content

Publicidade




ATENÇÃO

Para evitar posts desnecessários e que não influam para o andamento e desenvolvimento do fórum, clique aqui e leia todas as regras.
Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

erro na classe de upload kentinha do forno...

#1 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

  Posted 19 December 2008 - 08:24 PM

CÓDIGO
<?php

/**
* @author espiritodocoracao@hotmail.com
* @copyright 2008
*/

class Upload{
    
    public $w;
    public $h;
    public $dir;
    public $type;
    public $file;
    public $resize;
    public $rename;
    public $files;
    public $msg_error;
    public $peso;
    public $peso_msg;
    public $ext_msg;
    public $ext;
    
    protected $error;
    protected $image;
    protected $tipo;
    protected $filetype;
    protected $upload;
    protected $width_orig;
    protected $height_orig;
    protected $imagem;
    protected $imagem_p;
    protected $methodCreateFrom;
    protected $typefile;
    protected $rename_2;
    protected $imagetype;
    protected $upa;
    protected $up;
    protected $pesofile;
    protected $ext_allow;
    
    /** metodo construct faz a verificacao do tipo de arquivo */
    
    public function __construct($file){
        $files = $_FILES["$file"];
        $this->filetype = $files['type'];
        $tipo = explode("/",$this->filetype);
        if($tipo['0'] == 'image'){
            switch($tipo['1']){
                case "jpeg":
                $this->image = "jpeg";
                $this->methodCreateFrom = "imagecreatefromjpeg";
                $this->imagetype = "imagejpeg";
                break;
                case "gif":
                $this->image = 'gif';
                $this->methodCreateFrom = "imagecreatefromgif";
                $this->imagetype = "imagegif";
                break;
                case "png": $image = "png";
                $this->methodCreateFrom = "imagecreatefrompng";
                $this->imagetype = "imagepng";
                break;
                
            }
            return $this->image;
            return $this->imagetype;
            return $this->methodCreateFrom;    
        }    
        
        return $tipo['1'];
        return $tipo['0'];
        
        
              
    }
    
    /** metodo para setar o diretorio de destino */
    
    public function setDir($dir){
        if(!is_dir($dir)){
            $dire = mkdir($dir);
            if(!$dire){
                echo "Diretorio setado inexiste/permissao negada para criacao!";
            }else{
                $this->dir = $dir;
                return $this->dir;
            }
        }
        
    }
    
    /** metodo para setar a largura em caso de redimensionamento */
    
    public function setW($w){
        $this->w = $w;
        return $this->w;
    }
    
    /** metodo para setar a altura em caso de redimensionamento */
    
    public function setH($h){
        $this->h = $h;
        return $this->h;
    }
    
    /** metodo para setar o redimensionamento */
    
    public function setRezise($resize = false){
        return $this->resize;        
    }
    
    /** metodo de validacao das extensoes permitidas */
    
    public function setExtAllowed($ext){
        $this->type = explode("/",$this->files['type']);
        if(is_array($ext)){
            if(in_array($this->tipo['1'],$ext)){
                $this->ext_allow = true;
                $this->ext_msg = '';
            }else{
                $this->ext_allow = false;
                $this->ext_msg = "Extensao de arquivo nao permitido";
            }
        }else{
            if($ext == $this->type['1']){
                $this->ext_allow = true;
                $this->ext_allow = '';
            }else{
                $this->ext_allow = false;
                $this->ext_msg = "Extensao de arquivo nao permitido";
            }
        }
        return $this->ext_allow;
        return $this->ext_msg;
    }
    
    /** metodo para renomear o arquivo*/

    public function Rename($rename = 0){
        // 0 => name
        // 1 => date
        // 2 => thumb_name
        // 3 => thumb_date
        // 4 => uniq
        $typefile = explode(".",$this->files);
        switch($this->rename){
            case '0': $this->rename_2 = implode(".",$this->typefile);
            break;
            case '1': $this->rename_2 = date("d_m_Y_H_i_s").".".$this->typefile['1'];
            break;
            case '2': $this->rename_2 = "thumb_".$this->typefile['0'].".".$this->typefile['1'];
            break;
            case '3': $this->rename_2 = "thumb_".date("d_m_Y_H_i_s").".".$this->typefile['1'];
            break;
            case '4': $this->rename_2 = uniqid(md5($this->typefile['0'])).".".$this->typefile['1'];
            break;
        }
        return $this->rename_2;
    }
    
    /** metodo de validacao do envio do upload */
    
    public function setMsg(){
        $this->error = $this->files['error'];
        switch($this->error){
            case UPLOAD_ERR_OK: $this->msg_error = "Upload feito com sucesso!";
            break;
            case UPLOAD_ERR_INI_SIZE: $this->msg_error = "Arquivo maior que o especificado!";
            break;
            case UPLOAD_ERR_FORM_SIZE: $this->msg_error = "Arquivo maior que o especificado pelo formulario!";
            break;
            case UPLOAD_ERR_PARTIAL: $this->msg_error = "Upload realizado parcialmente!";
            break;
            case UPLOAD_ERR_NO_FILE: $this->msg_error = "Sem arquivo definido para upload!";
            break;
        }
        return $this->msg_error;
    }
    
    /** metodo de validacao do tamanho do arquivo */
    
    public function setPeso($peso){
        if($files['size'] > $peso){
            $this->pesofile = false;
            $this->peso_msg = "Peso acima do permitido!";
        }else{
            $this->pesofile = true;
            $this->peso_msg = "";
        }
        return $this->pesofile;
        return $this->peso_msg;
    }
    
    /** metodo para fazer o upload, utilizando as validacoes */
    
    public function Execute(){
        /** se ha arquivo */
        if($_FILES){
            /** valida o tamanho */
            if(self::setPeso($this->files['name'])){
                /** valida as extensoes permitidas */
                if(self::setExtAllowed($ext)){
                    /** verifica se eh uma imagem */
                    if($this->image == "image"){
                        /** se foi setado para redimensionar a imagem */
                        if($this->resize == true){
                            /** redimensiona */
                            list($width_orig, $height_orig) = getimagesize($this->files['tmp_name']);
                            if ($this->w && ($width_orig < $height_orig)) {
                                $this->w = ($this->h / $height_orig) * $width_orig;
                            } else {
                                $this->h = ($this->w / $width_orig) * $height_orig;
                            }
                            $imagem_p = imagecreatetruecolor($this->w, $this->h);
                            $imagem = $this->methodCreateFrom($this->files);
                            imagecopyresampled($imagem_p, $imagem, 0, 0, 0, 0, $this->w, $this->h, $width_orig, $height_orig);
                            /** upa a imagem redimensionada */
                            $upa = $this->imagetype($imagem_p, $this->dir."/".$this->rename_2, 100);
                            if($upa){
                                /** se upou emite a mensagem */
                                echo self::setMsg();
                            }else{
                                /** se nao upou emite a mensagem */
                                echo self::setMsg();
                            }
                            /** se nao foi setado para redimensionar a imagem, ou seja, enviar do jeito que e */
                        }else{
                            /** valida o tamanho em kb */
                            if(self::setPeso($this->files['name'])){
                                /** valida as extensoes */
                                if(self::setExtAllowed($ext)){
                                    /** upa o arquivo */
                                    $upa = move_uploaded_file($this->files['tmp_name'], $this->dir."/".$this->rename_2);
                                    if($upa){
                                        /** se upou emite a mensagem */
                                        echo self::setMsg();
                                    }else{
                                        /** se nao upou */
                                        echo self::setMsg();
                                    }
                                }
                            }
                        }
                        /** se nao for imagem */
                    }else{
                        /** valida a extensao */
                        if(self::setExtAllowed($ext)){
                            /** valida o tamanho em kb */
                            if(self::setPeso($this->files['name'])){
                                /** upa o arquivo */
                                $upa = move_uploaded_file($files['tmp_name'],$this->dir."/".$this->rename_2);
                                if($upa){
                                    /** se upou emite a mensagem */
                                    echo self::setMsg();
                                }else{
                                    /** se nao upou */
                                    echo self::setMsg();
                                }
                                
                            }else{
                                echo $this->peso_msg;
                            }
                        }
                    }
                }
            }
        }
    }
}

?>


acabei de criar esta classe, mas nao esta funcionando, nem emitindo mensagem de erro...

como resolver...?
0

#2 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 22 December 2008 - 11:40 AM

o código éh um pouquinho grande, deu preguiça de ler ele todo, então vai uma dica, procure pela linha error_reporting no seu php.ini e ponha o valor E_ALL que o PHP vai mostrar qualquer frecuragenzinha que tiver de errado, até uma variável não inicializada que você tentar acessar geraria erro, quam sabe assim... Então se mesmo assim não der em nada, avisa!

Deve ficar mais ou menos assim:
error_reporting = E_ALL

Ou você pode colocar na primeira linha do arquivo o comando
error_reporting(E_ALL);

Já que a primeira opção vai fazer isso ser válido pra qualquer arquivo.
0

#3 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 22 December 2008 - 05:01 PM

mostrou 4 erros, 2 eu consertei, outros 2 eu nao entendi


QUOTE
Notice: Undefined variable: files in C:\AppServ\www\ajax\class.upload.php on line 185

Notice: Undefined variable: class in C:\AppServ\www\ajax\class.html.php on line 103


a classe class.html.php eh esta



CÓDIGO
<?php

/**
* @author
* @copyright 2008
*/

class Html{
    
    var $label;
    Var $id_field;
    var $method;
    var $action;
    var $text;
    var $address;
    var $element;
    var $cols;
    var $rows;
    var $enctype;
    var $type;
    var $value;
    var $class;
    var $js;
    var $selected;
    var $values = array();
    var $labels = array();
    var $content;
    var $width;
    var $heigth;
    var $border;
    var $cellsp;
    var $cellpd;
    var $cell = array();
    
    function AddTextField($id_field, $type = "text", $value = "", $class = ""){
        
        switch($type){
            case "text":
        $this->TextField ="<input class=\"".$class."\" type=\"text\" name=\"".$id_field."\" id=\"".$id_field."\" value=\"".$value."\" /></br>";
        break;
        case "hidden":
        $this->TextField ="<input class=\"".$class."\" type=\"hidden\" name=\"".$id_field."\" id=\"".$id_field."\" value=\"".$value."\"/></br>";
        break;
        case "pass":
        $this->TextField ="<input class=\"".$class."\" type=\"password\" name=\"".$id_field."\" id=\"".$id_field."\" value=\"".$value."\"/></br>";
        break;
        case "file":
        $this->TextField ="<input class=\"".$class."\" type=\"file\" name=\"".$id_field."\" id=\"".$id_field."\"  value=\"".$value."\"/></br>";
        break;
        
        }
        return $this->TextField;
        
    }
    
    function AddLink($text, $address, $class = "", $js = ""){
        $this->Link = "<a class=\"".$class."\" href=\"".$address."\" ".$js.">".$text."</a>";
        return $this->Link;
    }
    
    function AddTextArea($id_field, $class = "", $cols = 45, $rows = 5){
        $this->TextArea = "<textarea name=\"".$id_field."\" id=\"".$id_field."\" cols=\"45\" rows=\"5\"></textarea>";
        return $this->TextArea;
        
    }
    
    function AddLabel($text, $element, $class = ""){
        $this->Label = "<label></br>".$text.": ".$element."</label></br>";
        return $this->Label;
    }
    

    /**
     * Seta a pagina para acion do form
     */
    
    function SetAction($action){
        $this->action  = $action;
        return $this->action;
        
    }
    
    function SetEnctype($enctype = 2){
        switch($enctype){
            case 0:
            $this->enctype = "multipart/form-data";
            return $this->enctype;
            break;
            case 1:
            $this->enctype = "application/x-www-form-urlencoded";
            return $this->enctype;
            break;
            case 2:
            $this->enctype = "";
            return $this->enctype;
            break;
        
        }
        
    }
    
    function SetButton($name, $value){
        $this->Button = "<input class=\"".$class."\" type=\"submit\" name=\"".$name."\" id=\"".$name."\" value=\"".$value."\" />";
        return $this->Button;
    }
    
    function SetMethod($method = "post"){
        switch($method){
            case "post":
            $this->method = "POST";
            return $this->method;
            break;
            case "get":
            $this->method = "GET";
            return $this->method;
            break;
        }
    }
    
    function AddCheckBox($id_field,$value = "",$class=""){
        return  "<input name=\"".$id_field."\" type=\"checkbox\" id=\"".$id_field."\" value=".$value." />";
    }
    
    
        function CreateForm($name, $element, $class = ""){
    $this->Form = '<form action="'.$this->action.'" method="'.$this->method.'" enctype="'.$this->enctype.'" name="'.$name.'" id="'.$name.'">';
if(is_array($element)){
for ($a = 0;$a<=sizeof($element); $a++) {
     $this->Form .=  $element[$a]."<br>";
}
}else{
    $this->Form .= $element;
}
$this->Form .= "</br>".$this->Button."</br>";
$this->Form .= "</form>";
return $this->Form;
        
    }
    function AddSelect($id_field,$labels,$values,$class = "",$selected = ""){
        if(count($labels) != count($values)){
            echo "Erro no select!";
        }else{
        $this->select =  "<select name=\"".$id_field."\" id=\"".$id_field."\">";
        for($s = 0; $s < sizeof($labels) && $s < sizeof($values); $s++){
            $this->select .= "<option value=\"".$values[$s]."\">".$labels[$s]."</option>";
        }
        $this->select .="</select><br>";
        return $this->select;  
        }
    }    
    function OpenTable($id_field,$width, $heigth = "",$border="0",$cellsp="0",$cellpd="0", $class = ""){
        return "<table id=\"".$id_field."\" width=\"".$width."\" height=\"".$heigth."\" border=\"".$border."\" cellspacing=\"".$cellsp."\" cellpadding=\"".$cellpd."\" class=\"".$class."\" ><br>\n";
    }
    
    function CloseTable(){
        return "</table><br>\n";
    }
    
    function CreateLineTable($id_field,$cell,$class = ""){
        if(is_array($cell)){
        $this->tr = "<tr id=\"".$id_field."\" class=\"".$class."\">\n";
        for($c = 0; $c <= count($cell); $c++){
            $this->tr .= $cell[$c];
        }
        $this->tr .= "</tr>\n";
        }else{
            $this->tr = "<tr id=\"".$id_field."\" class=\"".$class."\">".$cell."</tr>\n";
        }
        return $this->tr;
        
    }
    
    function CreateCellTable($id_field,$content,$width = "",$heigth="",$class = ""){
        return "<td id=\"".$id_field."\" class=\"".$class."\">".$content."</td>\n";
    }
    
}

?>

0

#4 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 22 December 2008 - 05:22 PM

Isto quer dize que a variável não está definida, acho que você neste caso queria acessar a variável da classe, mas usou $files ao invés de $this->files e $class ao invés de $this->class:
CÓDIGO
function SetButton($name, $value){
        $this->Button = "<input class=\"".$class."\" type=\"submit\" name=\"".$name."\" id=\"".$name."\" value=\"".$value."\" />";
        // Na linha acima, procure por $class, deveria estar $this->class
        return $this->Button;
}
Como você não disse nada, consederei que o primeiro arquivo que você mostrou era o C:\AppServ\www\ajax\class.upload.php, localizei assim:
CÓDIGO
public function setPeso($peso){
        if($files['size'] > $peso){
            // Dá uma  olhada dentro do if, está $files onde deveria estar $this->files
            $this->pesofile = false;
            $this->peso_msg = "Peso acima do permitido!";
        }else{
            $this->pesofile = true;
            $this->peso_msg = "";
        }
        return $this->pesofile;
        return $this->peso_msg;
}

0

#5 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 22 December 2008 - 05:48 PM

consertei, nao mostra nenhuma mensagem de erro....porem nao faz o upload....
0

#6 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 23 December 2008 - 01:04 PM

Mostra o código que você usa pra construir o objeto (inicializar a classe), vendo ele vai ficar mais fácil ver o que pode ser.
0

#7 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 24 December 2008 - 09:47 AM

eu to usando as duas classes assim....


CÓDIGO
<?php



include("class.html.php");
include("class.upload.php");

$upload = new Upload('upload');
$upload->setDir("teste");
$upload->Rename(0);
$upload->setRezise();
$upload->setExtAllowed(array("jpeg", "gif"));
$upload->setPeso(253659);
$upload->Execute();

$html_upload = new Html();
$html_upload->SetAction($_SERVER['PHP_SELF']);
$html_upload->SetEnctype(0);
$html_upload->SetButton("enviar","Enviar");
$html_upload->SetMethod();

$campo = $html_upload->AddTextField("upload","file");
$arquivo = $html_upload->AddLabel("Arquivo",$campo);
echo $html_upload->CreateForm("upload",$arquivo);
?>

0

#8 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 26 December 2008 - 04:32 PM

Logo no começo do código, repare isso:
CÓDIGO
public function __construct($file){
        $files = $_FILES["$file"];

Em seguida, nos outros métodos você tenta acessar $this->files, mas no construtor você não faz nenhuma associação entre $files e $this->files, não cheguei a testar, mas talvez se você corrigir isso dê certo, já que você faz o acesso através de $this->files ao invés de $_FILES.
0

#9 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 26 December 2008 - 06:57 PM

fiz a alteracao sem sucesso..... =/
0

#10 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 26 December 2008 - 11:03 PM

Verifique todo o seu código, podem haver ocorrencias semelhantes...
0

#11 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 27 December 2008 - 11:33 AM

ja verifiquei....
0

#12 User is offline   Wanderson Regis 

  • Group: Moderadores
  • Posts: 1275
  • Joined: 10-January 05

Posted 29 December 2008 - 11:58 AM

No arquivo que chama as chasses, comente tudo e imprima só a variável $_FILES:
CÓDIGO
<?php
print_r($_FILES);
// Pra verificar que dados estão sendo recebidos
// Se é que estão sendo recebidos
?>

E no seu formulário está assim a tag FORM: enctype="multipart/form-data"?

Tente também rever a sua classe como um upload simples, e depois que estiver funcionando vai incrementando resursos para que só aceite imagens e etc. Eu particularmente prefiro desenvolver assim, pois posso detectar facilmente onde o erro pode estar, pois se não estava lá, está no que modifiquei.
0

#13 User is offline   Igor de Paula 

  • Group: Membros
  • Posts: 449
  • Joined: 25-March 06

Posted 29 December 2008 - 02:28 PM

no form esta td certo....mas vou redezenvolve-la como vc disse....obrigado pela paciencia, em outro forum, zombaram de mim....mas obrigado mesmo...
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic


Similar Topics Collapse

  Topic Forum Started By Stats Last Post Info
New Replies testando mysql
erro
MySQL Only Dust 
  • 2 Replies
  • 3238 Views
New Replies UHUU todo mundo errou
viviane a vencedora
O Aprendiz Tygra 
  • 1 Reply
  • 4403 Views
New Replies Erro de Javascript no Ff, no IE tudo ok. Web Standards Philippe Dias 
  • 3 Replies
  • 1637 Views
New Replies Classe Key. Iniciando estudos...
"Pegar" a ativação do CAPSLOCK
Flash & ActionScript Cassiano Óliver 
  • 2 Replies
  • 1402 Views
New Replies Maioria da classe C terá banda larga em 2020 Notícias Notícias 
  • 0 Replies
  • 150 Views
New Replies Erro no Login
Wamp Server
MySQL skyphill 
  • 2 Replies
  • 1122 Views
New Replies Error #2038
Alguém já resolveu esse problema?
Flex poste9 
  • 0 Replies
  • 2165 Views
New Replies erro no msn windows live..
me ajudem por favor..
Dúvidas Gerais Igor [-)IsN_IP(-] 
  • 3 Replies
  • 1764 Views

Publicidade




2 User(s) are reading this topic
0 membro(s), 2 visitante(s) e 0 membros anônimo(s)