Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
How to read the .docx files in PHP

How to read the .docx files in PHP

Hi, In This tutorial you will learn about "How to read the .docx files in PHP". Generally .docx files will be opened in the MS-OFFICE, But we are able to open the .docx file in PHP we have to convert the .docx file into text then we can easily display the content in the web browser.

<?php  
 function read_file_docx($filename){  
      $striped_content = '';  
      $content = '';  
      if(!$filename || !file_exists($filename)) return false;  
      $zip = zip_open($filename);  
      if (!$zip || is_numeric($zip)) return false;  
      while ($zip_entry = zip_read($zip)) {  
      if (zip_entry_open($zip, $zip_entry) == FALSE) continue;  
      if (zip_entry_name($zip_entry) != "word/document.xml") continue;  
      $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));  
      zip_entry_close($zip_entry);  
      }// end while  
      zip_close($zip);  
      $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);  
      $content = str_replace('</w:r></w:p>', "\r\n", $content);  
      $striped_content = strip_tags($content);  
      return $striped_content;  
 }  
 $filename = "sample.docx";// or /var/www/html/file.docx  
 $content = read_file_docx($filename);  
 if($content !== false) {  
      echo nl2br($content);  
 }  
  else {  
      echo 'Couldn\'t the file. Please check that file.';  
           }  
 ?>  

* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to save an HTML5 Canvas as Image on a server using PHP

How to save an HTML5 Canvas as Image on a server using PHP

Hi, In this tutorial, I am going to explain, How to save an HTML5 Canvas as Image on a server using PHP. Before going to this topic please refer "How to convert the HTML content into an image using jquery" in my previous post then you will get an idea how to generate the div content as an image.

Step 1: First Convert canvas image to URL format (base64)
var dataURL = canvas.toDataURL();
Step 2: After Send it to your server via Ajax
$.ajax({
  type: "POST",
  url: "script.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
});
Step 3: Now Save base64 on your server as an image using php code
<?php  
      // requires php5  
      define('UPLOAD_DIR', 'images/');  
      $img = $_POST['imgBase64'];  
      $img = str_replace('data:image/png;base64,', '', $img);  
      $img = str_replace(' ', '+', $img);  
      $data = base64_decode($img);  
      $file = UPLOAD_DIR . uniqid() . '.png';  
      $success = file_put_contents($file, $data);  
      print $success ? $file : 'Unable to save the file.';  
 ?>  
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to Refresh a page after specific time automatically in PHP

How to Refresh a page after specific time automatically in PHP

Hi, In This tutorial you will know about How to Refresh a page after specific time automatically in PHP. Generally, we did this type of implementation in the javascript or jquery but sometimes javascript is disabled in the user's side (i.e users disabled the javascript in their browsers).

At this situation, we need to implement that code in PHP
it is very simple first we need to fix the specific time for the refresh the website.
In general, the header is used to redirect the web page in PHP by using the location. But here we will use the header in the Refresh tag to set the time and web page URL to refresh the web page.

 //getting the current web page url
 $page = $_SERVER['PHP_SELF'];
 //set the time in seconds
 $sec = "10";
 header("Refresh: $sec; url=$page");
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to store and retrieve array in MySQL and PHP

How to store and retrieve array in MySQL and PHP

This is the most important technique for all Php developers because of Mysql can't store the array values directly.
So we need to convert the PHP Array to string by using the serialize().

This mechanism is very useful in the e-commerce cart functionality. For example, we can store the customer purchase items list and price can be stored in the associative array and convert into string and store in the MySQL.
This way we can reduce the logic of the code get the accurate result also.

