Home

Wednesday, July 10, 2019

How to get youtube video details using PHP ?

<?php
function get_youtube_title($video_id){ 
$html = 'https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx&part=snippet,statistics';
    $response = file_get_contents($html);
    $decoded = json_decode($response, true);
   
echo "<pre>";
print_r($decoded);
echo "</pre>";

foreach ($decoded['items'] as $items) {
         $title= $items['snippet']['title'];
         return $title;
    }
}
echo $title = get_youtube_title('6kTGlADNy7g');
?>

Require: Google API Key

Refere this link for more part, like:snippet,statistics,topicDetails etc
https://developers.google.com/youtube/v3/docs/videos/list

Friday, April 26, 2019

How to create HTML to PDF using jsPDF ?

<!doctype html>
<html lang="en">
<head>
<title>jsPDF</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<link href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

<script>
var pdf,page_section,HTML_Width,HTML_Height,top_left_margin,PDF_Width,PDF_Height,canvas_image_width,canvas_image_height;

function calculatePDF_height_width(selector,index){
page_section = $(selector).eq(index);
HTML_Width = page_section.width();
HTML_Height = page_section.height();
top_left_margin = 15;
PDF_Width = HTML_Width + (top_left_margin * 2);
PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
canvas_image_width = HTML_Width;
canvas_image_height = HTML_Height;
}
    //Generate PDF
    function generatePDF() {
        pdf = "";
$("#downloadbtn").hide();
$("#genmsg").show();
        html2canvas($(".print-wrap:eq(0)")[0], { allowTaint: true }).then(function(canvas) {

            calculatePDF_height_width(".print-wrap",0);
            var imgData = canvas.toDataURL("image/png", 1.0);
pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
            pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, HTML_Width, HTML_Height);
        });

        html2canvas($(".print-wrap:eq(1)")[0], { allowTaint: true }).then(function(canvas) {

            calculatePDF_height_width(".print-wrap",1);

            var imgData = canvas.toDataURL("image/png", 1.0);
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, HTML_Width, HTML_Height);

        });

        html2canvas($(".print-wrap:eq(2)")[0], { allowTaint: true }).then(function(canvas) {

            calculatePDF_height_width(".print-wrap",2);

            var imgData = canvas.toDataURL("image/png", 1.0);
            pdf.addPage();
            pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, HTML_Width, HTML_Height);


         
                //console.log((page_section.length-1)+"==="+index);
                setTimeout(function() {

                    //Save PDF Doc
                    pdf.save("HTML-Document.pdf");

                    //Generate BLOB object
                    var blob = pdf.output("blob");

                    //Getting URL of blob object
                    var blobURL = URL.createObjectURL(blob);

                    //Showing PDF generated in iFrame element
                    var iframe = document.getElementById('sample-pdf');
                    iframe.src = blobURL;

                    //Setting download link
                    var downloadLink = document.getElementById('pdf-download-link');
                    downloadLink.href = blobURL;
$(".pdf-download-link").show();

$("#sample-pdf").slideDown();


$("#downloadbtn").show();
$("#genmsg").hide();
                }, 0);
        });
    };

</script>
<style>
.print-wrap {
width: 826px;
margin: 0 auto;
}
.bgimg{
background:url('2.jpg');
background-repeat:no-repeat;
background-position:center;
height:826px;
}
</style>
</head>
<body style="text-align: center;"><br>
<a class="btn btn-primary" id="downloadbtn" onclick="generatePDF()" style="color:#ffffff"><b>Create & Download PDF</b></a>
<span id="genmsg" style="display:none;"><b>Generating PDF ...</b></span>
<br>
<iframe frameBorder="0" id="sample-pdf" style="right:0; top:53px; bottom:0; height:400px; width:100%;display:none;"></iframe>
<br>
<h1 class="pdf-download-link" style="display:none">Download Link Of Created PDF</h1>
<br>
<a class="pdf-download-link" id="pdf-download-link" style="display:none" title="Download PDF File">Download PDF file</a>
<br>
<div class="print-wrap page1">
<h3 style="color:blue;">Sample page 1 for demo</h3>
<img src="1.jpg">
<p style="color:red;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla placerat egestas massa, a feugiat augue tristique at. Integer interdum turpis in velit fermentum, sed feugiat odio finibus. </p>
</div>
<div class="print-wrap page2 bgimg">
<h3 style="color:white;">Sample page 2 for demo</h3>
<p style="color:yellow;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla placerat egestas massa, a feugiat augue tristique at. Integer interdum turpis in velit fermentum, sed feugiat odio finibus.</p>
</div>
<div class="print-wrap page3">
<h3 style="color:white;">Sample page 3 for demo</h3>
<img src="2.jpg">
<p style="color:black;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla placerat egestas massa, a feugiat augue tristique at. Integer interdum turpis in velit fermentum, sed feugiat odio finibus.</p>
</div>
</body>
</html>

