PHP How do I make an image to be the default icon if I do not have an image selected?

0

When a person selects an image they will send the selected one, but if not select choose a pattern. How can I do this?

I was making a code to upload more how can I add this functionality?

$up = new Upload("file");
    if(!is_dir($path)):
            mkdir($path, 0755, true);
    endif;
    $up->setDir( $path )->setExtension( array( 'jpeg','jpg','png', 'gif' ) )->setSize( 2 );
    @$up->upload();

<?php

class Upload 
{    
    private $file = array();    
    public $dir;
    public $extension = array(); 
    public $size;
    public $name = array();

    public function __construct( $file )
    {
        $this->file = $_FILES[ $file ];        
    }

    public function upload()
    {
        $this->checkExtension()->size()->rename();

        if( is_array( $this->file[ "name" ] ) && !empty( $this->file[ "name" ] ) )
        {   
            foreach( $this->file[ "error" ] as $key => $error )
            {
                if( $error == UPLOAD_ERR_OK || !empty( $this->file[ "name" ][ $key ] ) )
                {
                    move_uploaded_file( $this->file[ "tmp_name" ][ $key ], $this->getDir() . $this->file[ "name" ][ $key ] );

                    $this->name[] = $this->file[ "name" ][ $key ];
                }
            }
        }
        elseif( !empty( $this->file[ "name" ] ) )
        {            
            move_uploaded_file( $this->file[ "tmp_name" ], $this->getDir() . $this->file[ "name" ] );
            $this->name[] = $this->file[ "name" ];
        }

        return $this->name;
    }

    public function checkExtension()
    {
        if( is_array( $this->extension ) )
        {
            $extensions = implode( "|", $this->extension );

            if( is_array( $this->file[ "name" ] ) )
            {
                foreach( $this->file[ "name" ] as $key => $val )
                {
                    if( !preg_match( "/.+\.({$extensions})/", $val ) )
                    {
                        $this->file[ "name" ][ $key ] = "";
                    }
                }
            }
            else
            {
                if( !preg_match( "/.+\.({$extensions})/", $this->file[ "name" ] ) )
                {
                    unset( $this->file[ "name" ] );
                }
            }
        }

        return $this;
    }

    public function size()
    {
        $size = $this->convertMbToBt();

        if( is_array( $this->file[ "size" ] ) )
        {
            foreach( $this->file[ "size" ] as $key => $sizes )
            {
                if( $sizes > $size )
                {
                    $this->file[ "name" ][ $key ] = "";
                    $this->file[ "size" ][ $key ] = "";
                }
            }
        }
        else
        {
            if( $this->file[ "size" ] > $size )
            {
                unset( $this->file[ "size" ] );
            }
        }

        return $this;
    }

    private function convertMbToBt()
    {
        $size = $this->getSize() * ( 1024 * 1024 );
        return $size;
    }

    protected function rename()
    {
        if( is_array( $this->file[ "name" ] ) )
        {
            foreach( $this->file[ "name" ] as $key => $val )
            {
                if( !empty( $this->file[ "name" ][ $key ] ) )
                {
                    $exts = preg_split( "[\.]", $this->file[ "name" ][ $key ] );
                    $n = count( $exts ) - 1;            
                    $exts = $exts[ $n ];

                    $this->file[ "name" ] = time() . uniqid() . md5($this->file['name']) . "." . $exts;
                }
                else
                {
                    $this->file[ "name" ][ $key ] = "";
                }
            }
        }
        else
        {
            $exts = preg_split( "[\.]", $this->file[ "name" ] );
            $n = count( $exts ) - 1;            
            $exts = $exts[ $n ];
            $this->file[ "name" ] = time() . uniqid() . md5($this->file['name']) . "." . $exts;
        }

        return $this;
    }

    public function getDir()
    {
        return $this->dir;
    }

    public function setDir( $dir )
    {
        $this->dir = $dir;
        return $this;
    }

    public function getExtension()
    {
        return $this->extension;
    }

    public function setExtension( $extension )
    {
        $this->extension = $extension;
        return $this;
    }

    public function getSize()
    {
        return $this->size;
    }

    public function setSize( $size ) 
    {
        $this->size = $size;
        return $this;
    }

    public function setName( $nomeFim ) 
    {
        $this->size = $size;
        return $this;
    }

}

?>
    
asked by anonymous 20.07.2017 / 15:59

3 answers

1

I think you could do a simple check before calling the upload class, something like:

if (isset($_FILES['arquivo']))
{
  "Executa ação de upload"
}
else
{ 
    "utiliza imagem padrão" caminho/imagem.jpg
}
    
20.07.2017 / 16:47
0

You can do this as follows. Let's use as an example user registration.

For each new user you create, you can associate a default.jpg image already located in your project.

To manage you create a database structure that relates the table of images to that of the user. The image table will have the image name and image path in the project.

When the user uploads his / her photo, save the image in the project and change the path and image name of the user id ( UPDATE ) to the database, thus

p>
UPDATE 
  'imagem' SET 'nome'='perfil.jpg' AND caminho='caminho/salvo/no_projeto/imagem'
WHERE 'id_usuario'= 3;

Regarding the file upload process with PHP

if (isset($_FILES) || isset($_POST['id'])) {
    throw new Exception('Erro ao carregar arquivo');
}

$file = $_FILES;
$user_id = $_POST['id'];

$config = [
    'type_file_allowed' => ['jpeg', 'png', 'jpg'],
    'size_allowed' => 1024 * 1024 * 5, // 5Mb
    'folder' => __DIR__ . 'tmp/', //caminho que irá salvar o arquivo,
    'format_name' => date('now'),
    'file_error_message' => [
        0 => 'Não houve erro e o upload foi bem sucedido.',
        1 => 'O arquivo enviado excede o limite definido.',
        2 => 'O arquivo excede o limite definido em MAX_FILE_SIZE no formulário HTML.',
        3 => 'O upload do arquivo foi feito parcialmente.',
        4 => 'Nenhum arquivo foi anexado',
        6 => 'Pasta temporária estar ausente.',
        7 => 'Falha ao escrever o arquivo em disco.',
        8 => 'Uma extensão do PHP interrompeu o upload do arquivo.'
    ]
];

//Pega extensão do arquivo
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $config['type_file_allowed'])) {
    throw new Exception('Extesão '. $extension .' do arquivo
    não permitida');
}

if($_FILES['size'] > $config['size_allowed']){
    throw new Exception('O arquivo enviado é muito grande, 
    envie arquivos de até 5Mb');
}

$file_name = $config['format_name'] . '.' . $extension;
$path = $config['folder'];

if (move_uploaded_file($_FILES['tmp_name'], $path . $file_name)) {
    $sql = printf("UPDATE 'imagem' SET 'nome'='%s' AND caminho='%s'
          WHERE 'id_usuario'= '%s' ", $file_name, $path, $user_id);
    //$conn é conexão mysqli do banco
    if ($conn->query($sql) === TRUE) {
        echo "Foto do perfil atualizado com sucesso";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
}
    
20.07.2017 / 16:54
0

I need it when it, in this step of user registration, DO NOT define an image, which enters a pattern, any indication? Thanks

    
15.12.2018 / 22:56