MySql Code
CREATE TABLE `students` (
  `id` int(11) NOT NULL,
  `language` varchar(50) NOT NULL,
  `student_names` mediumtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `students`
--
ALTER TABLE `students`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `students`
--
ALTER TABLE `students`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
You need to connect the database create the dbconfig.php file
 <?php  
 $servername = "localhost";  
 $username = "root";  
 $password = "";  
 $dbname = "techiesbadi";  
 // Create connection  
 $con = new mysqli($servername,$username, $password, $dbname);  
 // Check connection  
 if ($con->connect_error) {  
 die("Connection failed: " . $con->connect_error);  
 }  
 ?> 
Now Store the PHP Array in MySql create the store-array.php file
 <?php  
 include "dbconfig.php";  
 $students = array("ramu", "ravi", "gopal", "krishna");  
 //Converting array to String  
 $student_names=mysqli_real_escape_string($con, serialize($students));  
 $sql = "INSERT INTO `students` (`id`, `language`, `student_names`) VALUES (NULL, 'php', '$student_names')";  
 $result = $con->query($sql);  
 if($result === TRUE){  
      echo "Record inserted successfully";  
 }  
 ?>
Now retrieve the PHP Array from MySQL create the retrieve-array.php file
<?php  
 include "dbconfig.php";  
 $getStudnets = $con->query("SELECT * FROM `students` LIMIT 1");   
 $studentsData = $getStudnets->fetch_object();  
 $language = $studentsData->language;  
 //Converting string to array  
 $students = unserialize($studentsData->student_names);  
 //printing students array  
 print_r($students);  
 echo "<br />";  
 foreach ($students as $student) {  
      echo $student." learning ".$language." language.<br/>";  
 }  
 ?>
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff

How to Generate QR Code using Google Chart API in PHP

Hi, In this tutorial you will learn How to Generate QR Code using Google Chart API in PHP. Before going to the topic you need to know about what is QR Code?
QR Code is a machine-readable code, It consisting of an array of black and white squares. It is typically used for storing the information like general text, contact information, URL, image and SMS this information is reading by the smartphone cameras and QRcode Scanner Devices.

If you want to generate the QRcode in PHP you shall need to load the lots of libraries to your application.But we use this  Google chart API to generate the QRcode. Here there is no need to load the libraries to your application just we use the Google Chart API and CURL.

The Script allows you to create the dynamic QRcodes for the content like  TEXT, URL, EMAIL, CONTACT, SMS and other details.
You can save the generated QR code as a PNG file.

qrcode.php
<?php  
 class QrCode{  
   // Google Chart API URL  
   private $apiUrl = 'http://chart.apis.google.com/chart';  
   private $data;  
   // It generates URL type of Qr code  
   public function URL($url = null){  
     $this->data = preg_match("#^https?\:\/\/#", $url) ? $url : "http://{$url}";  
   }  
    // It generate the Text type of Qr code  
   public function TEXT($text){  
     $this->data = $text;  
   }  
   // It generates the Email type of Qr code  
      public function EMAIL($email = null, $subject = null, $message = null) {  
           $this->data = "MATMSG:TO:{$email};SUB:{$subject};BODY:{$message};;";  
      }  
   //It generates the Phone numner type of Qr Code  
   public function PHONE($phone){  
     $this->data = "TEL:{$phone}";  
   }  
   //It generates the Sms type of Qr code  
      public function SMS($phone = null, $msg = null) {  
           $this->data = "SMSTO:{$phone}:{$msg}";  
      }  
   //It generates the VCARD type of Qr code  
      public function CONTACT($name = null, $address = null, $phone = null, $email = null) {  
           $this->data = "MECARD:N:{$name};ADR:{$address};TEL:{$phone};EMAIL:{$email};;";  
      }  
   // It Generates the Image type of Qr Code  
      public function CONTENT($type = null, $size = null, $content = null) {  
           $this->data = "CNTS:TYPE:{$type};LNG:{$size};BODY:{$content};;";  
      }  
   // Saving the Qr code image   
      public function QRCODE($size = 400, $filename = null) {  
           $ch = curl_init();  
           curl_setopt($ch, CURLOPT_URL, $this->apiUrl);  
           curl_setopt($ch, CURLOPT_POST, true);  
           curl_setopt($ch, CURLOPT_POSTFIELDS, "chs={$size}x{$size}&cht=qr&chl=" . urlencode($this->data));  
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
           curl_setopt($ch, CURLOPT_HEADER, false);  
           curl_setopt($ch, CURLOPT_TIMEOUT, 30);  
           $img = curl_exec($ch);  
           curl_close($ch);  
           if($img) {  
                if($filename) {  
                     if(!preg_match("#\.png$#i", $filename)) {  
                          $filename .= ".png";  
                     }  
                     return file_put_contents($filename, $img);  
                } else {  
                     header("Content-type: image/png");  
                     print $img;  
                     return true;  
                }  
           }  
           return false;  
      }  
 }  
 ?>
To create the QR code you need to include the qrcode.php file in your index.php file
<?php  
 include "qrcode.php";   
 // Create QRcode object   
 $qc = new QRCODE();   
 // create text QR code   
 $qc->TEXT("TechiesBadi");     
 // render QR code  
 $qc->QRCODE(400,"qrcode.png");  
 ?>  
Like this you can generate the remainig Qrcodes.
// URL QR code 
$qc->URL('www.techiesbadi.in');

// EMAIL QR code 
$qc->EMAIL('info@techiesbadi.in', 'SUBJECT', 'MESSAGE');

// PHONE QR code 
$qc->PHONE('PHONENUMBER');

// SMS QR code 
$qc->SMS('PHONENUMBER', 'MESSAGE');

// CONTACT QR code 
$qc->CONTACT('NAME', 'ADDRESS', 'PHONE', 'EMAIL');
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to get the geolocation details of the user during a website visit

How to get the geolocation details of the user during a website visit

Hi, You will learn in this tutorial how to get the geolocation details of the user during a website visit. Basically, we need the visitor's location details to analyze the site webmasters to know which country users are visiting the site and also some area wise reports and interested post published on the website, For which post gains more traffic from the particular country or region. And also this is very useful when a website is a done in the country wise website like

http://in.example.com/
http://us.example.com/
http://fr.example.com/
http://de.example.com/

In this situation also we need to collect the visited user's geolocation. Because we collect the user's geolocation then we will redirect the user to based on the country website.

Suppose if a user is visited the http://www.example.com/ the user is coming from the united states then we will redirect to the http://us.example.com/

To do this by using a simple plugin i.e geo plugin. By using this plugin we can get the visited user's information like city, region, Country Name, Country Code, Currency Code, etc..

You need to download the geoplugin library and call it on your page.
http://www.geoplugin.com/_media/webservices/geoplugin.class.phps
 <?php  
 require_once('geoplugin.class.php');  
 $geoplugin = new geoPlugin();  
 //locate the IP  
 $geoplugin->locate();  
 echo "Geolocation results for {$geoplugin->ip}: <br />\n".  
      "City: {$geoplugin->city} <br />\n".  
      "Region: {$geoplugin->region} <br />\n".  
      "Area Code: {$geoplugin->areaCode} <br />\n".  
      "DMA Code: {$geoplugin->dmaCode} <br />\n".  
      "Country Name: {$geoplugin->countryName} <br />\n".  
      "Country Code: {$geoplugin->countryCode} <br />\n".  
      "Longitude: {$geoplugin->longitude} <br />\n".  
      "Latitude: {$geoplugin->latitude} <br />\n".  
      "Currency Code: {$geoplugin->currencyCode} <br />\n".  
      "Currency Symbol: {$geoplugin->currencySymbol} <br />\n".  
      "Exchange Rate: {$geoplugin->currencyConverter} <br />\n";  
 ?>  
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to Export and Download the Mysql Table data to CSV File in PHP

How to Export and Download the Mysql Table data to CSV File in PHP

Hi, You will learn in this tutorial How to Export and Download the Mysql Table data to CSV File in PHP. Sometimes you need to Export the user's data to CSV file because if a client wants to send the emails from the Autoresponders like Aweber, GetResponse, Mailchimp, etc..

In this case, you need to provide the user's contact information in the form of CSV file. It is a comma separated values so the human can read easily and exported CSV file can be imported on the Auto responders easily.

Related to Read : How to Upload CSV File into Database Using PHP and MYSQL

MySql Users Table
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `user_first_name` varchar(100) NOT NULL,
  `user_last_name` varchar(100) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `user_country` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`);

ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT;
Exporting the MySql table data to CSV file follow the step by step process

Step #1: Connect to the MySql Database in PHP
First let's connect to the database using the mysqli() object.
 <?php  
 $servername = "localhost";  
 $username = "root";  
 $password = "";  
 $dbname = "leads";  
 // Create connection  
 $con = new mysqli($servername,$username, $password, $dbname);  
 // Check connection  
 if ($con->connect_error) {  
 die("Connection failed: " . $con->connect_error);  
 }  
 ?>  
Step #2: Select the table and its columns from the MySql database
After connecting to the database, we need to fetch the records from the table.
If you want to export the entire table then execute this SQL Query "SELECT * FROM `users`"
otherwise, you need the custom columns then specify the column names in the Query "SELECT `user_first_name`,`user_email` FROM `users`".  Here I am taking the entire table 'users'.
 <?php  
 // Fetch Records From Table  
 $sql = "SELECT * FROM `users`";  
 $result = $con->query($sql);  
 ?>  
Step #3: Converting the MySql Results to CSV file format
Now we have to convert the fetched records into CSV file one by one. First, we need to write the table headings after that write the each row of data into the CSV file.
 <?php  
 $output = "";  
 // Get The Field Names from the table  
 while ($fieldinfo=$result->fetch_field())  
 {  
 $output .= '"'.$fieldinfo->name.'",';  
 }  
 $output .="\n";  
 // Get Records from the table  
 while ($row = $result->fetch_array()) {  
 for ($i = 0; $i < $columns_total; $i++) {  
 $output .='"'.$row["$i"].'",';  
 }  
 $output .="\n";  
 }  
 ?>  
Here each and every table records are saved in the form of the comma separated value format in the $output.

Step #4: Download the Exported CSV file.
Here we need to specify the CSV file name and add the PHP headers application/csv and then add the attachment header this will force to downloaded the CSV file in the Browser.
 <?php   
 // Download the CSV file  
 $filename = "myFile.csv";  
 header('Content-type: application/csv');  
 header('Content-Disposition: attachment; filename='.$filename);  
 echo $output;  
 ?>  
Complete PHP code to Export and Download the MySql Table data to CSV File
 <?php  
 $servername = "localhost";  
 $username = "root";  
 $password = "";  
 $dbname = "leads";  
 // Create connection  
 $con = new mysqli($servername,$username, $password, $dbname);  
 // Check connection  
 if ($con->connect_error) {  
 die("Connection failed: " . $con->connect_error);  
 }  
 // Fetch Records From Table  
 $output = "";  
 $sql = "SELECT * FROM `users`";  
 $result = $con->query($sql);  
 $columns_total = mysqli_num_fields($result);  
 // Get The Field Names from the table  
 while ($fieldinfo=$result->fetch_field())  
 {  
 $output .= '"'.$fieldinfo->name.'",';  
 }  
 $output .="\n";  
 // Get Records from the table  
 while ($row = $result->fetch_array()) {  
 for ($i = 0; $i < $columns_total; $i++) {  
 $output .='"'.$row["$i"].'",';  
 }  
 $output .="\n";  
 }  
 // Download the CSV file  
 $filename = "myFile.csv";  
 header('Content-type: application/csv');  
 header('Content-Disposition: attachment; filename='.$filename);  
 echo $output;  
 exit;  
 ?> 
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff

How to integrate the PayPal payment gateway in PHP

Hi, Today I am going to explain the major payment gateway used by all websites. i.e PayPal
This is a very simple mechanism to integrate the Paypal payment gateway in web applications.

First, we need the business email for the Paypal Account for this you have to sign up in the Paypal Website.

Before going to integrate the Paypal in web applications you need know about these Payment Modes

1) Test Mode
2) Live Mode

In test mode, you can set the test URL i.e https://www.sandbox.paypal.com/cgi-bin/webscr
Here you can test the payment mechanism before going to live mode. This is very helpful for the developers

In live mode, you can set the live URL i.e https://www.paypal.com/cgi-bin/webscr
Here you can't test the payment mechanism in live mode. All the transactions are done in real accounts (Means all transactions are made live)

You need to pass the some of the hidden input parameters through the POST request to the Paypal.
item_name, item_number, amount, currency_code. These are the Product details.

And one more thing finally you need to pass the two input parameters through the POST request
cancel_return -- Here you need to specify the cancel return URL if a transaction fails.
return -- Here you need to specify the return URL after the successful transaction completes

Payments db
CREATE TABLE `payments` (
  `payment_id` int(11) NOT NULL,
  `item_number` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `payment_gross` float(10,2) NOT NULL,
  `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `payments`
  ADD PRIMARY KEY (`payment_id`);
index.php
 <?php  
 $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; //Test PayPal API URL  
 $paypal_id = 'techiesbadi@gmail.com'; //Business Email  
 ?>  
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
 <title>Paypal Payments --TechiesBadi</title>  
 </head>  
 <body>  
 <center>  
 <h1>Paypal Payments</h1>  
   <img src="images/redmi.png"/>  
   <br/>Redmi 3s prime  
   <br/> $ 10.00  
   <form action="<?php echo $paypal_url; ?>" method="post">  
     <!-- Here Specify the Paypal Bussiness Email-->  
     <input type="hidden" name="business" value="<?php echo $paypal_id; ?>">  
     <!-- Specify a Buy Now button. -->  
     <input type="hidden" name="cmd" value="_xclick">  
     <!-- Here Specify the buyer product details -->  
     <input type="hidden" name="item_name" value="Product1">  
     <input type="hidden" name="item_number" value="1">  
     <input type="hidden" name="amount" value="10">  
     <input type="hidden" name="currency_code" value="USD">  
     <!-- Here Specify the Return and Cancel URLs -->  
     <input type='hidden' name='cancel_return' value='http://demos.techiesbadi.in/paypal/cancel.php'>  
           <input type='hidden' name='return' value='http://demos.techiesbadi.in/paypal/success.php'>  
     <!-- Display the payment button. -->  
     <input type="image" name="submit" border="0"  
     src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">  
     <img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >  
   </form>  
   </center>  
 </body>  
 </html>
success.php
<?php  
 include 'config.php';  
 extract($_REQUEST);  
 //Store transaction information from PayPal  
 $item_number = $item_number;   
 $txn_id = $tx;  
 $payment_gross = $amt;  
 $currency_code = $cc;  
 $payment_status = $st;  
 if(!empty($txn_id)){  
      //Check if payment data exists with the same TXN ID.  
   $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");  
   if($prevPaymentResult->num_rows > 0){  
     $paymentRow = $prevPaymentResult->fetch_assoc();  
     $last_insert_id = $paymentRow['payment_id'];  
   }else{  
     //Insert tansaction data into the database  
     $insert = $db->query("INSERT INTO payments(item_number,txn_id,payment_gross,currency_code,payment_status) VALUES('$item_number','$txn_id','$payment_gross','$currency_code','$payment_status')");  
     $last_insert_id = $db->insert_id;  
   }  
 ?>  
      <h1>Your payment has been successful.</h1>  
   <h1>Your Payment ID - <?php echo $last_insert_id; ?>.</h1>  
 <?php  
 }else{  
 ?>  
      <h1>Your payment has failed.</h1>  
 <?php  
 }  
 ?> 
 
cancel.php
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
 <title>PayPal Transaction Cancel - TechiesBadi</title>  
 </head>  
 <body>  
      <h1>Your PayPal transaction has been canceled.</h1>  
 </body>  
 </html>  
config.php
 <?php  
 //Database credentials  
 $dbHost = 'localhost';  
 $dbUsername = 'root';  
 $dbPassword = '';  
 $dbName = 'techiesbadi';  
 //Connect with the database  
 $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  
 ?>  
 
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to convert the PHP Array to JSON String

How to convert the PHP Array to JSON String

Hi, In this tutorial, I am going to explain, How to convert the PHP Array to JSON String.

If you want to convert the PHP Array to JSON String use the json_encode().It will convert the PHP Array to JSON String.
Syntax: json_encode($array, Constant1 | Constant2 .... | Constantn);
How to log out a user after 10 minutes of inactivity on the site

Consider sample PHP Array
$array = array(
"website" => "Techiesbadi",
"url" => "http://techiesbadi.in",
"description" => "Programming Blog"
);
Now we have to convert this array to JSON string.
<?php  
 $array = array(  
 "website" => "Techiesbadi",  
 "url" => "http://techiesbadi.in",  
 "description" => "Programming Blog"  
 );  
 //json_encode($array);  
 $JSON=json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);  
 echo "<pre>";  
 echo $JSON;  
 echo "</pre>";  
 ?> 
