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

Saturday 14 April 2018

SQLSTATE[HY000]: General error: 1 Can't create/write to file '/tmp/#sql_83d_0.MYI' (Errcode: 28) Magento / PHP

Problem can be connected with inodes. Maybe you have too many small files and your inodes are full. You can check inode status with df -i 

Tuesday 23 January 2018

How to set background color into transparent image Imagick PHP

ini_set('display_errors',1);
header('Content-type: image/png');
$strInputFile = 'front.png'; // transparent image
$im = new Imagick($strInputFile);
$im->setImageBackgroundColor('green');
$im = $im->flattenImages();
echo $im;exit;

Tuesday 2 January 2018

How to install extensions in php 7 cent os


Install extensions in php 7 cent os follow these steps

1. curl 'https://setup.ius.io/' -o setup-ius.sh
2. sudo bash setup-ius.sh
3. sudo yum install -y mod_php70w php70w-cli php70w-mysqlnd php70w-json php70w-gd php70w-dom php70w-simplexml php70w-mcrypt php70w-intl httpd mysql-server git

Saturday 30 December 2017

How to download and Extract Uncompress zip / gz file from URL in PHP


File zip / gz download from URL

ini_set('display_errors', 1);
$dbname = 'db_'.date('Ymdhis').".gz";
$url = 'http://www.domainname.com/backups/bkp30122017.gz';
file_put_contents($dbname, fopen($url, 'r'));

Extract / Uncompress GZ / ZIP file

try{
    //This input should be from somewhere else, hard-coded in this example
    $file_name = $dbname;
    // Raising this value may increase performance
    $buffer_size = 4096; // read 4kb at a time
    $out_file_name = str_replace('.gz', '.sql', $file_name);
    // Open our files (in binary mode)
    $file = gzopen($file_name, 'rb');
    $out_file = fopen($out_file_name, 'wb');
    // Keep repeating until the end of the input file
    while (!gzeof($file)) {
        // Read buffer-size bytes
        // Both fwrite and gzread and binary-safe
        fwrite($out_file, gzread($file, $buffer_size));
    }
    // Files are done, close files
    fclose($out_file);
    gzclose($file);
} catch (Exception $ex) {
    echo $ex->getMessage();
}

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 Enable SSL certificate in cloud.google.com

How to Enable SSL certificate in cloud.google.com


Open cloud.google.com
1. Goto your VM instance
2. Click on name of your instance
3. Edit instance
4. Checked "Firewalls Allow HTTPS traffic" and save


5. Goto Network services -> Load balancing -> Edit / add your Load balancer
6. Add / Edit "https protocol" on Frontend configuration and select / create new certificate




7. Again goto your VM instance list
8. Click on SSH



9. After open google cloud ssh window, write "sudo su" on ssh window
10. ssh-keygen
11. gcloud compute ssl-certificates list
12. gcloud compute ssl-certificates describe ssl2111(name of your ssl certificate)
13. nano /etc/apache2/sites-available/default-ssl.conf
Upload certificate files and update path here where you place your SSLCertificateFiles
<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        <Directory /var/www/html/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>
    DocumentRoot /var/www/html

    ..........
    ..........
    ..........
    ..........
    #SSLCertificateFile     /etc/ssl/certs/ssl-cert-snakeoil.pem
    #SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
    SSLCertificateFile "/var/www/html/cert/cert.pem"
    SSLCertificateKeyFile "/var/www/html/cert/privkey.key"
    SSLCertificateChainFile "/var/www/html/cert/chain.crt"
    ..........
    ..........
    ..........
    ..........
</VirtualHost>
</IfModule>

14. sudo service apache2 restart
15. gcloud auth login
16. gcloud config set project projectname-010412(Your project id)
17. sudo a2ensite default-ssl
18. service apache2 reload
19. sudo a2enmod ssl
20. sudo service apache2 restart
21. gcloud compute firewall-rules create www-firewall     --target-tags https-tag --allow tcp:443
22. service apache2 reload 

That's It, Please check your SSL 

Saturday 28 October 2017

Get Address of customer from database Query in Magento PHP Mysql

SELECT
`entity_id` as `entity_id`,
`firstname`.`value` as `First_Name`,
`surname`.`value` as `Surname`,
`telephone`.`value` as `Telephone`,
`country`.`value` as `country`,
`region`.`value` as `region`,
`statecounty`.`value` as `statecounty`,
`city`.`value` as `city`,
`company`.`value` as `company`,
`street`.`value` as `street1`,
`customer_entity`.`created_at`,
`customer_entity`.`updated_at`
FROM
`customer_address_entity_varchar` as `country`
INNER JOIN
`customer_address_entity_varchar` as  `firstname` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `surname` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `telephone` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `region` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `statecounty` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `city` USING (`entity_id`)
INNER JOIN
`customer_address_entity_varchar` as  `company` USING (`entity_id`)
INNER JOIN
`customer_address_entity_text` as  `street` USING (`entity_id`)
INNER JOIN
`customer_entity` USING (`entity_id`)
WHERE
`firstname`.`attribute_id` = 20  &&
`surname`.`attribute_id` = 22  &&
`country`.`attribute_id` = 27 &&
`region`.`attribute_id` = 28 &&
`statecounty`.`attribute_id` = 144 &&
`city`.`attribute_id` = 26 &&
`company`.`attribute_id` = 24 &&
`street`.`attribute_id` = 25 &&
`telephone`.`attribute_id` = 31

