Category Archives: Core Php

How to get image from youtube and vimeo embedded url?

This tutorial for gettting the image from youtube and vimeo embedded url using the php code without any 3rd party tools. you can just enter the embedded url in below code and get HD Image from this two plateform

Step 1)

just put this code in your php file where you want to get the youtube and vimeo embedded url image in high resolution.

$url2 = "Your youtube and vimeo embedded url here";
$parsed     = parse_url($url2);
$hostname   = $parsed['host']; 
$path       = $parsed['path']; 
if(!empty($hostname)){
  if($hostname=='www.youtube.com' || $hostname=='youtube.com'){
	preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url2, $match);
	$youtube_id = $match[1];
        $videoID = substr($youtube_id,0,11);
        $video_image_src = "https://i.ytimg.com/vi/".$videoID."/maxresdefault.jpg";
	$video_image_href = "https://www.youtube.com/embed/".$videoID;
}else if($hostname=='player.vimeo.com'){
	preg_match("/vimeo\.com\/(\w+\s*\/?)*([0-9]+)*$/i", $url2, $output_array);
	$vimdeoIDInt = intval($output_array[1]);
	$vimeo = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$vimdeoIDInt.php"));
	$small = $vimeo[0]['thumbnail_small'];
	$medium = $vimeo[0]['thumbnail_medium'];
	$large = $vimeo[0]['thumbnail_large'];
        $video_image_src = $large;
	$video_image_href = "https://player.vimeo.com/video/".$vimdeoIDInt; 
 }
echo $video_image_href;
}

Add Forfully Redirect http to https using php code without .htaccess

This tutorial for redirect the http url to https using the php code if your .htaccess will not work for the SSL. it will just redirect all your http url to https without using the .htaccess if your server https is not on. just follow the step and you can get your own redirction.

Step 1)

just put this code in your main root file or connection file which is included in everywhere of your project. so everytime url will scan with this code and if it finds the http then convert into https.

if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || 
   $_SERVER['HTTPS'] == 1) ||  
   isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
   $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}

How to upload bigger file in Chunks?

This tutorial for upload bigger file split into different part when it will upload and after complete upload it will combine to one file so it your bigger file will upload fast to your upload server. this is use for upload the bigger file to server.

Step 1)

Download the file upload library from here. click here for download

Step 2)

Now run this code in your php server. it will give option for browse the file, where you can browse multiple file for upload to you server

Step 3)

Now you can upload your bigger file with out form submission in php and without any php restriction for upload max file in php server.

How to Generate Image from html using js?

This tutorial about generating the image from the HTML. You can just create the HTML and put this code after your code and it will generate the image from your HTML. below is the easy step to generate the image from custom HTML.

Step 1)

Create one php file like index.php as below

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Html To Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"> </script>
<div class="bingo-box bingo-green generatedata" id="generatedata1" data-id="1">
<div class="number-row number-row1">
<div class="number number1">1</div>
<div class="number number2">2</div>
<div class="number number4">4</div>
<div class="number number5">5</div>
<div class="number number5">9</div>
</div>
</div>
<script>
        $(document).ready(function() {
            var getCanvas;
            $( ".generatedata" ).each(function( index ) {
                var dataid = $( this ).attr("id");
                var catid = $( this ).data("id");
                var datafid = parseInt(index) + parseInt(1);
                var element = $("#"+dataid);
                html2canvas(element, {
                    onrendered: function(canvas) {
                        getCanvas = canvas;
                        var imgageData = getCanvas.toDataURL("image/png");
                        var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
                        $.ajax({
                          type: "POST",
                          url: "upload.php",
                          data: {
                             imgBase64: newData
                          }
                        }).done(function(o) {
                          console.log('saved');
                        });
                    }
                });
            });
        });
    </script>

Step 2)

Create another page like upload.php

<?php
$catid = $_POST['catid'];
$folderPath = "upload_img/";
$image_parts = explode(";base64,", $_POST['imgBase64']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$filename = uniqid() . '.png';
$file = $folderPath . $filename;
file_put_contents($file, $image_base64);
?>

Step 3)

Now Just run index.php file to your browser this will generate the image in folder.

How to Crop Image using cropper with rotation function?

This tutorial about to crop an image using cropper js and also rotate the image as you need. so it will help that upload your crop image to your PHP code. also, this will give other options for an image. so you can easily be used in your PHP code. simply follow the step and get the image cropper in your PHP code.

Step 1)

Download the zip file in your system. Click Here For Download

Step 2)

Now extract this folder and put in your PHP server like xampp or wamp or put directly to the live server where your apache is running.

Step 3)

Finally, Run the index.php file in your system which is in the demo folder it will display the image uploader. select image for crop and rotate and then you can click on done and it will crop the image and display in the image box.

Integrate Stripe API using php

If you need to integrate stripe api to your php project then follow this tutorial which can create/edit/update/delete charges, customer, subscription, plan, payment,card and many more. just simply follow this step and you can get your api working.

Step 1)

NOTE*: for this api integration you need to enable below modules in your apache or live server

  • curl, although you can use your own non-cURL client if you prefer
  • json
  • mbstring (Multibyte String)