Output
{
    "website": "Techiesbadi",
    "url": "http://techiesbadi.in",
    "description": "Programming Blog"
}
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to log out a user after 10 minutes of inactivity on the site

How to log out a user after 10 minutes of inactivity on the site

Hi, In this tutorial, I am going to teach you how to log out a user after 10 minutes of inactivity on the site.

Generally, we implement the logic like this when user logins authenticate the user information, If user information is a valid i.e username, email, and password then we will create the session for the user.

Then user session is maintained throughout the website. whenever a user logs out then we will remove the session of the user on the server. If a user doesn't log out from the site then his session never expired / removed automatically, we have to remove the session manually, In this situation, we can implement this mechanism i.e log out a user after 10 minutes of inactivity on the site.
In Session start page to set the login time in the session.

sessionStart.php
<?php  
 session_start(); //on pageload  
 $_SESSION['start_time'] = time(); //on session creation  
 $_SESSION["name"] = "TechiesBadi";  
 $_SESSION["email"] = "techiesbadi@gmail.com";  
 header('Location: home.php');  
?>  
isLoggedIn.php
<?php  
 session_start(); //on pageload  
 $timeout = 10; // Set timeout minutes  
 $logout_redirect_url = "index.php"; // Set logout URL  
 $timeout = $timeout * 60; // Converts minutes to seconds  
 if (isset($_SESSION['start_time'])) {  
   $elapsed_time = time() - $_SESSION['start_time'];  
   if ($elapsed_time >= $timeout) {  
     session_destroy();  
     header("Location: $logout_redirect_url");  
   }  
 }  
 $_SESSION['start_time'] = time();  
