Monday, October 22, 2018

image upload using Jquery Ajax and Codeigniter

Image Upload HTML

This code shows photo icon in the middle of a preview box and an upload button. On clicking the photo icon a transparent preview of the image will be displayed in the preview box. Then, this image will be uploaded to a folder on clicking the upload button. It shows a window overlay with a loader to represent that the image upload is in progress.
<div class="form-group">
    <label>Logo</label>                               
    <?php $logo = isset($data['logo']) && $data['logo'] ? $data['logo'] : '' ?>
    <div id="uploadImageBox">
        <div id="targetLayer" style="position:relative;display: inline-block">
            <span class="remove_btn <?php echo $logo ? '' : 'hidden'; ?>" onclick="remove_image($(this))">&times;</span>
            <img src="<?php echo $logo ? base_url("assets/upload/customer/$logo") : base_url("assets/admin/img/no_image.jpg"); ?>" style="height:80px; width: 80px;" />
        </div>
        <input type="hidden" name="old_image" id="old_image" value="<?php echo $logo; ?>">
        <input type="hidden" name="remove_image" id="remove_image" value="">
        <div class="icon-choose-image" >
            <input name="userImage" id="userImage" type="file" class="inputFile" onChange="showPreview(this);" />
        </div>
    </div>
    <div class="error text-danger" id='logo_error'></div>
</div>


Uploading Image and Showing Preview using jQuery AJAX
This script contains a jQuery function showPreview(). It will be called when selecting the image file to be uploaded. This function is used to show a transparent preview of the selected image before upload.
<script type="text/javascript">
function showPreview(objFileInput) {
    if (objFileInput.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
   $("#targetLayer").html('<img src="'+e.target.result+'" width="200px" height="200px" class="upload-preview" />');
   $("#targetLayer").css('opacity','0.7');
   $(".icon-choose-image").css('opacity','0.5');
        }
  fileReader.readAsDataURL(objFileInput.files[0]);
    }
}
</script>
 On clicking the upload button, it submits the form data to PHP via jQuery AJAX.In PHP code, it uploads the image to the target folder and returns the image HTML as an AJAX response. This AJAX response HTML will be added to the preview box.


<script type="text/javascript">
$(document).ready(function (e) {
 $("#uploadForm").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "upload.php",
   type: "POST",
   data:  new FormData(this),
   beforeSend: function(){$("#body-overlay").show();},
   contentType: false,
         processData:false,
   success: function(data)
      {
   $("#targetLayer").html(data);
   $("#targetLayer").css('opacity','1');
   setInterval(function() {$("#body-overlay").hide(); },500);
   },
     error: function() 
      {
      }          
    });
 }));
});
</script>

Thursday, October 11, 2018

Slug Generator Function : PHP

            function slugify($text) {
                // trim
                $text = trim($text);
                // replace non letter or digits by -
                $text = preg_replace('~[^\pL\d]+~u', '_', $text);

                // transliterate
                $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

                // remove unwanted characters
                $text = preg_replace('~[^-\w]+~', '', $text);


                // remove duplicate -
               $text = preg_replace('~-+~', '_', $text);

                // lowercase
                $text = strtolower($text);

                return $text;
            }

Random password Generator Function : PHP

            function random_password($length = 8) {
                $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
                $password = substr(str_shuffle($chars), 0, $length);
                return $password;
            }

Friday, August 3, 2018

dump/export heroku database