Upload this stripe demo library to your project. click here for download library

Step 2)

Now make one test.php file for create customer to stripe using api in php and include below code in that file and save the file.

require_once('strip-demo/vendor/autoload.php');
$stripe = new \Stripe\StripeClient(<ENTER STRIPE KEY HERE>);
$customer = $stripe->customers->create('description' => '<CUSTOMER DESCRIPTION>','email' => "<CUSTOMER EMAIL ADDRESS>",'name' => "<CUSTOMER NAME>",
]);
$id=$customer->id;
print_r($customer); //get response from stripe when customer created in stripe
            
    $stripe = new \Stripe\StripeClient(<ENTER STRIPE KEY HERE>);
    $option = array("object" => 'card', "number" => "<CUSTOMER CARD NUMBER>","exp_month" => "CUSTOMER CARD MONTH","exp_year" => "<CUSTOMER CARD YEAR>","cvc" => "<CUSTOMER CARD CVV>");
    $card = $stripe->customers->createSource(
        $id,['source' => $option]);
        print_r($card_id); //get response from stripe when card created in stripe for specific user

    $data = $stripe->charges->create([
               'amount' => "1.00",
               'customer' => $id,
               'currency' => 'usd',
               'description' => 'Total Subscription Charges',
   ]);

print_r($data); //get response from stripe when charges created in stripe for specific user

Step 3)

Finally, run this test.php file in your system it will sent the data to your stripe. for more api visit this link https://stripe.com/docs/api

How to implement firebase push notification in android and iphone

push_notification_in_iphone_and_android

If you need send Firebase notification using PHP then simple use this tutorials which can help you send the notification to android and iPhone devices. Basically there is a GCM(Google Cloud Messaging) which is sending the notification but now google has been launched Firebase Cloud Messaging (FCM)

Step 1)

Generate the Firebase Server Key. for this you need to follow below steps.

  • Login to the Firebase Developer Console and if you haven’t created a project yet, click “Create Project”.
  • Enter a project name, accept the firebase terms and press “CREATE PROJECT”.
  • Does setup google analytics for your project? select “Not Right Now” and press “CREATE PROJECT”.
  • The project will be created and you get the message “Your new project is ready”, press the “Continue” button to redirect your project dashboard page.
  • On the dashboard page click the Gear icon in the top left and select “Project settings”.
  • Go to the “Cloud Messaging Section” section and you will have the Server Key.
  • Done! I hope you successfully Generate a Firebase Server Key

Step 2)

Create a file named fcm.php and add the below push notification php code. Be sure to replace the Your Firebase Server API Key Here with a proper one from the Google API’s Console page.

<?php
class FCM {
    function __construct() {
    }
   /**
    * Sending Push Notification
   */
  public function send_notification($registatoin_ids, $notification,$device_type) {
      $url = 'https://fcm.googleapis.com/fcm/send';
      if($device_type == "Android"){
            $fields = array(
                'to' => $registatoin_ids,
                'data' => $notification
            );
      } else {
            $fields = array(
                'to' => $registatoin_ids,
                'notification' => $notification
            );
      }
      // Firebase API Key
      $headers = array('Authorization:key=Your Firebase 
Server API Key Here','Content-Type:application/json');
     // Open connection
      $ch = curl_init();
      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      // Disabling SSL Certificate support temporarly
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
      $result = curl_exec($ch);
      if ($result === FALSE) {
          die('Curl failed: ' . curl_error($ch));
      }
      curl_close($ch);
  }
}   
?>

Step 3)

Finally, create an index.php and add the below code. Before testing please replace Your Device Token with your real device token.

<?php
$regId ="Your Device Token";

// INCLUDE YOUR FCM FILE
include_once 'fcm.php';    

$notification = array();
$arrNotification= array();			
$arrData = array();											
$arrNotification["body"] ="Test by Ravi Sukhadia.";
$arrNotification["title"] = "TECHIBUCKET";
$arrNotification["sound"] = "default";
$arrNotification["type"] = 1;

$fcm = new FCM();
$result = $fcm->send_notification($regId, $arrNotification,"Android");
?>

Step 4)

Send Push Notification to IOS Using PHP. You just need to change “Android” to “IOS” in your index.php file. like below…


FOR ANDROID

$result=$fcm->send_notification($regId,$arrNotification,"Android");

FOR IPHONE

$result=$fcm->send_notification($regId, $arrNotification,"IOS");

Step 5)

Now run your index.php file and you can get the notification to your devices.

How to verify Australian ABN/ACN is active or not in PHP

ABN-Lookup

This tutorial is check for ABN/ACN number is active or not. generally, ABN/ACN use for Australian companies registered in Australia. so this tutorial will give to functionality that is ABN/ACN is active in Australia or deactivate. you can check via PHP curl API.

Step 1)

Register web services agreement form here. click here for register. after the register, they will verify you and then provide the guid number.

Step 2)

Now make the below function to check the status of ABN/ACN number where you need to pass the guid number which is provided by the ABN lookup after your register. click here for download the function which is use for this. implement all functions and set guid number in the function.