?>
include this isLoggedIn.php in your header page simply or you can add this entire code in header page. Then a user can log out the site after 10 minutes of inactivity on the site automatically.

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff

CURD operations using PHP Functions with Bootstrap

Hi, In this tutorial, I am going to teach you how to perform the CURD operations using PHP Functions with Bootstrap.

What do you mean by CRUD operations ?
CRUD operations are the basic operations in database
C - Create
R - Read
U - Update
D - Delete

Generally, we implement the CURD operations normal way. But we implement these operations by using PHP functions.
The code will clean and reduce the steps also and we can reuse these functions in a later project also.

Simply implement the function execute($query). Here execute function needs the one parameter i.e $query.
You have to pass the SQL query here it will execute the query. Like this way, you have to write all those functions for the CRUD operations.

Step #1:
We need to create the database with name student
data table
--
-- Table structure for table `data`
--

CREATE TABLE `data` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step #2:
We need to connect the database from PHP
config.php
<?php
$servername = "localhost";
$username = "root";
$password = "vertrigo";
$dbname = "student";

// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 

include "includes/functions.php";
?>
Step #3:
Create includes folder in your project directory and create the functions.php file
This file contains the CURD operations functions
functions.php
<?php
//Execute the query statement
function execute($query){
    global $con;
    if($con->query($query)){
        return 1;
    } 
    else{
        return 0;
    }
}

//Delete the record from the table
function delete($table,$id){
    global $con;
    if($con->query("DELETE FROM $table WHERE id = $id")){
        return 1;
    } 
    else{
        return 0;
    }
}

