Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Saturday 28 September 2019

How to create/write code in text/json file and get content of file in PHP | Codeigniter

Create file and directory
public function createfileanddir() {
    $directoryname = 'directoryname';
    $filename = 1;
    $directory = APPPATH . 'uploads/cache/'.$directoryname;
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }
    $file = APPPATH . 'uploads/cache/'.$directoryname.'/'.$filename.'.json';
    if (file_exists($file)) {
        unlink($file);
    }
    if (!file_exists($file)) {
        $settings = [
            'settings'=>[],
            'socialSettingsArr'=>[],
            'pageSettings'=>[],
        ];
        $fh = fopen($file, 'w');
        fwrite($fh, json_encode($settings));
        fclose($fh);
    }
}
Get content from file and directory
public function getfiles() {
    $directoryname = 'directoryname';
    $directory = 'uploads/cache/'.$directoryname;
    $files = array_diff(scandir($directory), array('.', '..'));
    if(count($files) > 0){
        foreach ($files as $file):
            $file = $directory . '/'.$file;
            $storedata = file_get_contents($file);
            $storedata = json_decode($storedata, true);
            echo '<pre>';print_r($storedata);
        endforeach;
    }
}

Thursday 5 September 2019

How to upload image file with ajax

jQuery("form#add-group-form").submit(function(e){
        e.preventDefault();
        var formData = new FormData(jQuery(this)[0]);
       
        jQuery.ajax({
            type:"POST",
            url:jQuery(this).attr("action"),
            data:formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(response){
                alert(response);
            }
        });
    });

Friday 5 July 2019

How to add file into gitignore which is already push into github

Step 1 : You need to soft remove from git : $ git rm --cached tax.txt
Step 2 : Add tax.txt file in .gitignore
Step 3 : commit and push.
Step 4 : Finished!

Tuesday 13 November 2018

How to override third party vendor block file in magento 2.2

If you need to override third party or Magento file from vendor directory

Here I override Block file "/var/www/html/magento/magentoproject/vendor/onestop/image-server/Block/Product/View/Gallery.php"

FYI : You need to create new extension when you wish to override default Vendor or Magento file

1. Create new Extension - Jaydip (Namespace)
2. Create Module directory - ImagegalleryAlt (Modulename)
3. Create new file like ( /var/www/html/magento/magentoproject/app/code/Jaydip/ImagegalleryAlt/etc/di.xml )

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <preference for="Onestop\ImageServer\Block\Product\View\Gallery" type="Jaydip\ImagegalleryAlt\Block\Product\View\Gallery" />
</config>
4. Create new directory "etc" and create file like : /var/www/html/magento/magentoproject/app/code/Jaydip/ImagegalleryAlt/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Jaydip_ImagegalleryAlt" setup_version="0.1.1">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Onestop_ImageServer"/>
        </sequence>
    </module>
</config>
5. Create new directory "Block/Product/View" and create file like : /var/www/html/magento/magentoproject/app/code/Jaydip/ImagegalleryAlt/Block/Product/View/Gallery.php
  • Copy file from old directory and paste to : /var/www/html/magento/magentoproject/app/code/Jaydip/ImagegalleryAlt/Block/Product/View/Gallery.php
  • Open : /var/www/html/magento/magentoproject/app/code/Jaydip/ImagegalleryAlt/Block/Product/View/Gallery.php
  • Change namespace like : namespace Jaydip\ImagegalleryAlt\Block\Product\View;
6. Upgrade data in Magento 2
php -dmemory_limit=5G bin/magento setup:upgrade
7. Static Content Deploy data  in Magento 2
php -dmemory_limit=5G bin/magento setup:static-content:deploy -f
8. Finish!!!

Thursday 12 April 2018

How to Find / Search a file using CMD / Terminal Command Linux Ubuntu


1. Find file from computer using CMD / Terminal Command

sudo find / -name index.php
2. Find file from Specific Directory using CMD / Terminal Command

sudo find /var/www/html/ -name index.php

Wednesday 27 December 2017

How to upload image / file in magento


<input type="file" name="image">

Select path of media directory

$path = Mage::getBaseDir() . DS . 'media' . DS . 'customerimages' . DS;
$imagename = $this->uploadImageFile($_FILES, $path);

Create functions