Note: for this, you have to curl active in your server. if not then first on the curl function in your server and then implement the above code and check.

Step 3)

Now pass your ABN/ACN details to the above variable which can check if it’s active then give status true otherwise it will give false.

Implement PHP mailer with smtp authentication

smtpmailer

This tutorial for implement the PHP mailer with smtp authentication. you can set smtp authentication mail to your website using this. so simply follow the setup and you can get working smtp authentication mail.

Step 1)

Download the php mailer library from here. click here for download

Step 2)

Make a function for send a mail as below.

function phpMailerMailNew($FromDisplay, $FromEmail, $ReplyTo, $ToName, $ToEmail, $myCCList, $myBCCList, $Subject, $HTMLMsg, $TxtMsg, $AttFile, $AttFileName, $AttFileType){
       if(isset($ToEmail) && validateEmail($ToEmail))
       {
        require_once('phpMailer/PHPMailerAutoload.php');

        $mail = new PHPMailer();
        # -- prepare mail body
        $message = strip_tags($HTMLMsg);
        $message = str_replace("\t","",$message);
        $message = str_replace("&nbsp;","",$message);
        # --      
        if(!isset($FromDisplay) || strlen(trim($FromDisplay))==0)
            $FromDisplay = $FromEmail;  
        if(!isset($ToName) || strlen(trim($ToName))==0)
            $ToName = $ToEmail;
        # -- add ccs
        if(isset($myCCList) && strlen(trim($myCCList)) > 0)
        {
            $tempCCs = explode(",", $myCCList);            
            for($c = 0;$c<count($tempCCs);$c++)
                if(validateEmail($tempCCs[$c]))
                    $mail->AddCC($tempCCs[$c]);
        }       
        # ---
        # -- add bccs
        if(isset($myBCCList) && strlen(trim($myBCCList)) > 0)
        {
            $tempBCCs = explode(",", $myBCCList);
            for($c = 0;$c<count($tempBCCs);$c++)
                if(validateEmail($tempBCCs[$c]))
                    $mail->AddBCC($tempBCCs[$c]);
        }       
        # --
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        $mail->IsSMTP(); // set mailer to use SMTP
        $mail->SMTPDebug = 0;
        
        $mail->Timeout  =   60;

        $mail->Port = 465;
        $mail->SMTPSecure = 'ssl'; 

        $mail->Host = "";  // mail.example.com
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = ""; // SMTP username like example@domain
        $mail->Password = ""; // SMTP password-

             
        $mail->FromName = $FromDisplay;
        $mail->From = $FromEmail;
        $mail->AddAddress($ToEmail,$ToName);

        # -- if a reply to is set, add it.

        if(validateEmail($ReplyTo))
            $mail->AddReplyTo($ReplyTo);

        if(strlen(trim($HTMLMsg)) > 0)
        {

            $mail->IsHTML(true); // set email format to HTML

            $mail->Body = $HTMLMsg;
            if(strlen(trim($TxtMsg)) >0)
            {
                $mail->AltBody = $TxtMsg;
            }
            else
            {
                $message = strip_tags($HTMLMsg);
                $message = str_replace("\t","",$message);
                $message = str_replace("&nbsp;","",$message);
                $mail->AltBody =    $message;
            }
        }
        else
        {
            $mail->IsHTML(false);
            $mail->Body = $TxtMsg;
        }
        $mail->Subject = $Subject;

        if(strlen(trim($AttFile))> 0 && file_exists($AttFile))
        {

            $mail -> AddAttachment($AttFile,$AttFileName);

        }
        $mail->Send();
    }

}

Step 3)

Now use above function for sent the smtp authentication mail via smtp.

Import data from excel file to php database

excelimport

You have a excel file and if you want to import that excel file to your database then fetch the cell value using this tutorials. you can directly import to your MySQL, Ms SQL and various database using this library and tutorials. just download library and integrate below code there.

Step 1)

Download the excel read library from here. click here for download

Step 2)

Make a form for upload your excel file as below.

<html>
<body>
    <form method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>
                    Select File:
                </td>
                <td>
                    <input type="file" name="file" id="file">
                </td>
            </tr>
            <tr>
                <td colspan="2" align="left">
                    <input type="submit" name="submit" value="Submit">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Step 3)

Now make code for read the excel file cell and import to database as below.

<?php
include('PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');

if(isset($_POST["submit"]))
{
	$inputFileName = $_FILES["file"]["tmp_name"];

	try {
		$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$objPHPExcel = $objReader->load($inputFileName);
	} catch (Exception $e) {
		die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . 
		$e->getMessage());
	}

	$sheet = $objPHPExcel->getSheet(0);
	$highestRow = $sheet->getHighestRow();
	$highestColumn = $sheet->getHighestColumn();

	$newArr = array();
	for($row = 1; $row <= $highestRow; $row++) { 
		$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false);

		array_push($newArr, $rowData);
	}

    echo "<pre>";
    print_r($newArr);
	
    echo "Record Update Successfully...";
}
?>

Step 4)

Now upload your excel to form and submit the excel it will return you all cell value which you will insert to your database.