//Return result set
function getData($table){
    global $con;
    $result = $con->query("SELECT * FROM $table");
    return $result;
}

//Return a single record
function getRecord($table,$id){
    global $con;
    $result = $con->query("SELECT * FROM $table WHERE id = $id");
    $record = $result->fetch_object();
    return $record;
}

//Returns number of affected rows
function rowCount($table){
    global $con;
    $result = $con->query("SELECT * FROM $table");
    $count =$result->num_rows;
    return $count;
}

//Returns last inserted id
function lastInsertId(){
    global $con;
    return $con->insert_id;
}

//Close the connection
function close(){
    global $con;
    $con->close();
}
?>

Step #4:
Now just call the functions to execute
For insertion
<?php
include "config.php";
$insert = "INSERT INTO `data` (`id`, `name`, `address`, `email`) VALUES (NULL, 'test', 'test', 'test@test.com')";
$i = execute($insert);
if($i == 1){
    echo "1 row inserted";
}
?>
Fetch the data from table
<?php
include "config.php";
$data = getData("data");
while($row = $data->fetch_object()){
    echo $row->id;
}
?>
Get single record from table
<?php
include "config.php";
$row = getRecord("data",6);
print_r($row);
echo $row->id;
echo "<br />";
echo $row->name;
echo "<br />";
echo $row->address;
echo "<br /> 
";
echo $row->email;
echo "<br />";
?>
How to get the rows count from the table
<?php
include "config.php";
echo rowCount("data");
?>
How to get the last inserted id
<?php
include "config.php";
$insert = "INSERT INTO `data` (`id`, `name`, `address`, `email`) VALUES (NULL, 'test', 'test', 'test@test.com')";
echo "
".lastInsertId(execute($insert));
?>
Download Demo


Now the implementation of the CURD operations using PHP Functions with Bootstrap.
index.php
<!DOCTYPE html>  
 <html lang="en">  
 <head>  
  <title>DB Functions</title>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="stylesheet" href="assets/css/bootstrap.min.css">  
   <link rel="stylesheet" href="assets/css/style.css">  
  <script src="assets/js/jquery.min.js"></script>  
  <script src="assets/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
 <?php  
 extract($_REQUEST);   
 include "config.php";   
 ?>  
 <div class="container">  
  <div class="row">  
   <div class="col-md-6">  
    <h2>Student Information</h2>  
    <p>View all student information</p>  
   </div>  
   <div class="col-md-6">  
   <a href="" class="top btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Add new student</a>  
   </div>  
  </div>  
  <?php  
  if(isset($remove)){  
   $status = delete("data",$remove);  
   if($status == 1){  
    echo '<div class="alert alert-success" role="alert">Student record is removed successfully</div>';  
   }  
  }  
  if(isset($sadd)){  
   echo '<div class="alert alert-success" role="alert">Student record is added successfully</div>';  
  }  
  if(isset($supdate)){  
   echo '<div class="alert alert-success" role="alert">Student record is updated successfully</div>';  
  }  
  ?>  
  <table class="table table-hover">  
   <thead>  
    <tr>  
     <th>#</th>  
     <th>Name</th>  
     <th>Address</th>  
     <th>Email</th>  
     <th>Edit</th>  
     <th>Remove</th>  
    </tr>  
   </thead>  
   <tbody>  
   <?php  
     $data = getData("data");  
     while($row = $data->fetch_object()){  
   ?>  
    <tr>  
     <td><?=$row->id;?></td>  
     <td><?=$row->name;?></td>  
     <td><?=$row->address;?></td>  
     <td><?=$row->email;?></td>  
      <td><a href="edit.php?sid=<?=$row->id;?>"><span class="glyphicon glyphicon-edit"></span></a></td>  
     <td><a href="index.php?remove=<?=$row->id;?>"><span class="glyphicon glyphicon-trash"></span></a></td>  
    </tr>  
   <?php } ?>  
   </tbody>  
  </table>  
  <!-- Modal -->  
 <div id="myModal" class="modal fade" role="dialog">  
  <div class="modal-dialog">  
   <!-- Modal content-->  
   <div class="modal-content">  
    <div class="modal-header">  
     <button type="button" class="close" data-dismiss="modal">&times;</button>  
     <h4 class="modal-title">Student</h4>  
    </div>  
    <div class="modal-body">  
     <form role="form" method="post" action="save.php">  
      <div class="form-group">  
       <label for="name">Name:</label>  
       <input type="text" class="form-control" id="sname" name="sname">  
      </div>  
      <div class="form-group">  
       <label for="add">Address:</label>  
       <textarea class="form-control" rows="5" id="add" name="add"></textarea>  
      </div>  
      <div class="form-group">  
       <label for="email">Email address:</label>  
       <input type="email" class="form-control" id="email" name="email">  
      </div>  
      <button type="submit" class="btn btn-default">Submit</button>  
     </form>  
    </div>  
   </div>  
  </div>  
 </div>  
 <?php close(); ?>  
 </div>  
 </body>  
 </html> 
save.php
<?php  
 extract($_REQUEST);   
 include "config.php";  
 $insert = "INSERT INTO `data` (`id`, `name`, `address`, `email`) VALUES (NULL, '$sname', '$add', '$email')";  
 $status = execute($insert);  
 if($status == 1){  
      echo '<script>window.location.assign("index.php?sadd=success");</script>';  
 }  
 close();  
 ?>  
edit.php
<!DOCTYPE html>  
 <html lang="en">  
 <head>  
  <title>DB Functions</title>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="stylesheet" href="assets/css/bootstrap.min.css">  
   <link rel="stylesheet" href="assets/css/style.css">  
  <script src="assets/js/jquery.min.js"></script>  
  <script src="assets/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
 <?php  
 extract($_REQUEST);   
 include "config.php";   
 $row = getRecord("data",$sid);  
 ?>  
 <div class="container">  
   <h2>Student Information</h2>  
      <form role="form" method="post" action="update.php">  
       <input type="hidden" id="sid" name="sid" value="<?=$row->id;?>">  
       <div class="form-group">  
           <label for="name">Name:</label>  
           <input type="text" class="form-control" id="sname" name="sname" value="<?=$row->name;?>">  
       </div>  
       <div class="form-group">  
           <label for="add">Address:</label>  
           <textarea class="form-control" rows="5" id="add" name="add"><?=$row->address;?></textarea>  
       </div>  
       <div class="form-group">  
           <label for="email">Email address:</label>  
           <input type="email" class="form-control" id="email" name="email" value="<?=$row->email;?>">  
       </div>  
       <button type="submit" class="btn btn-default">Update</button>  
      </form>  
 <?php close(); ?>  
 </div>  
 </body>  
 </html>  
