Friday, 13 September 2019

How to upload All type of Files on AWS S3 using Codeigniter


Upload Files on Amazon S3 Bucket using Codeigniter.

Before this,Firstly You have to know about the S3 Bucket. This is the simple Storage Service on Amazon web services .Basically It is use for storing the large amount of files and folder. We can upload the website data on aws cloud storage.
Here Bucket is simply the name of folder.And files and data inside bucket is called Objects.We can say S3 Objects. It is also consist data as well as meta data.

How to use S3 :

1. Create Amazon(AWS) S3 Account.You can use this link https://signin.aws.amazon.com then Sign in to Console.
2.Now You have access key and secret key of your aws  account. 
3.Add Aws s3 Files in your root directory of the project.
4.Create Aws3.php file inside libraries folder. and Add this code.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Description of AmazonS3
 *
 * @author wahyu widodo
 */
 include("./vendor/autoload.php");
 use Aws\S3\S3Client;
 class Aws3{
private $S3;

public function __construct(){
$this->S3 = S3Client::factory([
'key'    => 'Your Access key',
'secret' => 'Your Secret Key',
'region' => 'ap-south-1',
'signature' => 'v4'
]);
}
public function addBucket($bucketName){
$result = $this->S3->createBucket(array(
'Bucket'=>$bucketName,
'LocationConstraint'=> 'ap-south-1'));
return $result;
}
public function sendFile($bucketName, $filename){
        $result = $this->S3->putObject(array(
'Bucket' => 'connectosh',
'Key' => $bucketName.'/'.preg_replace('/\s+/', '-',$filename['name']),
'SourceFile' => $filename['tmp_name'],
'StorageClass' => 'STANDARD',
'ACL' => 'public-read'
));
return $result['ObjectURL']."\n";
}
 
 }

5.Now Add Code in your Controller Function to upload files on Aws.
         $this->load->library('aws3');
$image_data['file_name'] = $this->aws3->sendFile($sub_bucket_name,$_FILES['image']);
$data = array('upload_data' => $image_data['file_name']);

In this data variable you will get the path of uploaded files. Here you will also learn How to create Sub bucket  on S3 dynamically using Php- Codeigniter.

Friday, 5 July 2019

How to upload multiple files at Once.

Uploading Any Files using codeigniter.


Today I am going to tell you that How we can upload multiple files at once.

Step:1
In Today's world website is  having lots of image files mostly in eCommerce sites.and we want to upload many images at once. Because of this we can save our time as well as speed.
Create a function upload_files in controller.all type of file you can upload either it is image file,pdf file,doc file or vedio file ,ios supported format file.
copy this code in your controller function.


              if(!empty($_FILES['image']['name']['0']))
              {
                $files = $_FILES;
                $config['upload_path'] = './post_file/';
                $path=$config['upload_path'];
                $config['allowed_types'] = 'gif|jpg|png|jpeg|mp4|3GP|OGG|pdf|csv|txt|doc|xlsx|docx|xls';
                $config['max_size'] = '15360';
                //$config['encrypt_name'] = TRUE;
                  //$config['max_width'] = '1920';
                  //$config['max_height'] = '1280';
                $this->load->library('upload', $config);
                $count = count($_FILES['image']['name']);
                for($i=0; $i<$count; $i++)
                {
                  if (!empty($_FILES['image']['name']))
                  {
                    $name = $files["image"]["name"][$i];
                    $ext = end((explode(".", $name)));
                    $_FILES['image']['name']= $files['image']['name'][$i];
                    $_FILES['image']['type']= $files['image']['type'][$i];
                    $_FILES['image']['tmp_name']= $files['image']['tmp_name'][$i];
                    $_FILES['image']['error']= $files['image']['error'][$i];
                    $_FILES['image']['size']= $files['image']['size'][$i];
                    $rand = rand(1,100).time();
                    $new_name = $rand.'_'.preg_replace('/[^A-Za-z0-9\_\-.]/', '_',$_FILES["image"]['name']);
                    $config['file_name'] = $new_name;
                    $this->upload->initialize($config);
                    if (!$this->upload->do_upload('image'))
                    {
                              $errors = $this->upload->display_errors();
                    }
                    else
                    {
                      $image_data=array(
                       'post_id' => $post_id,
                                           'file'      => $new_name//$_FILES['image']['name']
                                         );
                      $this->Admin_model->insert_file($image_data);
                    }
                  }
                }
              }

Step:2
In model write this code for the insert particular file in database.
public function insert_file($image_data)
{
    $this->db->insert('tbl_post_file',$image_data);
    return ($this->db->affected_rows() != 1) ? False : True;
}

one more thing also create folder post_file in application level of your project then you can see after this code files are uploading or not.if not then also check permission of folder change it to 777.

Hope this code will work .All the best.
If you are facing any problem with this code then contact me on my email and you can also do comment. Please feel free to ask any query for any topic on codeigniter.
           

Saturday, 29 June 2019

Push Notification on Post Like for IOS & Android.

Hi All,

Hope you are doing well. Today I am going to tell you how we can use Push Notification on any post like or we can say comment like for Android as well as IOS Device.
First we will create a controller function from where we can trigger notification after any event.
Create Controller API function Post_like().

Step 1.



Step 2:

This is post like Api. Expected Parameters  are post_id and user_id. using post_id and user_is user can check in the database that this post is like or not like . if found like then it returns dislike and vice versa.
No we will create a push notification api for that we will create new model that is called push_model.
here will define 2 function .
1. send_push_notification
2.send_notification 





