Sunday, December 25, 2016

Increasing upload size limit on PHP

open php.ini file
post_max_size = 225M
upload_max_size = 200M

save it and restart the server!
Note : post max size needs to be larger than upload max size limit!

Monday, October 10, 2016

Useful PHP Time functions

Create date string which adds 30 days from current date
strtotime('today' + '90 days')
date("Y-m-d", strtotime("+30 days")


Create DateTime object from date string
new_expiry_date = strtotime(date("Y-m-d", strtotime("+30 days")));

Convert DateTime to MongoDate
new MongoDate($new_expiry_date);

 //Adding days to mongodate  
 function add_days_mongodate($mongo_date, $days)  
 {  
   $expiry_date = strtotime(date("d-m-Y H:i:s", $mongo_date->sec));  
   $new_expiry_date = $expiry_date + ($days * 24 * 60 * 60); //Add 30 Days  
   return $new_expiry_date;  
 }  
 function convert_string_to_mongodate($date)  
 {  
   $carbon_date = Carbon::createFromFormat('d/m/Y', $date);  
   $mongo_date = new MongoDate(strtotime($carbon_date->toDateString()));  
   return $mongo_date;  
 }  
 // Calculate date from two datetime  
 function days_between($str_date1, $str_date2)  
 {  
   //Get 1 day in milliseconds  
   $one_day = 1000 * 60 * 60 * 24;  
   $date1 = strtotime($str_date1);  
   $date2 = strtotime($str_date2);  
   $difference = $date1 - $date2;  
   $days = $difference/$one_day;  
   return $days;  
 }  
 // Calculate hours from two datetime  
 function hours_between($str_date1, $str_date2)  
 {  
   $date1 = strtotime($str_date1);  
   $date2 = strtotime($str_date2);  
 //  Log::info($date1);  
 //  Log::info($date2);  
   $difference = $date1 - $date2;  
   $hours = $difference/3600;  
   Log::info($hours);  
   return $hours;  
 }  
 //Format mongo date to displayable date string  
 function parse_mongo_date($mongo_date)  
 {  
 //  $mongo_date == null  
   if(is_a($mongo_date, 'MongoDate'))  
     $new_date =date('d-m-Y H:i:s',$mongo_date->sec);  
   else  
     $new_date = $mongo_date;  
   return $new_date;  
 }  
 function convert_to_mongo_date($date)  
 {  
   return new MongoDate(strtotime(date(DATE_ISO8601, $date->sec)));  
 //  new MongoDate(strtotime(date(DATE_ISO8601, $mongo_date->sec) - "30 days"));  
 }  
 function get_mongo_date_from_string($str_date)  
 {  
   $mongo_date = new MongoDate();  
   if(isset($str_date)) {  
     $carbon_date = Carbon::createFromFormat('d/m/Y', $str_date);  
     $mongo_date = new MongoDate(strtotime($carbon_date->toDateString()));  
   }  
   return $mongo_date;  
 //  new MongoDate(strtotime(date(DATE_ISO8601, $mongo_date->sec) - "30 days"));  
 }  

Sunday, October 9, 2016

Backing up database to amazon s3

Go to the following address to download s3tools for linux
http://s3tools.org/usage

apt-get install unzip to install zip for Linux if the downloaded folder needs to unzip

apt-get install s3cmd to install s3tools from command line

Configure the s3
s3cmd --configure to configure the tool for the first time

Access Key: xxxxxxxxxxxxxxxx
Secret Key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Encryption password is used to protect your files from reading
by unauthorized persons while in transfer to S3
Encryption password: your_password
Path to GPG program [/usr/bin/gpg]:

When using secure HTTPS protocol all communication with Amazon S3
servers is protected from 3rd party eavesdropping. This method is
slower than plain HTTP and can't be used if you're behind a proxy
Use HTTPS protocol [No]: NO

On some networks all internet access must go through a HTTP proxy.
Try setting it here if you can't conect to S3 directly
HTTP Proxy server name:

New settings:
  Access Key: AKIAJWMP76CEGCZYJJJA
  Secret Key: oxDlDDsXMgYQ+W7ZvmdPKEsjKXoAfZ1DF2J7vK6k
  Encryption password: whitecat
  Path to GPG program: /usr/bin/gpg
  Use HTTPS protocol: False
  HTTP Proxy server name:
  HTTP Proxy server port: 0

Test access with supplied credentials? [Y/n] Y
Please wait, attempting to list all buckets...
Success. Your access key and secret key worked fine :-)