You could just make your own pg_dump directly from your Heroku database.
First, get your postgres string using heroku config:get DATABASE_URL.
Look for the Heroku Postgres url (example: HEROKU_POSTGRESQL_RED_URL: postgres://user3123:passkja83kd8@ec2-117-21-174-214.compute-1.amazonaws.com:6212/db982398), which format is postgres://<username>:<password>@<host_name>:<port>/<dbname>.
Next, run this on your command line:
pg_dump --host=<host_name> --port=<port> --username=<username> --password <dbname> > output.sql
OR
pg_dump <heroku postgres string> > output.sql
The terminal will ask for your password then run it and dump it into output.sql.
Then import it: to your localhost db
psql -d my_local_database -f output.sql

Thursday, August 2, 2018

Putting local Postregsql database in Heroku

Grab your the postgres string from your Heroku database using heroku config:get DATABASE

Look for the Heroku Postgres url (example: HEROKU_POSTGRESQL_RED_URL: postgres://user3123:passkja83kd8@ec2-117-21-174-214.compute-1.amazonaws.com:6212/db982398), which format is postgres://<username>:<password>@<host_name>:<port>/<dbname>.

Then import it:
psql -d <heroku postgres string> -f output.sql
Note: in each place where you see <.....> in the above code, be sure to substitute your specific information. Thus you would put your username where it says <username>, and your heroku database url where it says <heroku postgres string>.

Monday, July 23, 2018

wordpress - Woocommerce when deleting a product, also delete the product gallery and product image automatically

1. FOR Remove Attached Image with Product in Woocommerce 

add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
function delete_product_images( $post_id )
{
    $product = wc_get_product( $post_id );
    if ( !$product ) {
        return;
    }
    $featured_image_id = $product->get_image_id();
    $image_galleries_id = $product->get_gallery_image_ids();
    if( !empty( $featured_image_id ) ) {
        wp_delete_post( $featured_image_id );
    }
    if( !empty( $image_galleries_id ) ) {
        foreach( $image_galleries_id as $single_image_id ) {
            wp_delete_post( $single_image_id );
        }
    }
}

2. FOR Remove Attached Image with Post And Page


add_action("before_delete_post","wdm_delete_post_images",10,1);
function wdm_delete_post_images($post_id)
{
 global $wpdb;
          $args = array(
                'post_parent' => $post_id,
                'post_type'   => 'attachment',
                'numberposts' => -1,
                'post_status' => 'any'
        );
        $childrens = get_children( $args);
        if($childrens):
            foreach($childrens as $attachment):
             wp_delete_attachment( $attachment->ID, true );
             $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = ".$attachment->ID);
             wp_delete_post($attachment->ID,true );
            endforeach;
        endif;
}
loading...

Tuesday, May 29, 2018

Download Database Back_up using Codeigniter

//Backup manually
    public function CI_db_backup() {
        // Load the DB utility class
        $this->load->dbutil();
        $this->load->database();
        $dbName = $this->db->database;
        $prefs = array(
            "format" => 'sql', // gzip, zip, txt
            "filename" => $dbName.'.sql', // File name 
        );

// Backup your entire database and assign it to a variable
        $backup = $this->dbutil->backup($prefs);

        $folder = FCPATH . "/storage_db/db_backup/";
        $date = date("m-d-Y-H-i-s", time());
        $filename = $dbName . "_" . $date . ".sql";
// Load the file helper and write the file to your server
        $this->load->helper('file');
        write_file($folder . $filename, $backup);

// Load the download helper and send the file to your desktop
        $this->load->helper("download");
        force_download($filename, $backup);
    }

Friday, May 25, 2018

PHP Mail Function Working with Bluehost server

Simple code for sending emails that worked is as follows:



<?php
$emailto = 'to@domain.com';
$emailfrom = 'from@domain.com';
$subject = 'Email Subject';
$messagebody = 'Hello.';
$headers =
'From: ' . $emailfrom.' . "\r\n" .
'Reply-To: ' . $emailto . ' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($emailto, $subject, $message, $headers);
?>
PHP mail code that works with Bluehost



<?php
$emailto = 'to@domain.com';
$toname = 'TO NAME';
$emailfrom = 'from@domain.com';
$fromname = 'FROM NAME';
$subject = 'Email Subject';
$messagebody = 'Hello.';
$headers =
'Return-Path: ' . $emailfrom . "\r\n" .
'From: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" .
'X-Priority: 3' . "\r\n" .
'X-Mailer: PHP ' . phpversion() .  "\r\n" .
'Reply-To: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-Transfer-Encoding: 8bit' . "\r\n" .
'Content-Type: text/plain; charset=UTF-8' . "\r\n";
$params = '-f ' . $emailfrom;
$test = mail($emailto, $subject, $messagebody, $headers, $params);
// $test should be TRUE if the mail function is called correctly
?>

Product Category Demo in laravel

https://drive.google.com/file/d/1kuyeT3LA22IuN3o_kypOyXesEXMLv31e/view?usp=sharing