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

Monday 21 June 2021

Get Last Executed Query in Laravel

 Last Query in Laravel

DB::enableQueryLog();
$product = Product::get();
$query = DB::getQueryLog();
dd($query);
  1. \DB::enableQueryLog();
  2. $list = \DB::table("categories")->get();
  3. $query = \DB::getQueryLog();
  4. print_r(end($query));

Friday 21 June 2019

Best leading PHP frameworks in 2019

The top 10 PHP frameworks

Here’s a list of the best PHP frameworks, based on popularity and ability to facilitate application development.

  1. Laravel
  2. Symfony
  3. CodeIgniter
  4. Zend
  5. CakePHP
  6. FuelPHP
  7. Yii 2
  8. Phalcon
  9. Slim
  10. PHPixie


1. Laravel


If frameworks were people, Laravel would probably be the king. If you want to code beautiful designs, you’re looking for Laravel since it’s positioned as the go-to PHP framework for web artisans.
The reason for its wide popularity boils down to ease of use and virtually no learning curve. And despite that, it’s a framework developer use for some serious work. So it may seem like a simple tool at first, but it’s a beast when it comes to producing concrete work.

2. Symfony

When it comes to developing large-scale enterprise projects, Symfony makes a perfect choice amongst the PHP frameworks. Its ecosystem is a huge one, with a big set of reusable components and an active community of developers. The components serve the purpose of completing diverse tasks such as for creation, the configuration of objects, authentication, routing, templating, and much more. These components are being used to power up projects such as Drupal, Laravel, PHPBB, PIWIk, and OROCRM.

3. CodeIgniter

CodeIgniter is one of the oldest frameworks but is simple and powerful. It can easily be installed and requires minimal user configuration. It works perfectly on almost all shared and dedicated hosting platforms. CodeIgniter isn’t entirely based on the MVC framework. Models and Views are optional, but Controller classes are a must. Another strength of CodeIgniter is speed. It runs faster with database tasks in comparison to other frameworks. CodeIgniter is well documented and a good framework to start with for PHP beginners.

Sunday 21 January 2018

Delete Documents in MongoDB Collection

Delete Methods

MongoDB provides the following methods to delete documents of a collection:
db.collection.remove({})Delete a single document or all documents that match a specified filter.
db.collection.deleteOne({})Delete at most a single document that match a specified filter even though multiple documents may match the specified filter.
db.collection.deleteMany({})Delete all documents that match a specified filter.
Eg:-  db.users.deleteMany({ status : "A" })

      db.users.deleteOne( { status: "D" } )

      db.getCollection('Users').find({$and:[{"cid":2}, {"created-at":{ "$gte" : new ISODate("2018-01-22")}} ]})

Thursday 2 February 2017

Publishing your android App to Google Play Store

Publishing your app

$ cordova plugin rm cordova-plugin-console
$ cordova build --release android
This will generate a release build based on the settings in your config.xml. Your Ionic app will have preset default values in this file, but if you need to customize how your app is built, you can edit this file to fit your preferences. Check out the config.xml file documentation for more information.
Next, we can find our unsigned APK file in platforms/android/build/outputs/apk. In our example, the file was platforms/android/build/outputs/apk/HelloWorld-release-unsigned.apk. Now, we need to sign the unsigned APK and run an alignment utility on it to optimize it and prepare it for the app store. If you already have a signing key, skip these steps and use that one instead.
Let’s generate our private key using the keytool command that comes with the JDK. If this tool isn’t found, refer to the installation guide:
$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000
You’ll first be prompted to create a password for the keystore. Then, answer the rest of the nice tools’s questions and when it’s all done, you should have a file called my-release-key.keystore created in the current directory.
Note: Make sure to save this file somewhere safe, if you lose it you won’t be able to submit updates to your app!
To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore HelloWorld-release-unsigned.apk alias_name
This signs the apk in place. Finally, we need to run the zip align tool to optimize the APK. The zipalign tool can be found in /path/to/Android/sdk/build-tools/VERSION/zipalign. For example, on OS X with Android Studio installed, zipalign is in ~/Library/Android/sdk/build-tools/VERSION/zipalign:
$ zipalign -v 4 HelloWorld-release-unsigned.apk HelloWorld.apk
Now we have our final release binary called HelloWorld.apk and we can release this on the Google Play Store for all the world to enjoy!
(There are a few other ways to sign APKs. Refer to the official Android App Signing documentation for more information.)