How you will find the solution. In fisrt function we are passing 5 parameters.user_id,title,message,id,action.
On the basis of this you can find that where and whom you want to send push notification.
In the last line of this function we are redirecting to another function here we have define that how to use curl and finally send notification using fire base.

Wednesday, 8 May 2019

Fatal error: Class CI_Session_files_driver contains 2 abstract methods...

Fatal error: Class CI_Session_files_driver contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SessionHandlerInterface::open, SessionHandlerInterface::close) in C:\xampp\htdocs\connectosh\system\libraries\Session\drivers\Session_files_driver.php on line 49


According to my observation, This is only a bug that is related to session class.

Solution : Below are the some solution that will differently be overcome this bug.

Step 1: Stop XAMPP (Apache server) and then start.

Step 2: If not working then install Codeigniter again and use it as a fresh one..

Step 3: Go to in C:\xampp\htdocs\test\system\libraries\Session\SessionHandlerInterface.php .
            And comment code this.


Hope!!! Now your code will be work.



Tuesday, 7 May 2019

How to send HTML templates as an Email using SMTP in codeigniter

I am sharing this post which explains how to send HTML Template as an email using SMTP and PHPMailer in codeigniter.

Create a html template as per the requirement send this html page as per the project requirment.
Now we learn how to send Email by PHPMailer and Gmail Codeigniter.

Follow below steps we can implement it.



Step:1
First Create a HTML Template welcumemail.php Page which is suitable for your requirement.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Codeigniter</title>
</head>
<body>
<div class="wrapper">
<div style="margin:auto; text-align:center; width:625px;">
<p >Update your profile
Welcome Mail</p>
<p>Welcome to Codeigniter EmaIL!<br/></p>
</div>
</div>
</body>
</html>

Step:2
Create Controller Method for sending email.

public function sendemail()
{

   
            $data = array();
            $this->load->library('email');
            $subject='Welcome to Codeigniter';
       
            $htmlContent =  echo $this->load->view('welcumemail');
   
            $config['mailtype'] = 'html';
            $this->load->library('email');

            require("assets/testing/class.phpmailer.php");
            $email1='d.mehra@gmail.com';
            $mail = new PHPMailer();

            $mail->IsSMTP();
            $mail->Host = "xyz.in";
            $mail->SMTPAuth = true;
                    //$mail->SMTPSecure = "ssl";
            $mail->Port = 587;
            $mail->Username = "contact@xyz.in";
            $mail->Password = "xyz";

            $mail->From = "contact@xyz.in";
            $mail->FromName = "ABC";
            $mail->AddAddress("$email1");

            $mail->IsHTML(true);

            $mail->Subject = "Welcome ...";
            $mail->Body = ($htmlContent);
            
            $mail->Send();
            

            
        return True;
       

    }

         

Just Replace Your email ids,username,password and sending email using codeigniter.

Error:- $(...).modal is not a function.

$(...).modal is not a function.


This Error has so many solutions. Basically this is related to jquery and because model is related to bootstrap then we have to apply bootstrap js and bootstrap is depend on jquery then first we apply jquery.min.js and after that bootstrap.min.js.

like this.
    <script src="<?php echo base_url() ?>assets/global_assets/js/main/jquery.min.js"></script>
    <script src="<?php echo base_url() ?>assets/js/bootstrap.min.js"></script>

Solutions:

1. Apply above step means first jquery then bootstrap.
2. Check jquery is not included twice.
check with find in files using code igniter.



3. Change $.ajax(...) to JQuery.ajax(...).
4. Check using inspect element In console you can check error in which file.


Hope for this you can find error.



Saturday, 4 May 2019

Upgrade Android/IOS App using Codeigniter Restful Webservices(API)

What is Restful Webservices :- It is nothing just a function. webservices are the api that is used to communicate with different technologies. It is also called api (Application Programming Interface) used for provide the interface between different application.

Now I would like to share webservice of upgrade app and force update app.

Here we will writeapp_version_check() webservice in codeigniter controller or any framework.

Step:1 app_version_check()webservice



public function app_version_check()
{
$os = $this->input->get_post('os');
$app = $this->input->get_post('app');
$version = $this->input->get_post('version');
if($os == '' || $app == '' || $version == '' )
{

$status="error";
$message="Please Enter Required Fields";
$response=$this->response_msg($status,$message);
}
else
{
$upgrade_required = $this->Home_model->app_version_check($os,$app,$version);

if(!isset($upgrade_required))
{
$is_upgrade_required="True";
$message="New version of connectosh Available";
$response=$this->response_msg($status,$message);
}
else
{
$is_upgrade_required="False";
$message="No Need to update";
$response=$this->response_msg($status,$message);
}

}
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));

}

There are 3 parameters os,app_name,version name pass in model and get the response in json format.

Step:2 app_version_check() Model

public function app_version_check($os,$app,$version)
{

$this->db->select('*');
$this->db->from('app_info');
$this->db->where('os',$os);
$this->db->where('app_name',$app);
$this->db->where('upgrade_code',$version);
$query=$this->db->get();
return $query->row();


}

Make sure you have a database of app_info table with 3 columns name('os','app_name','upgrade_code').

Now you can test the webservices using Postman.

How to upload All type of Files on AWS S3 using Codeigniter

Upload Files on Amazon S3 Bucket using Codeigniter. Before this,Firstly You have to know about the S3 Bucket. This is the simple Storag...