update.php
 <?php  
 extract($_REQUEST);   
 include "config.php";  
 $update = "UPDATE `data` SET `name` = '$sname', `address` = '$add', `email` = '$email' WHERE `id` = $sid";  
 $status = execute($update);  
 if($status == 1){  
      echo '<script>window.location.assign("index.php?supdate=success");</script>';  
 }  
 close();  
 ?>  
Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to save the image from url directly

How to save the image from url directly

Hi, In this tutorial, I am going to teach you how to save the image from url directly.

Suppose in your web application user picture to be taken from the external URL. for example if a user signup / login using facebook in this case user profile picture url is return from the facebook. then you have to save the image from the external source in this situation we can use this logic.

saveimage.php
<?php  
 error_reporting(0);  
 function check_cURL()  
 {  
   if (in_array('curl', get_loaded_extensions())) {  
     return true;  
   } else {  
     return false;  
   }  
 }  
 function mime_content_type($filename)  
 {  
   $mime_types = array(  
     'txt' => 'text/plain',  
     'htm' => 'text/html',  
     'html' => 'text/html',  
     'php' => 'text/html',  
     'css' => 'text/css',  
     'js' => 'application/javascript',  
     'json' => 'application/json',  
     'xml' => 'application/xml',  
     'swf' => 'application/x-shockwave-flash',  
     'flv' => 'video/x-flv',  
     // images  
     'png' => 'image/png',  
     'jpe' => 'image/jpeg',  
     'jpeg' => 'image/jpeg',  
     'jpg' => 'image/jpeg',  
     'gif' => 'image/gif',  
     'bmp' => 'image/bmp',  
     'ico' => 'image/vnd.microsoft.icon',  
     'tiff' => 'image/tiff',  
     'tif' => 'image/tiff',  
     'svg' => 'image/svg+xml',  
     'svgz' => 'image/svg+xml',  
     // archives  
     'zip' => 'application/zip',  
     'rar' => 'application/x-rar-compressed',  
     'exe' => 'application/x-msdownload',  
     'msi' => 'application/x-msdownload',  
     'cab' => 'application/vnd.ms-cab-compressed',  
     // audio/video  
     'mp3' => 'audio/mpeg',  
     'qt' => 'video/quicktime',  
     'mov' => 'video/quicktime',  
     // adobe  
     'pdf' => 'application/pdf',  
     'psd' => 'image/vnd.adobe.photoshop',  
     'ai' => 'application/postscript',  
     'eps' => 'application/postscript',  
     'ps' => 'application/postscript',  
     // ms office  
     'doc' => 'application/msword',  
     'rtf' => 'application/rtf',  
     'xls' => 'application/vnd.ms-excel',  
     'ppt' => 'application/vnd.ms-powerpoint',  
     // open office  
     'odt' => 'application/vnd.oasis.opendocument.text',  
     'ods' => 'application/vnd.oasis.opendocument.spreadsheet'  
   );  
   $ext    = strtolower(array_pop(explode('.', $filename)));  
   if (array_key_exists($ext, $mime_types)) {  
     return $mime_types[$ext];  
   } elseif (function_exists('finfo_open')) {  
     $finfo  = finfo_open(FILEINFO_MIME);  
     $mimetype = finfo_file($finfo, $filename);  
     finfo_close($finfo);  
     return $mimetype;  
   } else {  
     return 'application/octet-stream';  
   }  
 }  
 function getimg($url)  
 {  
   $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';  
   $headers[] = 'Connection: Keep-Alive';  
   $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';  
   $useragent = 'php';  
   $process  = curl_init($url);  
   curl_setopt($process, CURLOPT_HTTPHEADER, $headers);  
   curl_setopt($process, CURLOPT_HEADER, 0);  
   curl_setopt($process, CURLOPT_USERAGENT, $useragent);  
   curl_setopt($process, CURLOPT_TIMEOUT, 30);  
   curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);  
   curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);  
   $return = curl_exec($process);  
   curl_close($process);  
   return $return;  
 }  
 function check_url_exist($url)  
 {  
   $handle = curl_init($url);  
   if (false === $handle) {  
     return false;  
   }  
   curl_setopt($handle, CURLOPT_HEADER, false);  
   curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works  
   curl_setopt($handle, CURLOPT_NOBODY, true);  
   curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);  
   $connectable = curl_exec($handle);  
   curl_close($handle);  
   return $connectable;  
 }  
 if (isset($_POST['link'])) {  
   if (check_cURL()) {  
     $imgurl = $_POST['link'];  
     if (check_url_exist($imgurl)) {  
       $file_type = mime_content_type($imgurl);  
       if (preg_match("/image/i", $file_type)) {  
         $imagename = basename($imgurl);  
         if (file_exists('./tmp/' . $imagename)) {  
           $text_message = 'This file exist!';  
         } else {  
           $image = getimg($imgurl);  
           file_put_contents('tmp/' . $imagename, $image);  
           $text_message = 'This file saved! Click <a href="./tmp/' . $imagename . '" target="_blank">here</a> to see your image.';  
         }  
       } else {  
         $text_message = 'This file is not an image. Please check again!';  
       }  
     } else {  
       $text_message = 'This link is a broken link. Please check again!';  
     }  
   } else {  
     $text_message = "cURL is NOT <span style=\"color:red\">installed</span> on this server";  
   }  
 }  
 ?>  
 <html>  
      <head>  
           <title>Save image from url directly on your server</title>  
           <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
           <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">  
           <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
           <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <div class="row">  
                     <p align="center"><span style="font-size:30px">SAVE IMAGE</span></p>  
                     <p align="center">We only support for image format.</p>  
                     <div align="center" class="col-sm-16" style="margin: 20px 0px;">  
                          <?php  
 if (isset($_POST['link'])) {  
 ?>                                
                               <p style="color: red;font-size: 20px;"><?php  
   echo $text_message;  
 ?></p>  
                          <?php  
 }  
 ?>  
                          <form method="post" class="link_video">  
                               <label for="link-image">Link:</label> <input style="width:300px;" type="text" name="link" id="link-image" value="" placeholder="image.jpg">  
                               <input type="submit" value="GRAB" class="btn btn-success">  
                          </form>  
                     </div>  
                </div>  
           </div>  
      </body>  
 </html>  