Thursday 14 September 2017

Create Zip file of all php files from your server using PHP file

Create Zip file of all php files from your server using PHP file. If you have not cpanel of the server so you can use this php file and compress files as zip file.

Just you need put this file into root directory of the server (ex.public_html/createzip.php)

And run this file from browser eg. http://domain.com/createzip.php

Create one file name : createzip.php and put following code into the file. and run file from browser.

<?php
// Get real path for our folder
$realpath = getcwd();
$rootPath = realpath($realpath);
// Initialize archive object
$zip = new ZipArchive();
$filename = 'bk_'.date('YmdHis').'.zip';
$zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);
        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}
// Zip archive will be created only after closing object
$zip->close();

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.

Saturday 22 July 2017

How to get the latest record in each group using GROUP BY


In PHP MySQL

SELECT `main_table`.`rebate_amount`, `main_table`.`companyname`, (SELECT target FROM batecash WHERE id = MAX(main_table.id)) AS `maxtarget`, SUM(rebate_amount) AS `rebate_amount`, SUM(invoiceamount) AS `purchase_amount`, MAX(id) AS `max_id`, `main_table`.`rebatetarget`, YEAR(created_at) yr, QUARTER(created_at) qt FROM `batecash` AS `main_table` WHERE (customerid = '5') GROUP BY YEAR(created_at), QUARTER(created_at) ORDER BY `created_at` DESC

 In Magento

$rebatecount = Mage::getModel('rebatereward/batecash')->getCollection()
                    ->addFieldToSelect('rebate_amount')
                    ->addFieldToSelect('companyname')
                    ->addFieldToFilter('orderstatus', array('eq' => 'completed'))
                    ->addFieldToFilter('addressid', array('eq' => $address->getId()))
                    ->addFieldToFilter('customerid', array('eq' => $this->getCustomer()->getId()));

            $rebatecount->getSelect()->columns("(SELECT rebatetarget FROM batecash WHERE id = MAX(main_table.id)) as maxtarget");
            $rebatecount->getSelect()
                    ->columns('SUM(rebate_amount) as rebate_amount')
                    ->columns('SUM(invoiceamount) as purchase_amount')
                    ->columns('MAX(id) as max_id')
                    ->columns('rebatetarget')
                    ->columns('YEAR(created_at) yr, QUARTER(created_at) qt')
                    ->group('YEAR(created_at), QUARTER(created_at)')
                    ->order(array('created_at DESC'));

Wednesday 29 March 2017

How to install PHP, apache and mysql in ununtu 14.04

https://www.howtoforge.com/ubuntu-lamp-server-with-apache2-php5-mysql-on-14.04-lts

https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-12-04

Enable .htaccess

sudo a2enmod rewrite
sudo service apache2 restart
sudo nano /etc/apache2/sites-available/000-default.conf
<Directory "/var/www/html">
AllowOverride All
</Directory>

sudo service apache2 restart

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/>';
?>

Tuesday 13 September 2016

How to Check URL is Secure or Not in amazon EC2 Server in PHP / Codeigniter SSL

You can use following code for  Check URL is Secure or Not in amazon EC2 Server


if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
      $_SERVER['HTTPS'] = 'on';
} else {
      $_SERVER['HTTPS'] = 'off';
}

Tuesday 30 August 2016

How to Get / Upload / Delete / Update file in using SFTP / FTP in PHP, Codeigniter Library

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol

Here is a small code on how to read the folder and download all files:

Controller.php

      $params = array('host' => $shopdata->ftphost, 'port' => 22);
            $this->load->library('sftpconnection', $params);
         
            $this->sftpconnection->login($shopdata->ftpuser, $shopdata->ftppass);
            //$this->sftpconnection->uploadFile("http://localhost/shopify/inventorymanagement/uploads/sku.csv", "/codetest/test.csv");
            //$result = $this->sftpconnection->scanFilesystem("/TEST/DESADV");
            $result = $this->sftpconnection->downloadFiles("$folder","/TEST/DESADV/");
            pre($result);
Create Library file : Sftpconnection.php

<?php
/*
  Sftp connection in PHP
  Created: Feb 18th, 2016
  Modified: Feb 18th, 2016
  Version: 1.0.1
  Auther : Jaydip Kanasagra
 */

//this function is just to make the code a little cleaner
class Sftpconnection {

    private $connection;
    private $sftp;

