Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday 4 June 2020

How to convert a multidimensional Array To XML in PHP

function createxmlele($data, $name='root', &$doc=null, &$node=null){
        if ($doc==null){
            $doc = new DOMDocument('1.0','UTF-8');
            $doc->formatOutput = TRUE;
            $node = $doc;
        }

        if (is_array($data)){
            foreach($data as $var=>$val){
                if (is_numeric($var)){
                    $this->createxmlele($val, $name, $doc, $node);
                }else{
                    if (!isset($child)){
                        $child = $doc->createElement($name);
                        $node->appendChild($child);
                    }

                    $this->createxmlele($val, $var, $doc, $child);
                }
            }
        }else{
            $child = $doc->createElement($name);
            $node->appendChild($child);
            $textNode = $doc->createTextNode($data);
            $child->appendChild($textNode);
        }

        if ($doc==$node){
            return $doc;
        }
    }

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;
    }
}

Tuesday 24 September 2019

How to create pagination in shopify rest api using php

Shopify new API next page issue | page_info => invalid value

Shopify API version 2019-07 you do indeed need to use cursor-based pagination.

First make a normal API call, include the header response.

Then in the header response API, you will see the "link" parameter with rel next or previous.

Extract the page_info and then make another call with page_info.
The first API call is something like this:

https://.....@abc.myshopify.com/admin/api/2019-10/products.json?limit=2&published_status=published
To get header response from API response :
function getheaderarray($apiresponse){
       
        $data = explode("\n",$apiresponse);
        $headers['status'] = $data[0];
        array_shift($data);
        foreach($data as $part){
            $middle = explode(":",$part,2);
            if ( !isset($middle[1]) ) { $middle[1] = null; }
            $headers[trim($middle[0])] = trim($middle[1]);
        }
       
        return $headers;
  }  
Then the second API call is something like this:
https://.....@abc.myshopify.com/admin/api/2019-10/products.json?limit=2&page_info=abcdsf21asdf3afdfdfd1safd51s3f1x32ref4asdj
When you make the second call, do not add any filers as the filters will be applied from the first call.
FYI: if your testing in a browser due to the way the link is in angle brackets, it will be hidden, so just view source code in your developer environment.

Friday 2 August 2019

How to set cron job in heroku in PHP | Codeigniter

Step 1:  Install Heroku Scheduler add-ons from Heroku.


Step 2: Goto Heroku Scheduler page and add Job, set time interval and add command " php /app/index.php orderupdate crontset jaydip "
  1. php = server language
  2. /app/index.php = Path of the project root index.php
  3. orderupdate = name of controller
  4. crontset = name of function
  5. jaydip = variable name which you want to get into crontset function
Step 3: open Orderupdate.php controller

public crontset function($name){

echo $name;

}

Thursday 18 July 2019

How to run composer install in another PHP version

How to tell Composer to use Different PHP Version
#ea-php72 /opt/cpanel/composer/bin/composer install
You can get list of php by using following command
# ls /usr/bin/ | grep php 

Check list of Installed PHP versions and PHP CLI version into cpanel

# ls /usr/bin/ | grep php
Result
alt-php-mysql-reconfigure@
alt-php-mysql-reconfigure.py*
ea-php54@
ea-php54-pear@
ea-php54-pecl@
ea-php55@
ea-php55-pear@
ea-php55-pecl@
ea-php56@
ea-php56-pear@
ea-php56-pecl@
ea-php70@
ea-php70-pear@
ea-php70-pecl@
ea-php71@
ea-php71-pear@
ea-php71-pecl@
ea-php72@
ea-php72-pear@
ea-php72-pecl@
lsphp*
php*
php5@
php5-cli@
php-cgi@
php-cli@



Thursday 13 June 2019

Saturday 8 June 2019

How to add Language of custom plugin in Admin dashboard in wordpress



Add text for language like this "<?php echo __('General options', 'roomle'); ?>"

Step 1 : Create plugin like "roomle"
Step 2 : Set domain path into plugin file like following screenshot

