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

Asked

Viewed 268 times

0

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

I was making a code for the upload more as I can 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;
    }

}

?>
  • you will read the image file name from a database after?

  • 1

    This, saved in a folder and the path in the @Fbidu database

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
}
  • So I wanted help selecting the image, this I had done but needed something to select the image after this check

  • You want to upload a default image, that’s it?

  • That’s what I want to do, go through the check (like this one above) and if you have set it is $_FILES, but if you don’t have to select the default image. I don’t know how to select the default image

  • A question, why redo the upload of an image (default) that is already in the directory? do not understand.

  • It is an image for each user. I want to copy to the user’s own folder

  • You can simply make a symbolic link in the user folder, or keep all the images in one place. It doesn’t make sense for you to have multiple copies of a standard image

  • What I thought, even if I was to draw among several standard imgs the ideal for several reasons would be, if there is no submission, simply point out a standard image that is already there.

Show 2 more comments

0

I need that when he, at this stage of user registration, NOT set an image, enter a pattern, some indication? Thanks

0

You can do as follows. Let’s use as example user registration.

With each new user created, you can associate an image default.jpg already located in your project.

To manage you create a database structure to relate 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 does the upload from his photo, save the image in the project and change(UPDATE) in the database the path and the name of the image referring to the user id, thus

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

Referring to the PHP file upload process

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();
}
  • Not before I insert. I want to check in the PHP file and then send everything right to the database

  • @Jow updated response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.