Download
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to detect the mobile device in PHP

How to detect the mobile device in PHP

Hi, In this tutorial, I am going to explain How to detect the mobile device in PHP.

This is the simplest way to identify the users mobile device.In many cases, the site owner wants to redirect the mobile users to some other location.
For example, http://www.example.com is the main website URL and one more URL is http://m.example.com .
Here http://www.example.com this is for desktop users & http://m.example.com this is for mobile users.

In this case, we have to identify the users device. If users device is a desktop then simply stay with the desktop URL otherwise user to be redirected from http://www.example.com to http://m.example.com. find the below the code

mobiledetect.php
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
header('Location: http://m.example.com/');
?>  

Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to Create, Read, Update and Delete a Cookie in PHP

How to Create, Read, Update and Delete a Cookie in PHP

In this tutorial, I will explain how to create, read, update and delete the cookie in PHP.

What is a cookie ?
Generally, the cookie will be stored in client side i.e in a browser, Each time the same computer requests a page with a browser, it will send the cookie to the server. This mechanism is mostly used in the shopping carts.

How to create the cookie
By using the setcookie method to create the cookie in PHP. Here we have to pass some values in this method, those are name, value, expire, path.
<?php
$cookie_name = 'site_user';
$cookie_value = 'TechiesBadi';
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
?>
This cookie will expire after 30 days. Using "/", the cookie is available in all website (otherwise, select the directory you prefer).
If you want to change the expire days just change as 30 to your own days.

How to read the cookie
By using global variable $_COOKIE to retrieve the stored cookies in PHP.
<?php
$cookie_name = 'site_user';
if(!isset($_COOKIE[$cookie_name])) {
  print 'Cookie ' . $cookie_name . ' does not exist...';
} else {
  print  $cookie_name . 'value is: ' . $_COOKIE[$cookie_name];
}
?>
How to update the cookie
Actually, there is no method for updating the cookie just simply recreate the cookie by using setcookie method.
<?php
$cookie_name = 'site_user';
$cookie_value = 'Techies';
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
?>
How to delete the cookie
By using the setcookie() function with an expiration date in the past.
<?php
$cookie_name = 'site_user';
unset($_COOKIE[$cookie_name]);
// empty value and expiration one hour before
$res = setcookie($cookie_name, '', time() - 3600);
?>

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff

How to integrate the Bulk SMS Provider API in PHP

Hi, In this tutorial, I am going to explain how to integrate the Bulk SMS Provider API in PHP.

What is Bulk SMS Provider API ?
Bulk SMS Provider is extended message service through Their software has provided a bulk full of messaging feature connecting all of us across the entire country. This service has whacked the other previously used SMS services through its speedy and accessible benefits. This has offered high connectivity, the best service, and message flow in an efficient way.

First, We need to register at the http://bulksmsserviceproviders.com/

Bulk SMS Provider  offers a free trial with 25 Transactional credits for testing purpose.
These Transactional  messages even mobile is on DND also a message will be sent.

Here we need to provide the original information i.e valid mobile number and email because your Bulk SMS Provider will send the verification code to the registered mobile number only.

How find your authentication key
Click  Developer Tools on the right navbar it will redirect to the Developer Tools page .

after the click Auth Key on the right navbar .


It will pop up the authentication key.









bulkSms.php
<?php
//Your authentication key
$authKey = "YourAuthKey";
//Multiple mobiles numbers separated by comma
$mobileNumber = "9999999";
//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "102234";
//Your message to send, Add URL encoding here.
$message = rawurlencode("Test message");
//Define route 
$route = "template";
//Prepare you post parameters
$postData = array(
    'authkey' => $authKey,
    'mobiles' => $mobileNumber,
    'message' => $message,
    'sender' => $senderId,
    'route' => $route
);
//API URL
$url = "http://sms.bulksmsserviceproviders.com/api/send_http.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData
    //,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
    echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo $output;
?>

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff

How to integrate the SMS gateway hub API in PHP

Hi, In this tutorial, I am going to explain how to integrate the SMS gateway hub API in PHP.

What is SMS gateway hub ?
SMS gateway hub is an SMS provider in India. It will allow to easily send & manage texts from PC, Web, Android, API or Excel.

First, We need to register at the https://www.smsgatewayhub.com/

SMS gateway hub  offers a free trial with 20 to 40 credits for testing purpose.

Here we need to provide the original information i.e valid mobile number and email because your SMS gateway hub  account username & password will be sent to the registered mobile number only.

After that, you will get a call from SMS gateway hub . They will ask you,
 Do you want promotional credits or transactional credits ?

Then you will ask them to give the promotional credits, Then they will credit the  20 to 40 promotional credits to your account.

Each credit equals to one SMS
i.e 20 credits = 20 SMS

API key is found at API Documents -> API Codes






sendSMS.php
<?php  
 function sendSMS($mobile,$message){  
 $user = "YOUR-API-KEY-HERE";  
 $url = 'http://login.smsgatewayhub.com/api/mt/SendSMS?APIKey='.$user.'&senderid=WEBSMS&channel=INT&DCS=0&flashsms=0&number='.$mobile.'&text='.$message.'&route=16;';  
 $ch=curl_init($url);  
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
 curl_setopt($ch,CURLOPT_POST,1);  
 curl_setopt($ch,CURLOPT_POSTFIELDS,"");  
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,2);  
 $data = curl_exec($ch);  
 print($data); /* result of API call*/  
 }  