keytool -genkey -v -keystore acharyasri-key.keystore -alias acharyasri -keyalg RSA -keysize 2048 -validity 10000

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore acharyasri-key.keystore platforms/android/build/outputs/apk/android-release-unsigned.apk acharyasri

zipalign -v 4 E:/MobileApps/aacharya/android/build/outputs/apk/android-release-unsigned.apk Acharyasri.apk

Google Play Store

Now that we have our release APK ready for the Google Play Store, we can create a Play Store listing and upload our APK.
To start, you’ll need to visit the Google Play Store Developer Console and create a new developer account. Unfortunately, this is not free. 

Monday 18 January 2016

CodeIgniter Remove index.php By .htaccess

Steps To Remove index.php using .htaccess:-


Step:-1  Open the file config.php located in application/config path.  Find and Replace the below code in config.php  file.
//  Find the below code

$config['index_page'] = "index.php"

//  Remove index.php

$config['index_page'] = ""
Step:-2  Go to your CodeIgniter folder and create .htaccess  file.

Path:
Your_website_folder/
application/
assets/
system/
user_guide/
.htaccess <--------- this file
index.php
license.txt
Step:-3  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>
Step:-4  In some cases the default setting for uri_protocol does not work properly. To solve this issue just open the file config.php located in application/configand then find and replace the code as:
//  Find the below code

$config['uri_protocol'] = "AUTO"

//  Replace it as

$config['uri_protocol'] = "REQUEST_URI" 

Thursday 11 September 2014

PrestaShop Remove Subcategories List From Category Page

PrestaShop Remove Subcategories List From Category Page

Remove this part of the code from category.tpl
{if isset($subcategories)}<!-- Subcategories --><div id="subcategories"><h3>{l s='Subcategories'}</h3><ul class="inline_list">{foreach from=$subcategories item=subcategory}<li><a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}" title="{$subcategory.name|escape:'htmlall':'UTF-8'}">{if $subcategory.id_image}<img src="{$link->getCatImageLink($subcategory.link_rewrite, $subcategory.id_image, 'medium')}" alt="" width="{$mediumSize.width}" height="{$mediumSize.height}" />{else}<img src="{$img_cat_dir}default-medium.jpg" alt="" width="{$mediumSize.width}" height="{$mediumSize.height}" />{/if}</a><br /><a href="{$link->getCategoryLink($subcategory.id_category, $subcategory.link_rewrite)|escape:'htmlall':'UTF-8'}">{$subcategory.name|escape:'htmlall':'UTF-8'}</a></li>{/foreach}</ul><br class="clear"/></div>{/if}

Monday 21 July 2014

Read xls or xlsx file using PHP

PHP XLSXReader Sample

<?php 
date_default_timezone_set('UTC');
require('XLSXReader.php');
$xlsx = new XLSXReader('Companies.xlsx');
$sheetNames = $xlsx->getSheetNames();

?>
<?php 
foreach($sheetNames as $sheetName) {
$sheet = $xlsx->getSheet($sheetName);
?>
<h3><?php echo escape($sheetName);?></h3>
<?php 
array2Table($sheet->getData());
}

?>
<?php 
$data = array_map(function($row) {
$converted = XLSXReader::toUnixTimeStamp($row[0]);
return array($row[0], $converted, date('c', $converted), $row[1]);
}, $xlsx->getSheetData('Dates'));
array_unshift($data, array('Excel Date', 'Unix Timestamp', 'Formatted Date', 'Data'));
array2Table($data);

function array2Table($data) {
echo '<table>';
foreach($data as $row) {
echo "<tr>";
foreach($row as $cell) {
echo "<td>" . escape($cell) . "</td>";
}
echo "</tr>";
}
echo '</table>';
}

function debug($data) {
echo '<pre>';
print_r($data);
echo '</pre>';
}

function escape($string) {
return htmlspecialchars($string, ENT_QUOTES);
}?>



<?php