Now verifying that encryption works...
Success. Encryption and decryption worked fine :-)

Save settings? [y/N] y

Configuration saved to '/root/.s3cfg'

Now you can upload the file to s3 using the following commands

s3cmd put /your/path/server/$FILE_NAME.tar.gz s3://backups.joydash.com/path/$FILE_NAME.tar.gz








Thursday, September 22, 2016

Allowed memory size of 268435456 bytes exhausted

This is due to default memory limit in PHP

Locate PHP.ini file
php --ini

find memory_limit and set to 2048M

Tuesday, September 6, 2016

Generating PDF file from html

You need to download and install wkhtmltopdf exe file
http://wkhtmltopdf.org/downloads.html#stable

then use laravel wrapper
Add the following line in the required
"barryvdh/laravel-snappy": "0.2.*"

After updating composer, add the ServiceProvider to the providers array in app/config/app.php
Barryvdh\Snappy\ServiceProvider::class,
You can optionally use the facade for shorter code. Add this to your facades:
'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
Using the wrapper:
$pdf = App::make('snappy.pdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->inline();
Or use the facade:
$pdf = PDF::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');
Important : You can publish the config-file to change some settings (default paper etc).
php artisan vendor:publish

Friday, June 24, 2016

cURL error 60 : SSL problem

Go to http://curl.haxx.se/ca/cacert.pem and download the pem file and save in your php installation directory ( make sure while saving it retains the extension and not saved as a text file )

Now, open your php.ini file, scroll to the bottom and add the following line:

[cURL]
curl.cainfo="D:\xampp\php\cacert.pem"
Replace D:\xampp\php\cacert.pem with the actual path.

Tuesday, June 21, 2016

payload is invalid

When you copied the whole project and start working again, it would say payload is invalid in all calls

php artisan key:generate

php artisan config:cache

Wednesday, April 20, 2016

Installing ssl certiciface on apache

Edit your vhost file located at /apache2/conf/extra/httpd-vhosts.conf if you're using bitnami stacks.

Add the following secure vhost file to enable SSL on your site

<VirtualHost *:443>
    DocumentRoot "/opt/lampstack-5.5.31-0/apache2/htdocs/your_site/public"
    ServerName yoursite.com:443
    ServerAlias www.yoursite.com:443
    <Directory "/opt/lampstack-5.5.31-0/apache2/htdocs/yoursite/public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    SSLEngine on
    SSLCertificateFile /opt/lampstack-5.5.31-0/apache2/conf/yoursite.crt
    SSLCertificateKeyFile /opt/lampstack-5.5.31-0/apache2/conf/yoursite.key
</VirtualHost>


if You would like to konw how the private key and csr file can be generate, go to the following link 

http://laraveldevelopmentonwindows.blogspot.com/2016/04/adding-ssl-to-laravel-site-running-on.html

Installing intermediate File
Some browser may tell that your ssl certificate is not secured and you might need to install intermediate chain file to remove that error

https://knowledge.rapidssl.com/support/ssl-certificate-support/index?page=content&actp=CROSSLINK&id=SO6252

https://knowledge.rapidssl.com/support/ssl-certificate-support/index?page=content&actp=CROSSLINK&id=INFO1548

Go to the above link to copy the certificate contents.
In your server, create a new file yoursite_intermediate.crt file
below SSLCertificateKeyFile line in your virtual host settings, add the following line

SSLCertificateChainFile /opt/lampstack-5.5.21-0/apache2/conf/yoursite_intermediate.crt
if SSLCertificateChainFile is not working for some server, use SSLCertificateFile instead

Restart apache server





Thursday, April 14, 2016

Adding SSL to laravel site running on apache server

To activate an SSL certificate you need to submit a CSR (Certificate Signing Request) on ssl provider site. CSR is a block of code with encrypted information about your company and domain name. Usually CSR openssl configuration contains by default the details as follows below:
  • Common Name (the domain name certificate should be issued for)
  • Country
  • State (or province)
  • Locality (or city)
  • Organization
  • Organizational Unit (Department)
  • E-mail address
It’s usually openssl that is used for CSR generation on Apache or Nginx web servers. It’s included by default in web servers’ properties. So if you have a web server installed, you will hardly need to install openssl additionally.
To generate a CSR run the command below in terminal:
openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out server.csr
We recommend you replace ‘server’ with the domain name the certificate will be issued for to avoid further confusion.
The command starts the process of CSR and Private Key generation. The Private Key will be required for certificate installation.
You will be prompted to fill in the information about your Company and domain name.

Country Name (2 letter code) [AU]:SG
State or Province Name (full name) [Some-State]:PlayRivals
Locality Name (eg, city) []:Singapore
Organization Name (eg, company) [Internet Widgits Pty Ltd]:JoyDash Pte Ltd
Organizational Unit Name (eg, section) []:NA
Common Name (e.g. server FQDN or YOUR name) []:*.playrivals.com
Email Address []:admin@joydash.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:your_password
An optional company name []:JoyDash

It is strongly recommended to fill all the required fields in. If a field is left blank, the CSR can be rejected during activation. For certificates with domain validation it is not mandatory to specify “Organization” and “Organization Unit” -you may fill the fields with ‘NA’ instead. In the Common Name field you need to enter the domain name the certificate should be issued for.
Please use only symbols of English alphanumeric alphabet. Otherwise the CSR can be rejected by a Certificate Authority.
If the certificate should be issued for a specific subdomain, you need to specify the subdomain in ‘Common Name’. For example ‘sub1.ssl-certificate-host.com’.
In case of Wildcard certificates, the domain name should start with an asterisk as in ‘*.ssl-certificate-host.com’
Geotrust Domain Validated certificates (QuickSSL Premium, RapidSSL) work for a main domain name with and without www only if it is issued for a domain name with www (www.ssl-certificate-host.com).
Once all the requested information is filled in, you should have *.csr and *.key files in the folder where the command has been run.
*.csr file contains the CSR code that you need to submit during certificate activation. It can be opened with a text editor. Usually it looks like a block of code with a header: “-----BEGIN CERTIFICATE REQUEST----“ It is recommended to submit a CSR with the header and footer.
*.key file is the Private Key, which will be used for decryption during SSL/TLS session establishment between a server and a client. It has such a header: “-----BEGIN RSA PRIVATE KEY-----“ Please make sure that the private key is saved as it will be impossible to install the certificate without it on the server afterwards.

Monday, March 28, 2016

Adding crossdomain policy security

Creating .htaccess file in your application root folder

<FilesMatch "\.(mpd||m4s|m3u8|jpg|png)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>


Add the XORS request middleware in laravel
<?php namespace App\Http\Middleware;
use Closure;//use Symfony\Component\HttpFoundation\Response;
class Cors {
    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {        header("Access-Control-Allow-Origin: *");
        // ALLOW OPTIONS METHOD        $headers = [            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'        ];        if($request->getMethod() == "OPTIONS") {            // The client-side application can set only headers allowed in Access-Control-Allow-Headers            return Response::make('OK', 200, $headers);        }
        $response = $next($request);        foreach($headers as $key => $value)            $response->header($key, $value);        return $response;    }
//    public function handle($request, Closure $next)//    {//        $content = $next($request);//        return ( new Response($content) )->header('Access-Control-Allow-Origin' , '*')//            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')//            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin');//    }
}

In Kernel.php
protected $middlewareGroups = [    'web' => [        
        \App\Http\Middleware\Cors::class,
    ],

Thursday, March 24, 2016

Tuesday, March 8, 2016

Laravel server error 500

For solving the problem i ran the following commands through terminal.
sudo chmod 755 -R project_name
and then type below to allow laravel to write file to storage folder
chmod -R o+w project_name/storage
This two commands solved the problem

Wednesday, March 2, 2016

Unsupported driver [mongodb] Error

- Check whether the mongo db php driver is installed (jenssegers) for laravel
- Check whether the .dll or .so file is placed in php directory and enabled in php.ini file
- Check whether the php path is in system path
- Check whether the Mongodb driver support current PHP version
- Check the Mongodb service is registered in app.php

When problems occur like mongoclient not found error, you can try to run php from your command line and you'll see the error message there!

Monday, February 22, 2016

Token Mismatch Bugs

Might occur based on the following two conditions

Missing token when submitting the form. Add the following file on each form submission
<input type="hidden" name="_token" value="{{ csrf_token() }}">

Or

Messed up with authentication sessions (Adding social log in or others after the basic login process)
Delete all the files in framework/sessions

Or session messed up with domain

In the session.php file
'domain' => env('DOMAIN', null),

and in the .env file, set domain to your domain