function uploadImageFile($filedata, $path){
   
    if(isset($filedata['image']) && $filedata['image']['error'] == 0){
        try{
           
            $uploader = new Varien_File_Uploader('image');
            $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
            $uploader->setAllowRenameFiles(true);
           
            if(!is_dir($path)){
                mkdir($path, 0755, true);
            }
            $ext = pathinfo($filedata['image']['name'], PATHINFO_EXTENSION);
            $uploader->save($path, date('Ymd') . "_" . date('his') . '.' . $ext);
            $uploadFile = $uploader->getUploadedFileName();
            if($uploadFile){
                return $uploadFile;
            } else {
                return 'File not uploaded!';
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    } else {
        return 'Please select image file!';
    }
}

Monday 25 December 2017

Export Big sql/mysql database using php file

Export Big sql/mysql database using php file

error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
$dbinfo = array(
    "host" => 'localhost',
    "user" => 'root',
    "pass" => 'root',
    "dbname" => 'dbname'
);

// Database Config
$sqlhost = $dbinfo["host"];
$dbuser = $dbinfo["user"];
$dbpassword = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
// filename
$file = date('Ymdhis');
echo shell_exec("mysqldump --add-drop-table -u $dbuser -p$dbpassword`cat /etc/psa/.psa.shadow` $dbname > $file.sql");
//shell_exec("mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file");
echo 'Finished!<br/>';

Thursday 21 December 2017

How to extract/ unzip ZIP / GZIP file using PHP

How to extract ZIP / GZIP file using PHP


<?php
$zip = new ZipArchive;
$res = $zip->open('myproject.zip');
if ($res === TRUE) {
  $zip->extractTo('/var/www/html/directoryname/');
  $zip->close();
  echo 'woot!';
} else {
  echo 'doh!';
}
?>

Tuesday 12 December 2017

How to check commit log of the particular file on Git or Bitbucket using terminal

How to check commit log of the particular file on Git or Bitbucket 


sudo git log -- app/code/local/jaydip/kansagra/controllers/CountryController.php

Friday 25 August 2017

Zip File Extract using PHP file

If you have not cpanel of the server so you can use this php file and extract uploaded zip file.

<?php
ini_set('display_errors', 1);
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('./rr/');
    $zip->close();
    echo "It's extract";
} else {
    echo 'failed';
}
?>

Saturday 12 August 2017

SoftException in Application.cpp:668: is writable by group

500 Error: File is writable by group

On occasion you may get a 500 page error (a blue/green error) when trying to run a PHP file in your account. When checking the error log which you can do via the cPanel account log in you may see the following line:

[Sat Aug 12 00:57:37 2017] [error] [client 103.240.34.54] SoftException in Application.cpp:668: Directory "/home/username/public_html/index.php" is writeable by group

This is due to the server running SuPHP and the files having higher permissions than allowed, 
 
How to solve this issue
 
Fix this problem you need to make sure your files are chmod 644 for all PHP based files and 755 for directories in order for them to work with SuPHP. You can easily do this by connecting via FTP with Filezilla Not from Cpanel and right clicking on the problem folders and files and selecting file permissions. Also set  0755 permission on public_html directory.

Monday 23 January 2017

How to import Big SQL file usign PHP with shell command into hosting server

<?php

error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');

$dbinfo = array(
    "host" => 'localhost',
    "user" => 'magentom_jaydip',
    "pass" => 'rmO22RQ%UbW0',
    "dbname" => 'magentom_jaydip'
);


// Database Config
$sqlhost = $dbinfo["host"];
$dbuser = $dbinfo["user"];
$dbpassword = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];

// filename
$file = "mg_jaydip.sql";

shell_exec("mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file");

echo 'Finished!<br/>';
?>

Wednesday 21 September 2016

How to get value from controller to phtml / view / template file in magento

You can use magento registry for set and get values

Set a value (in controller)

Mage::register('variable_name', $variable_value);

Get a value (in phtml/view/template)

$var_value = Mage::registry('variable_name');

Wednesday 14 September 2016

How to create custom model and resources file in existing module with database in magento

Step 1 : Update code in config.xml file of the model

<models>
...
...
<kanasagra_jaydip_resource>
...
...
<printsignsize>
   <table>name of your table</table>
</printsignsize>
</kanasagra_jaydip_resource>
</models>

Step 2 : Add new file in Model as Printsignsize.php

<?php
class Kanasagra_Jaydip_Model_Printsignsize extends Mage_Core_Model_Abstract
{

    const ENTITY    = 'kanasagra_jaydip_printsignsize';
    const CACHE_TAG = 'kanasagra_jaydip_printsignsize';
    protected $_eventPrefix = 'kanasagra_jaydip_printsignsize';
    protected $_eventObject = 'printsignsize';
    public function _construct()
    {
        parent::_construct();
        $this->_init('kanasagra_jaydip/printsignsize');
    }
    protected function _beforeSave()
    {
        parent::_beforeSave();
        $now = Mage::getSingleton('core/date')->gmtDate();
        if ($this->isObjectNew()) {
            $this->setCreatedAt($now);
        }
        $this->setUpdatedAt($now);
        return $this;
    }
    public function getPrintsignUrl()
    {
        return Mage::getUrl('kanasagra_jaydip/printsignsize/view', array('id'=>$this->getId()));
    }
    protected function _afterSave()
    {
        return parent::_afterSave();
    }
    public function getDefaultValues()
    {
        $values = array();
        $values['status'] = 1;
        return $values;
    }
 
}

Step 3 : Add new file in model/Resource as Printsignsize.php