Tuesday, December 4, 2018

How to add custom fields in ultimate profile page ?

add_action('um_after_account_general', 'showExtraFields', 100);

function showExtraFields(){

$custom_fields = [
"phone" => "Phone",
"Age" => "Age"
];

$fields = [];
foreach ($custom_fields as $key => $value) {
$fields[$key] = array(
'title' => $value,
'metakey' => $key,
'type' => 'text',
'label' => $value,
'required' => 1,
'public' => 1,
'editable' => 1,
'validate' => $key
);
}

$id = um_user('ID');
$fields = apply_filters( 'um_account_secure_fields', $fields, $id );

UM()->builtin()->saved_fields = $fields;
UM()->builtin()->set_custom_fields();

foreach( $fields as $key => $data )
$output .= UM()->fields()->edit_field( $key, $data );

echo $output;
}

add_action( 'um_submit_account_errors_hook', 'my_submit_account_errors', 10, 1 );
function my_submit_account_errors( $submitted ) {

global $ultimatemember;
if (strlen($submitted['phone'] ) > 9)
$ultimatemember->classes['form']->add_error('phone','Phone is too long');
}

Wednesday, February 7, 2018

How to get All Sub Category in Magento using Parent Category Id ?

<?php
require_once 'app/Mage.php';
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', 12000);
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);


?>
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $categoryId = 12449;?>
<?php $category = Mage::getModel('catalog/category')->load($categoryId) ?>
<?php $_categories = $category->getChildrenCategories() ?>

<?php if (count($_categories) > 0): ?>
    <ul>
        <?php foreach($_categories as $_category): ?>
            <li>
                <a href="<?php echo $_helper->getCategoryUrl($_category) ?>"><?php echo $_category->getName() ?></a>
                <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
                <?php if($_category->hasChildren()):?>
                <?php $_subcategories = $_category->getChildrenCategories() ?>
                    <ul>
                        <?php foreach($_subcategories as $_subcategory): ?>
                            <li>
                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"><?php echo $_subcategory->getName() ?></a>
                                <?php $_category2 = Mage::getModel('catalog/category')->load($_subcategory->getId()) ?>
                                <?php if($_category2->hasChildren()):?>
                                <?php $_subcategories2 = $_category2->getChildrenCategories() ?>
                                    <ul>
                                        <?php foreach($_subcategories2 as $_subcategory2): ?>
                                            <li>
                                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory2) ?>"><?php echo $_subcategory2->getName() ?></a>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php endif; ?>

                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>


Second Method 

$category_ids = array();
$catID = 12449;

function retrieveAllChilds($id = null, $childs = null) {
    $category = Mage::getModel('catalog/category')->load($id);
    $subCategory = $category->getResource()->getChildren($category, true);

foreach ($subCategory as $categoryID)
{
$sCategory = Mage::getModel('catalog/category')->load($categoryID);
//$catnames = array();
//$category_ids = array();
foreach ($sCategory->getParentCategories() as $parent) {
//$catnames[] = $parent->getName();
//array_push($category_ids,$parent->getName());
$category_ids[$parent->getId()] = $parent->getName();
}
//echo  implode('->',$catnames);
//echo '<br>';
/*echo "<pre>";
print_r($category_ids);*/

}
return $category_ids;
}

$dd = retrieveAllChilds(12449);