Step 3 : Create "roomle.pot" inside /wp-content/plugins/roomle/languages/
Step 4 : Add like following text inside "roomle.pot" file (FYI : Don't add any translation language just add as (msgstr = ""))
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-06-08 12:08+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#: functions.php:29
#, php-format
msgid "Roomle"
msgstr ""
#: functions.php:47
#, php-format
msgid "Select"
msgstr ""
#: functions.php:56
msgid "Roomle product type"
msgstr ""
Step 5 : Download the free plugin called Loco Translate from here. Or add directly from the WordPress administration via Plugins > Add New. (https://wordpress.org/plugins/loco-translate/)
Step 6 : Install and Activate Loco plugin
Step 7 : Click on Plugin inner menu of Loco after that click into your plugin from list.

Step 8 : Click on New language
Step 9 : Choose a language which you wish to translate (Here translate from English to Spanish)

Step 10 : See Source text (its from "roomle.pot" ) you need to add text of translate language.

Step 11 : After create all text to Spanish language, Check "/roomle/wp-content/languages/plugins/" directory. your 2 file is created here like "roomle-es_ES.mo" and "roomle-es_ES.po"
Step 12 : If you wish to check so you need to download wordpress in spanish language and setup wordpress and check

Also this answer for following question

  • How to Change the Admin plugin Language
  • How to add language into your plugin
  • How to add language into your custom plugin

Thursday 9 May 2019

Access denied for user 'root'@'localhost' even password is correct

Error : SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket
Step 1 : For backup = cp -rfv /var/lib/mysql /var/lib/mysql$(date +%s)
Step 2 : sudo /etc/init.d/mysql stop
Step 3 : sudo mysqld_safe --skip-grant-tables & (If process will not complete after 5 minuts keep this window open and open another terminal window)
Step 4 :  mysql -u root -p 
Step 5 : FLUSH PRIVILEGES;
Step 6 : UPDATE user SET Grant_priv = 1, Super_priv = 1 WHERE user = 'root'
Step 7 : update user set password=PASSWORD("Franki3r0s3") where User='root';
Step 8 : GRANT ALL PRIVILEGES ON . TO 'root'@'localhost' IDENTIFIED BY 'anki8f0s3';

Additional commands : 
1. mysql# show users;
2. mysql# SELECT User FROM mysql.user;
3. ps -e | grep mysqld
4. kill -kill 16300
5. ps -x



Friday 22 March 2019

How to make backgroud process in php using shell_exec

Create background.php file
<?php
$post_id = ['post_id'=>10];
$post_id = json_encode($post_id);
$pid = shell_exec("php /var/www/html/magento/dump/exportfile.php $post_id alert >> /var/www/html/magento/dump/test.log & echo $!");
echo $pid;
Create checkprocess.php file
$pid = 1254; // Copy pid from background.php
if (file_exists("/proc/$pid" )){
    echo "process with a pid = $pid is running";
}
 Create exportfile.php file
//Create this file with high time taking script

Monday 31 December 2018

sql_mode=only_full_group_by is incompatible in PHP mysql query with GROUP BY codeigniter


#1055 - Expression #24 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'customers.first_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Add $this->db->query("SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));") line above your query.

See Example :
$this->db->query("SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));");
$this->db->select('*, customers.first_name, customers.last_name, customers.id');
$this->db->select("(SELECT count(video_id) FROM customer_videos WHERE c.customer_id = customer_videos.customer_id AND (created_at >= '$from' OR created_at <= '$todate')) as seen");
$this->db->join('customers', 'customers.id = c.customer_id', 'left');
$this->db->group_by('c.customer_id');
$this->db->from('customer_videos as c');
$query = $this->db->get();
echo "<pre/>"; print_r($query->result());exit;
return $query->result_array();

Wednesday 28 November 2018

Join Query with LIKE in PHP Mysql

Join Query with %LIKE% function in MYSQL PHP

SELECT `customers`.*, `admin`.`firstname` AS `salespersonfname`, `admin`.`lastname` AS `salespersonlname`
FROM `customers`
LEFT JOIN `admin` ON customers.tags LIKE CONCAT('%', `admin`.firstname, ' ', `admin`.lastname, '%')
ORDER BY `id` DESC

Wednesday 19 September 2018

How to change url without reloading page in jQuery | Javascript | PHP

<?php
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$lastchar = substr($actual_link, -1);
if($lastchar == '/'){
$redirecturl = rtrim($actual_link,"/");
?>
<script>
    window.history.pushState('page2', 'Title', '<?php echo $redirecturl; ?>');
</script>
<?php } ?>

Wednesday 1 August 2018

How to get Missing / Deleted primary key from Mysql / PHP Database

select a.id + 1 RemoveIds
from jaydip_kansagra a
left join jaydip_kansagra b
  on a.id = b.id - 1
where b.id is null
  and a.id < 14481

14481 = Last Primary Key 

Saturday 14 July 2018

Re-Arrange primary key | INDEXING in MYSQL

Re-Arrange primary key | INDEXING in MYSQL
SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;
Last number of records
ALTER TABLE `jaydipkansagra` auto_increment = 720418;  

Saturday 23 June 2018

Remove special characters from string php

$title = 'Apple Fritter E Juice 120ml By Loaded E Liquid';
$urltitle = str_replace(' ', '-', $title);
$urlkey = preg_replace("/[^a-zA-Z0-9]+/[^a-zA-Z0-9]+/", "", strtolower($urltitle));
echo $urlkey;

How to check image is valid or not in php from URL in PHP

$imagePath = "https://jaydip.kansagra.com/image.jpg";
if (@getimagesize($imagePath)) {
   echo 'Image exists';
} else {
      echo 'Image not exists';
}

Wednesday 6 June 2018

How to Switch / Change / Downgrade from PHP 7.2 to 7.1 on Ubuntu 16.04 / 18.04 , Apache | PHP

Follow following steps

1. sudo add-apt-repository ppa:ondrej/php
2. sudo apt-get update
3. sudo apt-get install php7.1
4. sudo apt-get install php7.1-cli php7.1-common php7.1-json php7.1-opcache php7.1-mysql php7.1-mbstring php7.1-mcrypt php7.1-zip php7.1-fpm
5. sudo a2dismod php7.2
6. sudo a2enmod php7.1
7. systemctl restart apache2
8. sudo rm /usr/bin/php
9. sudo ln -s /usr/bin/php7.1 /usr/bin/php

Tuesday 5 June 2018

shell_exec("mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file") not working in PHP

I try to execute query from PHP / CMD / Terminal


mysql -u admin --password='jaydip' --host='localhost' 'mg_kansagra' < '/var/www/html/magento/dump/db.sql'


Its show me following error

mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 3167 (HY000) at line 17: The 'INFORMATION_SCHEMA.SESSION_VARIABLES' feature is disabled; see the documentation for 'show_compatibility_56'

ANSWER

Run the following query in your MySQL database:
set @@global.show_compatibility_56=ON;