Thursday 7 November 2019

Changing Number of Failed Attempts in Linux Hosting Firewall

When we purchase a dedicated linux server for our company, mostly we have to take care of its security. Its evident that, there are many attackers trying to penetrate through the systems for their attack initilizations. So if our server doesn't have any firewall, the chance of getting hacked is high. So every company will configure Firewall in their server. Mainly the services are  termed as CSF(ConfigServer Security firewall) and Login Failure Daemon(LFD).

CSF

The ConfigServer Security firewall known as CSF is an open source software and most commonly used to configure the advanced firewall in Linux servers such us Login detection, SSH login notifications, etc. CSF provides the wide range of protection on your Linux servers.  By default, CSF firewall will be blocked IP address when entering wrong username or password in more than 5 times in the last 3600 seconds.

LFD

LFD stands for Login Failure Daemon is a process that is a part of the CSF that checks periodically for potentials threats to a server. The CSF is working with LFD. CSF checks the LFD logs for failed login attempts at a regular time interval and is able to find most unauthorized attempts to gain access to your Linux server. 

Changing Configuration From Comman Line or Terminal

Edit csf configuration via command line(CLI)

1) Login to Server as a root user.

2) Open the csf config file using the text editor like vi, vim.

vi /etc/csf/csf.config

3) Then find the following entries.

To change FTP login failed attempt value.

LF_FTPD = “10”

To change the value failure detection of SMTP AUTH connections.

LF_SMTPAUTH = “5”

To change login failure detection value of courier pop3 connections.

LF_POP3D = “5”

To change login failure detection value of courier imap connections

LF_IMAPD = “10”

To change login failure detection value of cPanel, webmail and WHM connections.

LF_CPANEL = “5”

4) Then save this config file after changing these values.

5) You have to restart csf and lfd services.

csf -r

service csf restart.

service lfd restart.

Changing Configuration From WHM

1) Login to WHM as a root user.


2) Go to Plugins >> ConfigServer Security & Firewall.
3) Go To Firewall Configurations

4) Go Inside configuration , now search for   LF_FTPD,  LF_SMTPAUTH   ,LF_POP3D, LF_IMAPD , LF_CPANEL
change its values... and restart the firewall... Now your issues will be resolved!!




Monday 4 November 2019

Integrating Paypal into Your PHP Website with Dynamic Price

In this advanced world where online shopping is the new trend, its envitable for all the online selling providers to integrate payment gateways on their websites.People dont want to spend time on direct shopping or cash payments.etc.. So Here am explaining about simple way of integrating paypal buttons to your website.
1)First of all You have to create a paypal account. Also its better to create a sandbox accounts for testing. Better if you can create a buyer & seller sandbox accounts to check whether the transaction is happening or not.


2) Login to developer area.Create an app.
When you go inside you will get client id from the app created. So for testing purpose you can create a sandbox app for it and use its Client ID. 

3)In you website Checkout Page . Paste this Code:-

  <!-- Set up a container element for the button -->
    <div id="paypal-button-container"></div>

    <div id="info1"> </div>

    <!-- Include the PayPal JavaScript SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=CLIENT_ID&currency=USD"></script>
Replace CLIENT_ID with your client id , which i explained before. Currency you can set according to your preference based on the available Paypal Currencies.

4) In this Page you should have 2 things. one is the amount payable. this i want you to store in a variable called "payamount". if your currency is not available, you can convert same to USD using conversion rates and save it in same variable. Another thing you have to save is the corresponding order id of the order in your website. This is for saving the payment record corresponding to this transaction in your database. Save this value to a variable called "orderid".

<?php
 $orderid=$_GET['d'];
 $_SESSION['orderid']=$orderid;
 
 ?>

5)Before next step I want you to create one table in your database  called payments. This will save all payment records corresponding to the orders. So you can check whether the payment is done or not.

CREATE TABLE IF NOT EXISTS `payments` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `txnid` varchar(20) NOT NULL,
    `payment_amount` decimal(7,2) NOT NULL,
    `payment_status` varchar(25) NOT NULL,
    `orderid` varchar(25) NOT NULL,
    `createdtime` datetime NOT NULL,
   `payer_name` varchar(100) NOT NULL,
   `payer_email` varchar(100) NOT NULL,
    `payer_id` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

6) Now paste this code :-, I will explain the function one by one.

 <script>
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({
            // Set up the transaction
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: '<?php echo $payamount;  ?>'
                        }
                    }]
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    // Show a success message to the buyer
                     console.log(details);
                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                    var name=details.payer.name.given_name;
                    var txnid=details.id;
                    var email=details.payer.email_address;
                    var payerid=details.payer.payer_id;
                    var status=details.status;
                    var updated_date=details.update_time;
                    var payamount = <?php echo $payamount;  ?>;
                   
                      $.ajax({
    type: "POST",
    url:  "postpayment.php",
    data: 'name='+name+'&txnid='+txnid+'&email='+email+'&payerid='+payerid+'&status='+status+'&updated_date='+updated_date+'&payamount='+payamount,
    success: function(data){
        $("#info1").html(data);
    }
  });
                    
                });
            }


        }).render('#paypal-button-container');
    </script>

I have highlighted some variables with red, to  explain you, how it works. In that line

 value: '<?php echo $payamount;  ?>'

Here we are passing the payment amount to the paypal function. After thr transaction gets completed, paypal will return us an array with the success parameters. The enxt thing we have to do is fetch it and pass to our php function and save it..

                   var name=details.payer.name.given_name;
                    var txnid=details.id;
                    var email=details.payer.email_address;
                    var payerid=details.payer.payer_id;
                    var status=details.status;
                    var updated_date=details.update_time;
                    var payamount = <?php echo $payamount;  ?>;
Here am fetching the required values from the details object and parsing one by one. If you closely check, these all values we want to save it in our database.

    url:  "postpayment.php",
This is the php page where am passing these variables as POST method.. Iam passing it like:-
'name='+name+'&txnid='+txnid+'&email='+email+'&payerid='+payerid+'&status='+status+'&updated_date='+updated_date+'&payamount='+payamount,
These variables can be received by the php page as POST varaibles and can save it in database.

7) create a page called postpayment.php

<?php
ob_start();
session_start();
//Connect Database Here

$name=strip_tags($_POST['name']);
$email=strip_tags($_POST['email']);
$txnid=strip_tags($_POST['txnid']);
$payerid=strip_tags($_POST['payerid']);
$status=strip_tags($_POST['status']);
$updated_date=strip_tags($_POST['updated_date']);
$orderid=$_SESSION['orderid'];
$payamount=strip_tags($_POST['payamount']);


$paydet=$pay->getdetails($txnid);

if(count($paydet)<=0){
$insert=array('txn_id'=>$txnid,'payment_amount'=>$payamount,'payment_status'=>$status,'orderid'=>$orderid,'createdtime'=>$updated_date,'payer_name'=>$name,'payer_email'=>$email,'payer_id'=>$payerid);
$pay->addpayment($insert);
$lastid=$pay->lastInsertId();
echo "Your Payment transaction is successfull.Please Note your Payment Reference No. : PAYREF-".$lastid;

}


?>
You can use your own db connection methods. Dont forget to initialize session as you remember, we saved order id as a session varaiable. you can also pass it via ajax with the other varaiables. But am not doing it. So then , assign all varables came as POST method into an array and save it in your database. You can also check, whether same transaction is saved before or not. After you do the payment using your sandbox accounts, check whether value i s saved in database or not. if success, Congratzz.. otherwise recheck above instructions again.

8) If this is success, replace the sandbox app client id with Live app client ID. Enjoy...


Sunday 4 August 2019

Splitting Excel Files using Bat Script- easy way

Sometimes we will face situations, where we have to split our excel sheets into multiple. Suppose for importing to some softwares, if we have a excel sheet with millions of data we have to split it to small adata files for our convinence to upload. In those situations, copy pasting lakhs of adata into seperate excel sheet is a tiredous task. Here I will give a script which you can run as a bat file to split the xcel sheets.

1) Save your excel sheet in csv format.

2) Make a file and rename it as script.bat. Open it in edit mode and paste the following code:-

@echo off

setlocal ENABLEDELAYEDEXPANSION

REM Edit this value to change the name of the file that needs splitting. Include the extension.

SET BFN=importfile.csv

REM Edit this value to change the number of lines per file.

SET LPF=50000

REM Edit this value to change the name of each short file. It will be followed by a number indicating where it is in the list.

SET SFN=splitfile

REM Do not change beyond this line.

SET SFX=%BFN:~-3%

SET /A LineNum=0

SET /A FileNum=1

For /F "delims==" %%l in (%BFN%) Do (

SET /A LineNum+=1

echo %%l >> %SFN%!FileNum!.%SFX%

if !LineNum! EQU !LPF! (

SET /A LineNum=0

SET /A FileNum+=1

)

)

endlocal

Pause

3)In the above file set BFN variable the csv  file name  we want to split. and in SFN variable we have to put the split files prefix for our convinence .in LPF we have to mention the count of number of rows per excel sheet.Now save it and close it.

4) Put this script file in same folder of the csv file. Now open Command prompt and navigate to same file location and run the script.

Combining CSV Files

For combing CSV files.. Navigate to folder using cmd.Put the command
copy *.csv merge.csv


Wednesday 17 July 2019

Resolving PHP Auto emails from Linux Server Hostings

When you create new websites , a frequent requirement will be sending automatic mail notifications from Enquiry Forms, sending mail activations, forget password links, product enquiries.etc. When you host website in linux hosting , there are restrictions on mail sending. This is mainly due to the increase in number of spam mails all over the world. it is being noted that spammers are sending phishing mails through many domains even without having any login details. So the server people accept only SMTP secure mail transmission for this. I will be using PHP mailer for sending mails.

1) Download PHPMailer script from Github:- 

2) Now  you have to create an email account if you already didn't have and note the password of the same.Make sure to Enable DKIM,SPF and PKR for servers not marking it as spam.

3) Now in the project copy the phpmailer folder into the root folder of project.now in the script you want to send mail,include this code:-

date_default_timezone_set('Etc/UTC');

require 'PHPMailerAutoload.php';

//Create a new PHPMailer instance 
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP                                                                                     $mail->isSMTP();                                                                                                    //Enable SMTP debugging.This you can use to check the working. for testing put to 2 and check mails going or no.In production environment,put it as 0.
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "mail.domain.com";
//Set the SMTP port number should be ssl settings smtp port 465
$mail->Port = 465;
//Whether to use SMTP authentication,dont forget to put this line.
$mail->SMTPAuth = true;
$mail->SMTPSecure = true;

//Username to use for SMTP authentication
$mail->Username = "info@domain.com";
//Password to use for SMTP authentication
$mail->Password = "mYP@$$w0rd";
//Set who the message is to be sent from
$mail->setFrom('user@domain.com', 'Name');
//Set an alternative reply-to address
$mail->addReplyTo('user@domain.com', 'Name');
//Set who the message is to be sent to
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($msg);
//Replace the plain text body with one created manually
$mail->addAddress($email_to, 'User');
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

Tuesday 16 July 2019

Exporting Large Database From Linux Server Hosting

For exporting database more than certain size, PHPMYADMIN will give you timeout errors. For effective tackling the same, we need to do it via SSH. Here am going to show you, how to do it in linux server.

1) Enable Shell access in server

In your cpanel, dashboard you can see "manage Shell" option. Just click on that.
After that, we have to enable SSH access. Then we will get ssh port and details through this. If you want to use external terminal access softwares like putty, you can use those connection details. But here am explaining about how we can do in the server itself without using any external softwares.

2) Access Terminal of server
Click on Terminal menu in Advanced tab of cpanel. You will get a terminal to enter commands.

3) Executing commands in Terminal

Now from step 3, open the terminal. we have to put one command here..

mysqldump -u dbuser_user -p dbname > /home/folderuser/public_html/dbbackup/db.sql

(dbuser: Put the database username, dbname:Put the db name, db.sql: Give the database file name, path should be given relatively in repect to where you want the exported sql file)

Then it will ask for db user password just provide that. Now the command will execute and database will be exported successfully.

Importing Large Mysql Database in Linux Hosting Servers

When we are migrating very large websites, problem often comes when we are migrating the database. Through phpmyadmin, we can import database upto 50 mb. But the sql of size more than 50mb we have to import via SSH. Here I will explain how to do it in a linux server hosting.

1) Enable Shell access in server
In your cpanel, dashboard you can see "manage Shell" option. Just click on that.
After that, we have to enable SSH access. Then we will get ssh port and details through this. If you want to use external terminal access softwares like putty, you can use those connection details. But here am explaining about how we can do in the server itself without using any external softwares.


2) Access Terminal of server
Click on Terminal menu in Advanced tab of cpanel. You will get a terminal to enter commands.

3)Create Database and User

Now we have to make some basic things ready. So we need to create a database and user. Make sure to give all privileges to that particular user. Note down the db username, password,db name.etc.

3) Upload the Sql file to server

Now we have to upload the sql file to the server for importing.This you can use FTP and through server. Make sure in the sql script, db name should match the database name created in server. if its different open the sql file and edit it with the same.

5) Executing commands in Terminal

Now from step 3, open the terminal. we have to put one command here..

mysql -u dbuser -p dbname < /home/folderuser/db.sql
(dbuser: Put the database username, dbname:Put the db name, db.sql: Give the database file name, path should be given relatively in repect to where you uploaded the sql file)

Then it will ask for db user password just provide that. Now the command will execute and database will be imported successfully.



Monday 15 July 2019

Resolving Permission/ Undefined Variable Problem in SugarCRM/SuiteCRM in Linux Server

When we install or migrate Sugarcrm/Suitecrm,normally we have to face some issues like pages going blank or the messages and popup showing as undefined. This error occurs mostly when we migrate CRM to some Linux servers. This is mainly caused due to permission errors and missing extensions. I will give you step to step instruction on how to resolve this problem. we can divide the steps into three parts.

1) Checking all required extensions are installed or not?
2) Checking all files or folders  having required permissions?
3) Checking the correct path set in .htaccess file

so here am going to explain step by step..

1) Checking all required extensions are installed or not?

We have to check whether following extensions are installed or not.


  • PHP - (check the version.. if you are using older version of sugar or suitecrm ebnable lower php versions. If you are using latest suitecrm version, dont forget to upgrade php verision.)
  • JSON -( Check JSON support is enabled.)
  • XML Parsing- (XML parsing supports should be enabled)
  • MB Strings Module -(This is a php extension needed for sugarcrm to function.make sure to install this extension corresponding to php version in the server)
  • ZLIB Compression Module - (This module is needed for package installation function in crm.make sure to enable it)
  • ZIP Handling Module-  (This module is needed for package installation function in crm.make sure to enable it)
  • PCRE Library-(This is a Perl module needed for advanced regex functions)
  • IMAP Module- (This is for Mail functioning inside CRM for reminders.etc)
  • cURL Module
  • Sprite Support
After install of new modukles, just restart the apache services



2) Checking all files or folders  having required permissions?

We have to check permissions for some directories inside root folder.
Main directories to give 775 permission are:-cache, custom ,modules ,themes ,data, upload.
Also we have to change permission to config_override.php file also to 775
While giving permission to directory, make sure to give permission recursively for child objects under that folder also.

Login to terminal via root user then perform following commands:-

cd  /home/siteuser/public_html/    (siteuser will be username in the hosting)

sudo chmod -R 775 cache custom modules themes data upload config_override.php

Now check the permission has been granted or not

3) Checking the correct path set in .htaccess file

Just open .htaccess file in the root folder. check this line:-

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /

Verify RewriteBase /  is correctly set or not. If you have installed in public_html folder itself you have to use like this RewriteBase /. In case, if you installed inside a folder for eg: crm, this line have to change like:- RewriteBase /crm/

After editing , save the file and close it

Now login to CRM and check. Its betetr to do a Repair and rebuild from the admin to make sure everything reloaded correctly..