echo "<pre>";
print_r($dd);



Friday, January 12, 2018

How to remove woocommerce breadcrumb from product page ?

Add the following line of code to the WordPress theme functions.php file:

remove_action( 'woocommerce_before_main_content','woocommerce_breadcrumb', 20, 0);

add_action('template_redirect', 'remove_shop_breadcrumbs' );
function remove_shop_breadcrumbs(){
if (is_single()) {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
}
}

Monday, November 20, 2017

How to create category in magento with tree ?

<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

$array = array("Cat-A > Cat-B > Cat-C > Cat-G","Cat-D > Cat-E > Cat-F");

for($i=0;$i<count($array);$i++)
{
    $explode = explode(">",$array[$i]); 
    $trimmed_array=array_map('trim',$explode);   
   
    $previous_cat_id = 0;
    for($d=0;$d<count($trimmed_array);$d++)
    {       
       $cat_name = $trimmed_array[$d];   
     
       $_category = Mage::getResourceModel('catalog/category_collection')
        ->addFieldToFilter('name', $cat_name)
        ->getFirstItem();

       $categoryId = $_category->getId();     

       if($categoryId == '')
       {
           if($previous_cat_id == 0)
           {
                $parentId = '2';
           }else
           {
               $parentId = $previous_cat_id;
           }         
            try{
               $category = Mage::getModel('catalog/category');
               $category->setName($cat_name);         
               $category->setIsActive(1);
               $category->setDisplayMode('PRODUCTS');
               $category->setIsAnchor(1); //for active anchor
               $category->setStoreId(Mage::app()->getStore()->getId());
               $parentCategory = Mage::getModel('catalog/category')->load($parentId);
               $category->setPath($parentCategory->getPath());
               $category->save();
               $previous_cat_id = $category->getId();
           } catch(Exception $e) {
               print_r($e);
           } 
       }else
       {         
           if($previous_cat_id !="" && $categoryId!="")
           { 
                $categoryId = $categoryId;
                $parentId = $previous_cat_id;

                $category = Mage::getModel('catalog/category')->load($categoryId);
                $category->move($parentId, null);
                $previous_cat_id = 0;
           }else
           {
                $previous_cat_id = $categoryId;
           }         
       }
    } 
}
?>

Tuesday, September 26, 2017

How load PHP & Mysql data using Ajax in DataTables Server-side Processing ?

// HTML Code
<div class="alphabet">Search:
    <span class="clear active alphasearch open" id="all">All</span>
    <span>
        <span class="alphasearch" id="A">A</span>
    </span>
    <span>
        <span class="alphasearch" id="B">B</span>
    </span>
    <span>
        <span class="alphasearch" id="C">C</span>
    </span>
    <span>
        <span class="alphasearch" id="D">D</span>
    </span>
    <span>
        <span class="alphasearch" id="E">E</span>
    </span>
    <span>
        <span class="alphasearch" id="F">F</span>
    </span>
    <span>
        <span class="alphasearch" id="G">G</span>
    </span>
    <span>
        <span class="alphasearch" id="H">H</span>
    </span>
    <span>
        <span class="alphasearch" id="I">I</span>
    </span>
    <span>
        <span class="alphasearch" id="J">J</span>
    </span>
    <span>
        <span class="alphasearch" id="K">K</span>
    </span>
    <span>
        <span class="alphasearch" id="L">L</span>
    </span>
    <span>
        <span class="alphasearch" id="M">M</span>
    </span>
    <span>
        <span class="alphasearch" id="N">N</span>
    </span>
    <span>
        <span class="alphasearch" id="O">O</span>
    </span>
    <span>
        <span class="alphasearch" id="P">P</span>
    </span>
    <span>
        <span class="alphasearch" id="Q">Q</span>
    </span>
    <span>
        <span class="alphasearch" id="R">R</span>
    </span>
    <span>
        <span class="alphasearch" id="S">S</span>
    </span>
    <span>
        <span class="alphasearch" id="T">T</span>
    </span>
    <span>
        <span class="alphasearch" id="U">U</span>
    </span>
    <span>
        <span class="alphasearch" id="V">V</span>
    </span>
    <span>
        <span class="alphasearch" id="W">W</span>
    </span>
    <span>
        <span class="alphasearch" id="X">X</span>
    </span>
    <span>
        <span class="alphasearch" id="Y">Y</span>
    </span>
    <span>
        <span class="alphasearch" id="Z">Z</span>
    </span>