<?php
class Kanasagra_Jaydip_Model_Resource_Printsignsize extends Mage_Core_Model_Resource_Db_Abstract
{
    public function _construct()
    {
        $this->_init('kanasagra_jaydip/printsignsize', 'entity_id');
    }
    public function lookupStoreIds($printsignId)
    {
        $adapter = $this->_getReadAdapter();
        $select  = $adapter->select()
            ->from($this->getTable('kanasagra_jaydip/printsignsize_store'), 'store_id')
            ->where('printsignsize_id = ?', (int)$printsignId);
        return $adapter->fetchCol($select);
    }
 
    protected function _afterLoad(Mage_Core_Model_Abstract $object)
    {
        if ($object->getId()) {
            $stores = $this->lookupStoreIds($object->getId());
            $object->setData('store_id', $stores);
        }
        return parent::_afterLoad($object);
    }
    protected function _getLoadSelect($field, $value, $object)
    {
        $select = parent::_getLoadSelect($field, $value, $object);
        if ($object->getStoreId()) {
            $storeIds = array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId());
            $select->join(
                array('signprint_printsignsize_store' => $this->getTable('kanasagra_jaydip/printsignsize_store')),
                $this->getMainTable() . '.entity_id = signprint_printsignsize_store.printsignsize_id',
                array()
            )
            ->where('signprint_printsignsize_store.store_id IN (?)', $storeIds)
            ->order('signprint_printsignsize_store.store_id DESC')
            ->limit(1);
        }
        return $select;
    }
    protected function _afterSave(Mage_Core_Model_Abstract $object)
    {
        $oldStores = $this->lookupStoreIds($object->getId());
        $newStores = (array)$object->getStores();
     
        if (empty($newStores)) {
            $newStores = (array)$object->getStoreId();
        }
        $table  = $this->getTable('kanasagra_jaydip/printsignsize_store');
        $insert = array_diff($newStores, $oldStores);
        $delete = array_diff($oldStores, $newStores);
        if ($delete) {
            $where = array(
                'printsignsize_id = ?' => (int) $object->getId(),
                'store_id IN (?)' => $delete
            );
            $this->_getWriteAdapter()->delete($table, $where);
        }
        if ($insert) {
            $data = array();
            foreach ($insert as $storeId) {
                $data[] = array(
                    'printsignsize_id'  => (int) $object->getId(),
                    'store_id' => (int) $storeId
                );
            }
            $this->_getWriteAdapter()->insertMultiple($table, $data);
        }
        return parent::_afterSave($object);
    }
}

Step 4 : Add new file in model/Resource/Printsignsize as Collection.php


<?php
class Kanasagra_Jaydip_Model_Resource_Printsignsize_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected $_joinedFields = array();
    protected function _construct()
    {
        parent::_construct();
        $this->_init('kanasagra_jaydip/printsignsize');
        $this->_map['fields']['store'] = 'store_table.store_id';
    }
    public function addStoreFilter($store, $withAdmin = true)
    {
        if (!isset($this->_joinedFields['store'])) {
            if ($store instanceof Mage_Core_Model_Store) {
                $store = array($store->getId());
            }
            if (!is_array($store)) {
                $store = array($store);
            }
            if ($withAdmin) {
                $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
            }
            $this->addFilter('store', array('in' => $store), 'public');
            $this->_joinedFields['store'] = true;
        }
        return $this;
    }
    protected function _renderFiltersBefore()
    {
        if ($this->getFilter('store')) {
            $this->getSelect()->join(
                array('store_table' => $this->getTable('kanasagra_jaydip/printsignsize_store')),
                'main_table.entity_id = store_table.printsignsize_id',
                array()
            )
            ->group('main_table.entity_id');
            /*
             * Allow analytic functions usage because of one field grouping
             */
            $this->_useAnalyticFunction = true;
        }
        return parent::_renderFiltersBefore();
    }
    protected function _toOptionArray($valueField='entity_id', $labelField='materials', $additional=array())
    {
        return parent::_toOptionArray($valueField, $labelField, $additional);
    }
    protected function _toOptionHash($valueField='entity_id', $labelField='materials')
    {
        return parent::_toOptionHash($valueField, $labelField);
    }
    public function getSelectCountSql()
    {
        $countSelect = parent::getSelectCountSql();
        $countSelect->reset(Zend_Db_Select::GROUP);
        return $countSelect;
    }
}
Step 5 : Add following code into your Controller File

$printsignsize = Mage::getModel('kanasagra_jaydip/printsignsize');
                 
$printsignsize
             ->setPrintsignid($printsign->getId())
             ->setSizename($size['sizename'])
             ->setSizeword($size['sizeword'])
             ->setSizeprice($size['sizeprice'])
             ->setStores($answer['votes']);
$printsignsize->save();

Step 6 : Create table in your database.

Step 7 : Don't forget clear the cache. Finish n Enjoy!!!