PHP image upload function, save in a dir and then return save image url

前端 未结 5 510
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 12:55

I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.

HTML:



        
5条回答
  •  梦谈多话
    2021-01-03 13:53

    This my function, variable $ten_anh is name of file image in html.

    function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
    if(isset($_FILES[$ten_anh])){
         $errors= array();
         $file_name = $_FILES[$ten_anh]['name'];
         $file_size =$_FILES[$ten_anh]['size'];
         $file_tmp =$_FILES[$ten_anh]['tmp_name'];
         $file_type=$_FILES[$ten_anh]['type'];
         $file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));
    
         $expensions= array("jpeg","jpg","png");
    
         if(in_array($file_ext,$expensions)=== false){
                $errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
         }
    
         if($file_size > 2097152){
                $errors[]='Kích cỡ file nên là 2 MB';
         }
    
         if(empty($errors)==true){
                move_uploaded_file($file_tmp,"../images/".$file_name);
                echo "Thành công!!!";
         }
         else{
                print_r($errors);
         }
    }
    

    }

    Example: - html code:

    
    
    • call function php: upload_anh('avatar');

提交回复
热议问题