class XLSXReader {
protected $sheets = array();
protected $sharedstrings = array();
protected $sheetInfo;
protected $zip;
public $config = array(
'removeTrailingRows' => true
);
// XML schemas
const SCHEMA_OFFICEDOCUMENT  =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
const SCHEMA_RELATIONSHIP  =  'http://schemas.openxmlformats.org/package/2006/relationships';
const SCHEMA_OFFICEDOCUMENT_RELATIONSHIP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
const SCHEMA_SHAREDSTRINGS =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
const SCHEMA_WORKSHEETRELATION =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';

public function __construct($filePath, $config = array()) {
$this->config = array_merge($this->config, $config);
$this->zip = new ZipArchive();
$status = $this->zip->open($filePath);
if($status === true) {
$this->parse();
} else {
throw new Exception("Failed to open $filePath with zip error code: $status");
}
}

// get a file from the zip
protected function getEntryData($name) {
$data = $this->zip->getFromName($name);
if($data === false) {
throw new Exception("File $name does not exist in the Excel file");
} else {
return $data;
}
}

// extract the shared string and the list of sheets
protected function parse() {
$sheets = array();
$relationshipsXML = simplexml_load_string($this->getEntryData("_rels/.rels"));
foreach($relationshipsXML->Relationship as $rel) {
if($rel['Type'] == self::SCHEMA_OFFICEDOCUMENT) {
$workbookDir = dirname($rel['Target']) . '/';
$workbookXML = simplexml_load_string($this->getEntryData($rel['Target']));
foreach($workbookXML->sheets->sheet as $sheet) {
$r = $sheet->attributes('r', true);
$sheets[(string)$r->id] = array(
'sheetId' => (int)$sheet['sheetId'],
'name' => (string)$sheet['name']
);
}
$workbookRelationsXML = simplexml_load_string($this->getEntryData($workbookDir . '_rels/' . basename($rel['Target']) . '.rels'));
foreach($workbookRelationsXML->Relationship as $wrel) {
switch($wrel['Type']) {
case self::SCHEMA_WORKSHEETRELATION:
$sheets[(string)$wrel['Id']]['path'] = $workbookDir . (string)$wrel['Target'];
break;
case self::SCHEMA_SHAREDSTRINGS:
$sharedStringsXML = simplexml_load_string($this->getEntryData($workbookDir . (string)$wrel['Target']));
foreach($sharedStringsXML->si as $val) {
if(isset($val->t)) {
$this->sharedStrings[] = (string)$val->t;
} elseif(isset($val->r)) {
$this->sharedStrings[] = XLSXWorksheet::parseRichText($val);
}
}
break;
}
}
}
}
$this->sheetInfo = array();
foreach($sheets as $rid=>$info) {
$this->sheetInfo[$info['name']] = array(
'sheetId' => $info['sheetId'],
'rid' => $rid,
'path' => $info['path']
);
}
}

// returns an array of sheet names, indexed by sheetId
public function getSheetNames() {
$res = array();
foreach($this->sheetInfo as $sheetName=>$info) {
$res[$info['sheetId']] = $sheetName;
}
return $res;
}

public function getSheetCount() {
return count($this->sheetInfo);
}

// instantiates a sheet object (if needed) and returns an array of its data
public function getSheetData($sheetNameOrId) {
$sheet = $this->getSheet($sheetNameOrId);
return $sheet->getData();
}

// instantiates a sheet object (if needed) and returns the sheet object
public function getSheet($sheet) {
if(is_numeric($sheet)) {
$sheet = $this->getSheetNameById($sheet);
} elseif(!is_string($sheet)) {
throw new Exception("Sheet must be a string or a sheet Id");
}
if(!array_key_exists($sheet, $this->sheets)) {
$this->sheets[$sheet] = new XLSXWorksheet($this->getSheetXML($sheet), $sheet, $this);

}
return $this->sheets[$sheet];
}

public function getSheetNameById($sheetId) {
foreach($this->sheetInfo as $sheetName=>$sheetInfo) {
if($sheetInfo['sheetId'] === $sheetId) {
return $sheetName;
}
}
throw new Exception("Sheet ID $sheetId does not exist in the Excel file");
}

protected function getSheetXML($name) {
return simplexml_load_string($this->getEntryData($this->sheetInfo[$name]['path']));
}

// converts an Excel date field (a number) to a unix timestamp (granularity: seconds)
public static function toUnixTimeStamp($excelDateTime) {
if(!is_numeric($excelDateTime)) {
return $excelDateTime;
}
$d = floor($excelDateTime); // seconds since 1900
$t = $excelDateTime - $d;
return ($d > 0) ? ( $d - 25569 ) * 86400 + $t * 86400 : $t * 86400;
}

}

class XLSXWorksheet {

protected $workbook;
public $sheetName;
protected $data;
public $colCount;
public $rowCount;
protected $config;

public function __construct($xml, $sheetName, XLSXReader $workbook) {
$this->config = $workbook->config;
$this->sheetName = $sheetName;
$this->workbook = $workbook;
$this->parse($xml);
}

// returns an array of the data from the sheet
public function getData() {
return $this->data;
}

protected function parse($xml) {
$this->parseDimensions($xml->dimension);
$this->parseData($xml->sheetData);
}

protected function parseDimensions($dimensions) {
$range = (string) $dimensions['ref'];
$cells = explode(':', $range);
$maxValues = $this->getColumnIndex($cells[1]);
$this->colCount = $maxValues[0] + 1;
$this->rowCount = $maxValues[1] + 1;
}

protected function parseData($sheetData) {
$rows = array();
$curR = 0;
$lastDataRow = -1;
foreach ($sheetData->row as $row) {
$rowNum = (int)$row['r'];
if($rowNum != ($curR + 1)) {
$missingRows = $rowNum - ($curR + 1);
for($i=0; $i < $missingRows; $i++) {
$rows[$curR] = array_pad(array(),$this->colCount,null);
$curR++;
}
}
$curC = 0;
$rowData = array();
foreach ($row->c as $c) {
list($cellIndex,) = $this->getColumnIndex((string) $c['r']);
if($cellIndex !== $curC) {
$missingCols = $cellIndex - $curC;
for($i=0;$i<$missingCols;$i++) {
$rowData[$curC] = null;
$curC++;
}
}
$val = $this->parseCellValue($c);
if(!is_null($val)) {
$lastDataRow = $curR;
}
$rowData[$curC] = $val;
$curC++;
}
$rows[$curR] = array_pad($rowData, $this->colCount, null);
$curR++;
}
if($this->config['removeTrailingRows']) {
$this->data = array_slice($rows, 0, $lastDataRow + 1);
$this->rowCount = count($this->data);
} else {
$this->data = $rows;
}
}

protected function getColumnIndex($cell = 'A1') {
if (preg_match("/([A-Z]+)(\d+)/", $cell, $matches)) {
$col = $matches[1];
$row = $matches[2];
$colLen = strlen($col);
$index = 0;

for ($i = $colLen-1; $i >= 0; $i--) {
$index += (ord($col{$i}) - 64) * pow(26, $colLen-$i-1);
}
return array($index-1, $row-1);
}
throw new Exception("Invalid cell index");
}
protected function parseCellValue($cell) {
// $cell['t'] is the cell type
switch ((string)$cell["t"]) {
case "s": // Value is a shared string
if ((string)$cell->v != '') {
$value = $this->workbook->sharedStrings[intval($cell->v)];
} else {
$value = '';
}
break;
case "b": // Value is boolean
$value = (string)$cell->v;
if ($value == '0') {
$value = false;
} else if ($value == '1') {
$value = true;
} else {
$value = (bool)$cell->v;
}
break;
case "inlineStr": // Value is rich text inline
$value = self::parseRichText($cell->is);
break;
case "e": // Value is an error message
if ((string)$cell->v != '') {
$value = (string)$cell->v;
} else {
$value = '';
}
break;
default:
if(!isset($cell->v)) {
return null;
}
$value = (string)$cell->v;

// Check for numeric values
if (is_numeric($value)) {
if ($value == (int)$value) $value = (int)$value;
elseif ($value == (float)$value) $value = (float)$value;
elseif ($value == (double)$value) $value = (double)$value;
}
}
return $value;
}

// returns the text content from a rich text or inline string field
    public static function parseRichText($is = null) {
        $value = array();
        if (isset($is->t)) {
            $value[] = (string)$is->t;
        } else {
            foreach ($is->r as $run) {
                $value[] = (string)$run->t;
            }
        }
        return implode(' ', $value);
    }
}