    public function __construct($config) {
        $host = $config['host'];
        $port = $config['port'];
        $this->connection = @ssh2_connect($host, $port);
        if (!$this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password) {
        if (!@ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
            "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (!$this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (!$stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }

    public function receiveFile($remote_file, $local_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (!$stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents($local_file, $contents);
        @fclose($stream);
    }
 
    public function downloadFiles($local_dir, $remote_dir) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_dir";
        $downloadedfiles = $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
     
        foreach ($files as $file)
        {
            $currentdir = $this->getCurrentdirfiles('uploads/ftpfiles/TEST/JAYDIP/');
            if(in_array($file, $currentdir)){
                continue;
            }
         
            echo "Copying file: $file<br>";
            if (!$remote = @fopen("ssh2.sftp://{$sftp}{$remote_dir}{$file}", 'r'))
            {
                echo "Unable to open remote file: $file\n";
                continue;
            }

            if (!$local = @fopen($local_dir . $file, 'w'))
            {
                echo "Unable to create local file: $file\n";
                continue;
            }

            $read = 0;
            $filesize = filesize("ssh2.sftp://{$sftp}/{$remote_dir}{$file}");
            while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
            {
                $read += strlen($buffer);
                if (fwrite($local, $buffer) === FALSE)
                {
                    echo "Unable to write to local file: $file\n";
                    break;
                }
            }
            $downloadedfiles[] = $file;
            fclose($local);
            fclose($remote);
        }

        return $downloadedfiles;
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
 
    function getCurrentdirfiles($dir){
        //$dir = "ftpfiles/TEST/JAYDIP/";
        $listfiles = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $listfiles[] = $file;
                }
            }
        }
        closedir($handle);
        return $listfiles;
    }

}

?>

How to connect WSDL file with XML data with Basic Authentication in php

HTTP Auth works with SOAP Client, However you cannot access password protected WSDL files 

This is Simple example to auth webservice using soapClient
<?php
ini_set('display_errors', 1);
/*$client = new SoapClient('Materials_Availability.wsdl');
var_dump($client->__getFunctions());*/
$wsdl = "http://localhost/test/soap_wsdl/stock.wsdl?wsdl";
$client = new SoapClient($wsdl, array('login' => "******", 'password' => "******"));
echo ''.print_r($client,true).'';
$result = $client->__getFunctions();
echo '<pre>';print_r($result);
//$file = file_get_contents('soapxml.xml');
//echo $file;exit;
$array = array(
    'REQUEST'=> array(
        'MATERIALS'=> array(
                0=>array(
                    'MATERIAL_NUMBER'=>123654,
                    'MATERIAL_NUMBER_TYPE'=>'JAY',
                    'REQUEST_TYPE'=>array(
                        'TYPE'=>1
                    )
                ),
                1=>array(
                    'MATERIAL_NUMBER'=>654789,
                    'MATERIAL_NUMBER_TYPE'=>'JAM',
                    'REQUEST_TYPE'=>array(
                        'TYPE'=>2
                    )
                )
            )
        )
    );
print_r($array);
$result = $client->getMaterialAvailability($array);
print_r($result);
exit;
?>

Saturday 9 July 2016

What is the scope of variables in JavaScript?

JavaScript programmers are practically ranked by how well they understand scope.

1. A globally-scoped variable

var a = 1;
// global scope
function one() {
  alert(a); // alerts '1'
}

2. Local scope

var a = 1;
function two(a) {
  alert(a); // alerts the given argument, not the global value of '1'
}
// local scope again
function three() {
  var a = 3; // alerts '3'
  alert(a);
}

3. Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

var a = 1;
function four() {
  if (true) {
    var a = 4;
  }
  alert(a); // alerts '4', not the global value of '1'
}

4. Intermediate: Object properties

var a = 1;
function five() {
  this.a = 5;
}
alert(new five().a); // alerts '5'

5. Advanced: Closure

var a = 1;
var six = (function() {
  var a = 6;
  return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
  };
})();

6. Advanced: Prototype-based scope resolution

var a = 1;
function seven() {
  this.a = 7;
}
// [object].prototype.property loses to
// [object].property in the lookup chain. For example...
// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;
// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;
alert(new seven().a); // alerts '7'
alert(new seven().b); // alerts '8'

7. Global+Local: An extra complex Case

var x = 5;
(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();
This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:
var x = 5;
(function () {
    var x;
    console.log(x);
    x = 10;
    console.log(x);
})();

8. Catch clause-scoped variable

var e = 5;
console.log(e);
try {
    throw 6;
} catch (e) {
    console.log(e);
}
console.log(e);

Friday 8 July 2016

How to Append Javascript/Jquery code run using PHP

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var option_count = "text something";
$(document).ready(function(){
$('div').append('<?php echo add_option("' + option_count + '"); ?>');
});
</script>
<div></div>
<?php
ini_set('display_errors', 1);
function add_option($count) { ob_start();
echo $count;
    $stuff = ob_get_contents();
    ob_end_clean();
    echo replace_newline($stuff);
}
function replace_newline($string) {
  return trim((string)str_replace(array("\r", "\r\n", "\n", "\t"), ' ', $string));
}
?>