Upload image from URL in codeigniter

upload image from url

Upload image from URL in codeigniter

How to upload image from url in codeigniter?

Rather than selecting a file from drive and uploading into folder we can upload image from URL. For that we just need to specify the url of image.

View/uploadimagefromurl.php

<html>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row">
 <form method="post" action="<?php echo base_url().'test/uploadImage'; ?>">
  <div class="col-md-4">
    <input type="text" class="form-control" name="image_path" placeholder="Enter Image URL">
  </div>
  <div class="col-md-5">
    <input type="submit" class="btn btn-primary" name="post_image" value="Upload">
  </div>
 </form>
</div>
</body>
</html>

Declare a form with input type file box and submit button.

For styling use the following Bootstrap link.

Bootstrap css : https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css

Controllers/test.php

public function uploadImage()
    {
        if($this->input->post())
        {
            if(isset($_POST['post_image']))
            {
                $url_to_image=$_POST['image_path'];
                $my_save_dir = 'data/';
                $basename = basename($url_to_image);
                $ext = pathinfo($basename, PATHINFO_EXTENSION);
                $filename = 'NewImage.'.$ext;
                $complete_save_loc = $my_save_dir.$filename;
                $upload = file_put_contents($complete_save_loc,file_get_contents($url_to_image));
                if($upload) 
                {
                    echo '<img src="../'.$complete_save_loc.'" width="100"><br/>';
                }
                else
                {
                    echo "Please upload only image files";
                } 
            }
        }
        $this->load->view('uploadimagefromurl');
    }
  1. Define a function uploadImage()
  2. If form submitted and url specified,
    1. Take the url to a variable
    2. use file_get_contents() and pass the url to function as parameter. file_get_contents — Reads entire file into a string. Refer file_get_contents for details.
    3. use file_put_contents() to save file to folder. file_put_contents — Write data to a file. Refer file_put_contents for details.

For multiple file upload please visit Upload multiple files

For image compression and upload please visit Compress and upload image

Hope this tutorial for upload image from url will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top