?>  
Call the sendSMS function with two parameters, Those are mobile number and message.
<?php  
 $message = rawurlencode("Your message here");  
 sendSMS("919XXXXXXXXX",$message);  
 ?>  
Here 91 is the country code of India.
Output:
{"ErrorCode":"000","ErrorMessage":"Success","JobId":"36049283","MessageData":[{"Number":"919XXXXXXXXX","MessageId":"NGQPxdsUL0i5gaciWDMbxQ"}]}

Download
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to enable php intl extension in XAMPP / WAMP

How to enable php intl extension in XAMPP / WAMP

What is the php intl extension. It is a Internationalization extension. It is useful for formatting currency, number and date or time as well as UCA-conformant collations, for message formatting and normalizing text..etc

If you want to enable the php intl extension .Follow these steps.

Step #1:
Open the [xampp / Wamp path]/php/php.ini file
Now search for the extension=php_intl.dll
By default it is in commented mode
;extension=php_intl.dll 
Just remove the ; ( semicolon)
extension=php_intl.dll 
Then save the php.ini file

The latest versions of servers are supported just this minimal setting in the step #1.
Just restart your server for take effect the new changes.

If you got any warnings while your  server starts continue the below steps .Otherwise you did n’t get any warnings while your server starts then your  php intl extension is enabled successfully.

Step #2:
Browse the your server installation path like this
  
|-[xampp / Wamp path]/
|   |-php/
|   |  |-icudt57.dll
|   |  |-icuin57.dll
|   |  |-icuio57.dll
|   |  |-icule57.dll
|   |  |-iculx57.dll
|   |  |-icutu57.dll 
|   |  |-icuuc57.dll
Copy all these icu*.*.dll files from [xampp / Wamp path]/php to [xampp / Wamp path]/apache/bin

Now restart your server it takes effect.

When server starts you get  error 'MSVCR100.dll' is missing.
Now fix this error

Step #3:
You have to download the missing .dll file from here
https://www.microsoft.com/en-sg/download/confirmation.aspx?id=30679
Download the vcredist_x64.exe file and install them in to your system after installation restart your server to take effects.
Now php intl extension is enabled successfully.

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to send  email using Gmail SMTP with PHP

How to send email using Gmail SMTP with PHP

Generally any web application needs to send the emails to the users when there registration for the verification purpose or any notifications to the users.

In this mechanism we would like to send the emails through Gmail SMTP Configuration.
This is very simple to configure the SMTP setting in php

Before going to the code you need
  1. Your working gmail account with password
  2. Gmail Host : smtp.gmail.com
  3. Gmail port : 465 or 587
  4. Protocol : ssl or  tls
For more details about Gmail SMTP server
Project Structure
|-Smtpmail
| |-classes
| | |-class.phpmailer.php
| | |-class.smtp.php
|-library.php
|-smtpgmail.php
First of all you need the class.phpmailer.php , class.smtp.php and library.php files
smtpgmail.php
 <?php  
 include "classes/class.phpmailer.php"; // include the class name  
 $mail = new PHPMailer(); // create a new object  
 $mail->IsSMTP(); // enable SMTP  
 $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only  
 $mail->SMTPAuth = true; // authentication enabled  
 $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail  
 $mail->Host = "smtp.gmail.com";  
 $mail->Port = 465; // or 587  
 $mail->IsHTML(true);  
 $mail->Username = "YOURUSERNAME@gmail.com";  
 $mail->Password = "YOURPASSWORD";  
 $mail->SetFrom("YOURUSERNAME@gmail.com");  
 $mail->Subject = "GMAIL SMTP MAIL WITH PHP";  
 $mail->Body = "Welcome to TechiesBadi Programming blog url is: http://techiesbadi.blogspot.in";  
 $mail->AddAddress("TOADDRESS@EXAMPLE.COM");  
  if(!$mail->Send()){  
      echo "Mailer Error: " . $mail->ErrorInfo;  
 }  
 else{  
      echo "Message has been sent";  
 }  
 ?>  
The above code change these fields to your credentials
YOURUSERNAME, YOURPASSWORD
And change the to address of this field TOADDRESS@EXAMPLE.COM

Download
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to get the base url in php

How to get the base url in php

Suppose you have to retrieve the URL of the application in PHP i.e http://example.com
Using this piece of code
//output : example.com
$DOMAIN = $_SERVER['SERVER_NAME']; 
// output: http:// 
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://'; 
// output : http://example.com
$main_url = $protocol.$DOMAIN; 
When you are running the application in the subfolder / subdomain in the main website.I.e http://example.com/myproject/
In this case you want to retrieve the base url of the application not the main site url.

Use this simple function to get the base url of your application.
 
function getBaseUrl() 
{
    // output: /myproject/index.php
    $currentPath = $_SERVER['PHP_SELF']; 

    // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
    $pathInfo = pathinfo($currentPath); 

    // output: example.com
    $hostName = $_SERVER['HTTP_HOST']; 

    // output: http://
    $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';

    // return: http://example.com/myproject/
    return $protocol.$hostName.$pathInfo['dirname']."/";
}

$base_url = getBaseUrl();

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff
How to embed the user address using google map in php

How to embed the user address using google map in php

If you want to display the user's address in google map in their profile’s page. It is very simple follow these procedure.

Generally in user registration we store the user information like country, state, city or even taken the address fields. Do you want to display the user's address map on their profile page. You must need the address of the user.

This simple piece of code going to display the user's address in embed google map.
<?php  
 $userAddress ="Arundelpet, Guntur, Andhra Pradesh, India";  
?>  
<iframe width="640" height="480" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.it/maps?q=<?php echo $userAddress; ?>&output=embed">  
</iframe>   
Out put:


* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff