Pages

Wednesday, July 8, 2020

Add directory and set permissions rewritable in Linux PHP


$directory = 'images/author_pic/james';

if(check_dir($directory))
{
     echo "Direcotry Created"
} else {
     echo "directory not created something went wrong!";
}




// create writable directory or change the chmod permission of chosen directory

function check_dir($dir) {

    if (!file_exists($dir)) {
         if (mkdir($dir, 0777))// create images dir
            $done = true;

    } else if (!is_writeable($dir)) {
        if (chmod($dir, 0777)) // change perm. setting
            $done = true;

    } else
        $done = true;

    return $done;
}



Tuesday, May 12, 2020

Firebase Push Notification in PHP


// Push notification

$message = "This is test message here.";
$this->sendGCM($message, 'CODE_FOR_DEVICES_TO_RECEIVE');

-----------------------------------------------------------------------------------

Callback Funciton

    function sendGCM($message, $id) {



        // API access key from Google API's Console
            define( 'API_ACCESS_KEY', 'API_ACCESS_KEY_VALUE' );


            $registrationIds = array( $id );

            // prep the bundle
            $msg = array
            (
                'message'   => $message,
                'title'     => 'This is a title. title',
                'subtitle'  => 'This is a subtitle. subtitle',
                'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
                'vibrate'   => 1,
                'sound'     => 1,
                'largeIcon' => 'large_icon',
                'smallIcon' => 'small_icon'
            );

            $fields = array
            (
                'registration_ids'  => $registrationIds,
                'data'          => $msg
            );
           
            $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
           
            $ch = curl_init();
            // curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
            curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );

           
            curl_setopt( $ch,CURLOPT_POST, true );
            curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
            curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
            $result = curl_exec($ch );
            curl_close( $ch );

            echo $result;
    }

Thursday, March 26, 2020

Add and Renew SSL In Linod Server Linux Command line

https://www.linode.com/docs/security/ssl/install-lets-encrypt-to-create-ssl-certificates/

Before you BeginPermalink

  1. Familiarize yourself with our Getting Started guide and complete the steps for setting your Linode’s hostname and timezone.
  2. Complete the steps in our Securing Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.
  3. Update your server’s software packages:
    CentOS
    sudo yum update && sudo yum upgrade
    
    Debian / Ubuntu
    sudo apt update && sudo apt upgrade
    
    Note
    This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, you can check our Users and Groups guide.

Download and Install Let’s EncryptPermalink

  1. Install the git package:
    CentOS
    sudo yum install git
    
    Debian / Ubuntu
    sudo apt-get install git
    
  2. Download a clone of Let’s Encrypt from the official GitHub repository. /opt is a common installation directory for third-party packages, so let’s install the clone to /opt/letsencrypt:
    sudo git clone https://github.com/letsencrypt/letsencrypt /opt/letsencrypt
    
  3. Navigate to the new /opt/letsencrypt directory:
    cd /opt/letsencrypt
    

Create an SSL CertificatePermalink

Let’s Encrypt automatically performs Domain Validation (DV) using a series of challenges. The Certificate Authority (CA) uses challenges to verify the authenticity of your computer’s domain. Once your Linode has been validated, the CA will issue SSL certificates to you.
  1. Run Let’s Encrypt with the --standalone parameter. For each additional domain name requiring a certificate, add -d example.com to the end of the command.
    sudo -H ./letsencrypt-auto certonly --standalone -d example.com -d www.example.com
    
    Note
    ACME version 2 now supports wildcard certificates for subdomains by using the DNS challenge. For more information on obtaining wildcards, visit the Let’s Encrypt documentation.
  2. When prompted, specify an administrative email address. This will allow you to regain control of a lost certificate and receive urgent security notices if necessary. Press ENTER or RETURN to save.
  3. Agree to the Terms of Service and specify if you would like to share your email address with EFF:
      
    -------------------------------------------------------------------------------
    Please read the Terms of Service at
    https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
    agree in order to register with the ACME server at
    https://acme-v01.api.letsencrypt.org/directory
    -------------------------------------------------------------------------------
    (A)gree/(C)ancel: a
    
    -------------------------------------------------------------------------------
    Would you be willing to share your email address with the Electronic Frontier
    Foundation, a founding partner of the Let's Encrypt project and the non-profit
    organization that develops Certbot? We'd like to send you email about EFF and
    our work to encrypt the web, protect its users and defend digital rights.
    -------------------------------------------------------------------------------
    (Y)es/(N)o: n
    
    
  4. If all goes well, a message similar to the one below will appear. Its appearance means Let’s Encrypt has approved and issued your certificates.
      
    IMPORTANT NOTES:
     - Congratulations! Your certificate and chain have been saved at:
       /etc/letsencrypt/live/example.com/fullchain.pem
       Your key file has been saved at:
       /etc/letsencrypt/live/example.com/privkey.pem
       Your cert will expire on 2018-05-27. To obtain a new or tweaked
       version of this certificate in the future, simply run
       letsencrypt-auto again. To non-interactively renew *all* of your
       certificates, run "letsencrypt-auto renew"
     - If you like Certbot, please consider supporting our work by:
    
       Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
       Donating to EFF:                    https://eff.org/donate-le
    
    

Check Certificate DomainsPermalink

  1. The output of the Let’s Encrypt script shows where your certificate is stored; in this case, /etc/letsencrypt/live:
    sudo ls /etc/letsencrypt/live
    
      
    example.com
    
    
  2. All of the domains you specified above will be covered under this single certificate. This can be verified as follows:
    ./certbot-auto certificates
    
      
    Found the following certs:
      Certificate Name: example.com
        Domains: example.com www.example.com
        Expiry Date: 2018-05-27 20:49:02+00:00 (VALID: 89 days)
        Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem
        Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem
    
    

MaintenancePermalink

Renew SSL CertificatesPermalink

  1. Return to the /opt/letsencrypt directory:
    cd /opt/letsencrypt
    
  2. Execute the command you used in Step 1 of the Create an SSL Certificate section, adding the --renew-by-default parameter:
    sudo -H ./letsencrypt-auto certonly --standalone --renew-by-default -d example.com -d www.example.com
    
  3. After a few moments, a confirmation similar to the one below should appear:
      
    IMPORTANT NOTES:
     - Congratulations! Your certificate and chain have been saved at:
       /etc/letsencrypt/live/example.com/fullchain.pem
       Your key file has been saved at:
       /etc/letsencrypt/live/example.com/privkey.pem
       Your cert will expire on 2018-05-27. To obtain a new or tweaked
       version of this certificate in the future, simply run
       letsencrypt-auto again. To non-interactively renew *all* of your
       certificates, run "letsencrypt-auto renew"
     - If you like Certbot, please consider supporting our work by:
    
       Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
       Donating to EFF:                    https://eff.org/donate-le
        
    
    Let’s Encrypt has refreshed the lifespan of your certificates; in this example, March 31st, 2016 is the new expiration date.
Note
Let’s Encrypt certificates have a 90-day lifespan. According to Let’s Encrypt, this encourages automation and minimizes damage from key compromises. You can renew your certificates at any time during their lifespan.

Automatically Renew SSL Certificates (Optional)Permalink

You can also automate certificate renewal. This will prevent your certificates from expiring, and can be accomplished with cron.
  1. The output of the previous command shows how to non-interactively renew all of your certificates:
    ./letsencrypt-auto renew
    
  2. Set this task to run automatically once per month using a cron job:
    sudo crontab -e
    
    Add the following line to the end of the crontab file:
    crontab
    1
    
    0 0 1 * * /opt/letsencrypt/letsencrypt-auto renew

Update Let’s EncryptPermalink

  1. Return to the /opt/letsencrypt directory:
    cd /opt/letsencrypt
    
  2. Download any changes made to Let’s Encrypt since you last cloned or pulled the repository, effectively updating it:
    sudo git pull
    

Automatically Update Let’s Encrypt (Optional)Permalink

You can also use cron to keep the letsencrypt-auto client up to date.
sudo crontab -e
crontab
1
0 0 1 * * cd /opt/letsencrypt && git pull

Fix - Incorrect date value: '0000-00-00' in MYSQL

Fix - Incorrect date value: '0000-00-00' in MYSQL after Updating the Ubantu Server

SET sql_mode = '';
or
SET GLOBAL sql_mode = '';

 

Sunday, December 29, 2019

PHP Mailer Mail send with GMAIL SMTP Settings.

Install Composer and require the PHP Mailer Library

composer require phpmailer/phpmailer

<?php
error_reporting(0);
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 * This uses traditional id & password authentication - look at the gmail_xoauth.phps
 * example to see how to use XOAUTH2.
 * The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
 */
//Import PHPMailer classes into the global namespace

// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

//Load composer's autoloader
require './vendor/autoload.php';
//Create a new PHPMailer instance

$mail = new PHPMailer;
//Tell PHPMailer to use SMTP

$mail->isSMTP();

//Enable SMTP debugging
// SMTP::DEBUG_OFF = off (for production use)
// SMTP::DEBUG_CLIENT = client messages
// SMTP::DEBUG_SERVER = client and server messages

// $mail->SMTPDebug = SMTP::DEBUG_SERVER;



error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");


$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$select_price = $_POST['select_price'];
$select_service = $_POST['select_service'];
$subject = isset($_POST['subject']) ? $_POST['subject'] : 'new email sent';
$comments = $_POST['comments'];

// $verify = $_POST['verify'];

if(trim($first_name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
}  else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
}

if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
}

if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}


// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."

// Example, $e_subject = '$name . ' has contacted you via Your Website.';

$e_subject = 'You\'ve been contacted by ' . $first_name . '.';


// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.

$e_body = "You have been contacted by <strong> $first_name. $first_name </strong>  <br> selected service of <strong> $select_service </strong> , <br> their additional message is as follows:  Customer max budget is $select_price, for this project." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $first_name via email, $email or via phone $phone";

$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );



try {
     //$mail->Host       = "mail.gmail.com"; // SMTP server

      // $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
      $mail->SMTPAuth   = true;                  // enable SMTP authentication
      $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
      $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
      $mail->Port       = 465;   // set the SMTP port for the GMAIL server
      $mail->SMTPKeepAlive = true;
      $mail->Mailer = "smtp";
      $mail->Username   = "youremail@gmail.com";  // GMAIL username
      $mail->Password   = "yourgmailpassword";            // GMAIL password
      $mail->AddAddress('receiveremail@gmail.com', 'Info Webnem');
      $mail->addBCC('addbccemail@gmail.com', 'Info Webnem');



  $mail->AddReplyTo($email, $e_reply);

      $mail->SetFrom('emailfrom@gmail.com', $email);
      $mail->Subject = $e_subject;
      $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
      $mail->MsgHTML($msg);
      if($mail->Send()) {
      echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$first_name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
  }
} catch (phpmailerException $e) {
      echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
      echo $e->getMessage(); //Boring error messages from anything else!
}

Wednesday, November 13, 2019

Create Scheduler CronJob In Laravel and adding cronjob in Linux Crontab

Step 1: Create command in laravel
            php artisan make:command YourCommand

in /app/console/commands
YourCommand.php
     Update line

protected $signature = 'yourcommand:cron';

Create your logic in function

public function handle()
    {
        // Your Code Here

    }



in crontab linux command

sudo crontab -e
press INSERT Button
add command

* * * * * cd /var/www/html/yourproject/ && php artisan schedule:run >> /dev/null 2>&1

save: 
type (:wq)

Add cronjob in Kernel.php

protected function schedule(Schedule $schedule)
    {
        $minutes = env("CRON_INTERVAL",15); 

        // $schedule->command('testcronjob:cron')
                // ->cron($minutes.' * * * *');

        $schedule->command('testcronjob:cron')
                 ->cron('10 * * * *'); //cron('1 * * * *');
        // $schedule->command('testcronjob_half_hour:cron')
        //          ->cron('30 * * * *'); //cron('1 * * * *');
        // $schedule->command('testcronjob_quarter:cron')
        //          ->cron('45 * * * *'); //cron('1 * * * *');
        // $schedule->command('testcronjob_hour:cron')
        //          ->cron('* 1 * * *'); //cron('1 * * * *');
        // $schedule->command('testcronjob_hour_15:cron')
        //          ->cron('15 1 * * *'); //cron('1 * * * *');
        // $schedule->command('testcronjob_hour_30:cron')
        //          ->cron('30 1 * * *'); //cron('1 * * * *');
        // $schedule->call(function () {
        //     Log::info(': Job Run Successfully. ');
        // })->cron(' * * * *');


    }