</div>

<div class="portlet-body">
    <table class="table table-striped table-bordered table-hover table-checkable order-column" id="enquirylist">
        <thead>
            <tr>
                <th>Quote Received</th>
                <th>Service Date</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Phone</th>
                <th>State</th>
                <th>Move Type</th>
            </tr>
        </thead>
    </table>
</div>


<?php
// This code add in controller file
public function ajaxData() {     
    // Load here model
    $this->load->model('enquiry_model');
    if (isset($_POST)) {
    $this->enquiry_model->getAjaxData();
    }
}
?>

<?php
// This code add in model file

/* Get Ajax Data */
function getAjaxData() {
/* IF Query comes from DataTables do the following */
    if (!empty($_POST)) {
        /* echo "<pre>";
        print_r($_POST); */
        define("enquiry", "enquiry");
        define("move_type", "move_type");
        /* Useful $_POST Variables coming from the plugin */
        $draw = $_POST["draw"]; //counter used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables
        $orderByColumnIndex = $_POST['order'][0]['column']; // index of the sorting column (0 index based - i.e. 0 is the first record)

        $orderBy = $_POST['columns'][$orderByColumnIndex]['data']; //Get name of the sorting column from its index
        /* if($orderBy == 'edit_link')
          {
          $orderBy = 'enquiry_id';
          } */
        $orderType = $_POST['order'][0]['dir']; // ASC or DESC
        $start = $_POST["start"]; //Paging first record indicator.
        $length = $_POST['length']; //Number of records that the table can display in the current draw
        /* END of POST variables */

        $sql = "SELECT * FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id";
        $query = $this->db->query($sql);
        $recordsTotal = $query->num_rows();

        /* SEARCH CASE : Using Alphabest Wise */

        /* */
        /* SEARCH CASE : Filtered data */
        if (!empty($_POST['search']['value'])) {



            if (!empty($_POST['alphabet']) && $_POST['alphabet'] != 'all') {
               /* WHERE Clause for searching */
                for ($i = 0; $i < count($_POST['columns']); $i++) {

                    /*if($_POST['columns'][$i]['data'] !="en_fname")
                    {*/
                        $column = $_POST['columns'][$i]['data']; //we get the name of each column using its index from POST request
                        $where[] = "$column like '%" . $_POST['search']['value'] . "%'";
                   /* }*/
                }
                $where = "WHERE ( " . implode(" OR ", $where). " )"; // id like '%searchValue%' or name like '%searchValue%' ....
                $where .= " AND ( en_fname like '" . $_POST['alphabet'] . "%' )";
                /* End WHERE */
            }else
            {
               /* WHERE Clause for searching */
                for ($i = 0; $i < count($_POST['columns']); $i++) {

                    /* if($_POST['columns'][$i]['data'] !="edit_link")
                      { */
                    $column = $_POST['columns'][$i]['data']; //we get the name of each column using its index from POST request
                    $where[] = "$column like '%" . $_POST['search']['value'] . "%'";
                    /* } */
                }
                $where = "WHERE " . implode(" OR ", $where); // id like '%searchValue%' or name like '%searchValue%' ....
                /* End WHERE */
            }

           // echo $where;die;
            $sql = sprintf("SELECT *,DATE_FORMAT(e.en_date, '%%d/%%m/%%Y %%h:%%s %%p') as en_date,DATE_FORMAT(e.en_servicedate, '%%d/%%m/%%Y') as en_servicedate FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id %s", $where); //Search query without limit clause (No pagination)
            $query = $this->db->query($sql);
            $recordsFiltered = $query->num_rows(); //count(getData($sql));//Count of search result

            /* SQL Query for search with limit and orderBy clauses */
            $sql = sprintf("SELECT *,DATE_FORMAT(e.en_date, '%%d/%%m/%%Y %%h:%%s %%p') as en_date,DATE_FORMAT(e.en_servicedate, '%%d/%%m/%%Y') as en_servicedate FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id %s ORDER BY %s %s limit %d , %d ", $where, $orderBy, $orderType, $start, $length);
            $query = $this->db->query($sql);
            $query = $query->result_array();

            $data = array();
            foreach ($query as $row) {
                $row['en_date'] = '<a href="/enquiriesdetails/' . $row['enquiry_id'] . '">' . $row['en_date'] . '</a>';
                $data[] = $row;
            }
        } else if (!empty($_POST['alphabet']) && $_POST['alphabet'] != 'all') {
            $where[] = "en_fname like '" . $_POST['alphabet'] . "%'";
            $where = "WHERE " . implode(" OR ", $where); // id like '%searchValue%' or name like '%searchValue%' ....
            //$sql = sprintf("SELECT *,CONCAT_WS('', 'en_fname', 'en_lname', NULL) = 'en_fname' FROM %s %s", enquiry , $where);//Search query without limit clause (No pagination)
            $sql = sprintf("SELECT *,DATE_FORMAT(e.en_date, '%%d/%%m/%%Y %%h:%%s %%p') as en_date,DATE_FORMAT(e.en_servicedate, '%%d/%%m/%%Y') as en_servicedate FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id %s", $where); //Search query without limit clause (No pagination)
            $query = $this->db->query($sql);
            $recordsFiltered = $query->num_rows(); //count(getData($sql));//Count of search result

            /* SQL Query for search with limit and orderBy clauses */
            $sql = sprintf("SELECT *,DATE_FORMAT(e.en_date, '%%d/%%m/%%Y %%h:%%s %%p') as en_date,DATE_FORMAT(e.en_servicedate, '%%d/%%m/%%Y') as en_servicedate FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id %s ORDER BY %s %s limit %d , %d ", $where, $orderBy, $orderType, $start, $length);
            $query = $this->db->query($sql);
            $query = $query->result_array();

            $data = array();
            foreach ($query as $row) {
                $row['en_date'] = '<a href="' . base_url('/enquiries/view/' . $row['en_unique_id']) . '">' . $row['en_date'] . '</a>';
                $data[] = $row;
            }
        }
        /* END SEARCH */ else {
            $sql = sprintf("SELECT *,DATE_FORMAT(e.en_date, '%%d/%%m/%%Y %%h:%%s %%p') as en_date,DATE_FORMAT(e.en_servicedate, '%%d/%%m/%%Y') as en_servicedate FROM " . enquiry . " as e INNER JOIN " . move_type . " as m ON e.en_movetype=m.movetype_id ORDER BY %s %s limit %d , %d ", $orderBy, $orderType, $start, $length);
            $query = $this->db->query($sql);
            $query = $query->result_array();

            $data = array();
            foreach ($query as $row) {
                $row['en_date'] = '<a href="' . base_url('/enquiries/view/' . $row['en_unique_id']) . '">' . $row['en_date'] . '</a>';
                $data[] = $row;
            }
            $recordsFiltered = $recordsTotal;
        }

        // echo $sql;die;
        /* Response to client before JSON encoding */
        $response = array(
            "draw" => intval($draw),
            "recordsTotal" => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data" => $data
        );

        echo json_encode($response);
    } else {
        echo "NO POST Query from DataTable";
    }
}
?>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="global/scripts/datatable.js"></script>
<script type="text/javascript" src="global/plugins/datatables/datatables.min.js"></script>
<script>
/////// script code ///////
$(document).ready(function () {
    var myData ={};
    var table = $('#enquirylist').DataTable({
            "columns": [
                    {"data": "en_date"},
                    {"data": "en_servicedate"},
                    {"data": "en_fname"},
                    {"data": "en_lname"},
                    {"data": "en_phone"},
                    {"data": "en_movingfrom_state"},             
                    {"data": "movetype_name"},

            ],
            "columnDefs": [
                    /*{
                            "targets": [6],
                            "orderable": false,
                    },*/
                    { "width": "15%", "targets": 0 },
            ],

            "processing": true,
            //"autoWidth": false,
            "serverSide": true,
            "bStateSave": true,
            "stateSave": true,
            "ajax": {
                    url: 'enquirieslist/ajaxData',
                    "data": function ( d ) {
                       return  $.extend(d, myData);
                    },
                    type: 'POST'
            }
    });

    $( ".alphasearch" ).click(function() {
            $(".alphasearch").removeClass("open");
            $(this).toggleClass('open');
            var alpha = $(".open").attr("id");
            myData.alphabet = alpha;         
            table.ajax.reload();
    });
});
</script>

How to remove all product image in magento ?

<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);

$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product)
{
    echo $product->getId();
    echo "<br/>";
    $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
    echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
    echo "<br/>";

    $MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
    echo "<pre>";
    print_r($MediaGallery);
    echo "</pre>";

    foreach($MediaGallery as $eachImge){
        $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
        $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
        $DirImagePath=str_replace("/",DS,$eachImge['file']);
        $DirImagePath=$DirImagePath;
        // remove file from Dir
        $io     = new Varien_Io_File();
        $io->rm($MediaCatalogDir.$DirImagePath);

        $remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
    }
}
?>

Tuesday, August 22, 2017

How to get visitor country name,currency rate,currency symbol in PHP

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$dataArray = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));
echo "<pre>";
print_r($dataArray);
echo "You are from: ".$dataArray->geoplugin_countryName;
?>

Output :
stdClass Object
(
    [geoplugin_request] => 27.109.6.218
    [geoplugin_status] => 206   
    [geoplugin_city] => 
    [geoplugin_region] => Jammu and Kashmīr
    [geoplugin_areaCode] => 0
    [geoplugin_dmaCode] => 0
    [geoplugin_countryCode] => IN
    [geoplugin_countryName] => India
    [geoplugin_continentCode] => AS
    [geoplugin_latitude] => 33.8042
    [geoplugin_longitude] => 74.2583
    [geoplugin_regionCode] => 12
    [geoplugin_regionName] => Jammu and Kashmīr
    [geoplugin_currencyCode] => INR
    [geoplugin_currencySymbol] => ₨
    [geoplugin_currencySymbol_UTF8] => ₨
    [geoplugin_currencyConverter] => 64.1175
)
You are from: India

Saturday, July 22, 2017

Base url without index.php in magento

<?php
            echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
?>

Saturday, July 8, 2017

How to Remove index.php in codeigniter ?

Step: 1  Open the file config.php

--> Find the below code in file
$config['index_page'] = "index.php"
--> Remove index.php
$config['index_page'] = ""

// Find the below code in file
$config['uri_protocol'] = "AUTO"
// Replace it as $config['uri_protocol'] = "REQUEST_URI"


Step: 2  Go to your CodeIgniter folder and create .htaccess  file and Write below code in .htaccess file

<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule>

Thursday, June 22, 2017

How to add images for products in magento pragmatically ?

Use can upload Base-Image, Small-Image, Thumbnail-Image, and Image-Gallery for the product using CSV file in Magento programmatically.
=====================================================================
<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

// Images with SKU
$importDir = Mage::getBaseDir('media') . DS . 'import/diamond/shape/big/';
$file_handle = fopen("images5.csv", "r");
$c = 0;


while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000);

if($line_of_text[0] !="")
{
$productSKU = $line_of_text[0];
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
$lastproductSKU = $productSKU;

$basefileName = $line_of_text[1];
$smallfileName = $line_of_text[2];
$thumbfileName = $line_of_text[3];

$basefilePath = $importDir.$basefileName;
$smallfilePath = $importDir.$smallfileName;
$thumbfilePath = $importDir.$thumbfileName;

// Base Image
if (file_exists($basefilePath)) {
$ourProduct->addImageToMediaGallery($basefilePath, array('image'), false, false);
}

// Small Image
if (file_exists($smallfilePath)) {
$ourProduct->addImageToMediaGallery($smallfilePath, array('small_image'), false, false);
}

// thumbnail Image
if (file_exists($thumbfilePath)) {
$ourProduct->addImageToMediaGallery($thumbfilePath, array('thumbnail'), false, false);
}

$extrafileName = $line_of_text[4];
$extrafilePath = $importDir.$extrafileName;
if (file_exists($extrafilePath)) {
$ourProduct->addImageToMediaGallery($extrafilePath, null, false, false);
}
$ourProduct->save();
}else
{
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$lastproductSKU);
$extrafileName = $line_of_text[4];
$extrafilePath = $importDir.$extrafileName;
if (file_exists($extrafilePath)) {
$ourProduct->addImageToMediaGallery($extrafilePath, null, false, false);
$ourProduct->save();
}
}
$c++;
}
fclose($file_handle);
?>

Please check image for CSV format.


How to get all images of particular product in magento pragmatically ?

<?php
require_once '../app/Mage.php';
set_time_limit(1);
ini_set('memory_limit','1024M');
ini_set('max_execution_time', 3000);
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

// Get Product SKU using csv file
$file_handle = fopen("skus.csv", "r");
$c = 1;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000);
$productSKU = $line_of_text[0];


if($line_of_text[0]!="")
{
$sku = substr($productSKU,0,-1);
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if (false !== $id) {
  //sku exists
$model =  Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$productMediaConfig = Mage::getModel('catalog/product_media_config');

if($model->getImageUrl())
{
$baseImageUrl  = $productMediaConfig->getMediaUrl($model->getImage());
$smallImageUrl = $productMediaConfig->getMediaUrl($model->getSmallImage());
$thumbnailUrl  = $productMediaConfig->getMediaUrl($model->getThumbnail());

$basefileName = explode("/",$model->getImage());
$smallfileName = explode("/",$model->getSmallImage());
$thumbfileName = explode("/",$model->getThumbnail());

echo $c.")baseImageUrl ".$sku."==>".$baseImageUrl;
echo "<br>";
echo $c.")smallImageUrl ".$sku."==>".$smallImageUrl;
echo "<br>";
echo $c.")thumbnailUrl ".$sku."==>".$thumbnailUrl;


$gallery_images = Mage::getModel('catalog/product')->load($model->getId())->getMediaGalleryImages();

$items = array();

foreach($gallery_images as $g_image) {
$items[] = $g_image['url'];
}

echo "<pre>";
print_r($items);
echo "</pre>";
echo "<br>";
echo "<br>";echo "<br>";*/
}
echo "<br>";
$c++;
}
else {
  //sku does not exist
  echo $productSKU."==>sku does not exist";
  echo "<br>";
}
}
}
fclose($file_handle);
?>

Please check image for CSV format.


Monday, January 23, 2017

How to programmatically update short and long description using csv file for magento products ?

<?php
require_once '../app/Mage.php';
umask(0) ;
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$csv = new Varien_File_Csv();
$data = $csv->getData('sku_description.csv'); //path to csv
array_shift($data);

for($i=0;$i<count($data);$i++)
{
if($data[$i][0] != "")
{
$product_sku = $data[$i][0];
$short_description = $data[$i][1];
$long_description = $data[$i][2];

$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$product_sku);

if($product) {
$product->setShortDescription($short_description);
$product->setDescription($long_description);
$product->save();
echo "Updated product " . $productSku . "<br>";
}else
{
echo "Not - Updated product " . $productSku . "<br>";
}
}
}
?>

Please check image for CSV format.


Tuesday, January 10, 2017

How submit or insert data and files using JQuery Ajax ?

Step : 1 create Index.php file
----------------------------------------
<form id="data" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>FirstName</td>
<td><input type="text" name="firstName" value="" /></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" name="lastName" value="" /></td>
</tr>
<tr>
<td>Attachment</td>
<td><input name="image" type="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
<div id="response"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$("form#data").submit(function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: "data.php",
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            //alert(data)
    $("#response").html(data);
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
});
</script>

Step : 2 create data.php file
----------------------------------------
<?php
echo "<pre>";
print_r($_FILES);
echo "<pre>";
print_r($_POST );
/// Put here your logic for insert and uploading code.
?>
rathoddhirendra.blogspot.com-Google pagerank and Worth