Sunday, 22 October 2023

insert Youtube video in webpage with auto play function

 <!DOCTYPE html>

<html>

    <head>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">

    </head>

  <body>

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->

<div id="player"></div>


<script>

  // 2. This code loads the IFrame Player API code asynchronously.

  var tag = document.createElement('script');


  tag.src = "https://www.youtube.com/iframe_api";

  var firstScriptTag = document.getElementsByTagName('script')[0];

  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


  // 3. This function creates an <iframe> (and YouTube player)

  //    after the API code downloads.

  var player;

  function onYouTubeIframeAPIReady() {

    player = new YT.Player('player', {

      width: '300px',

      height: '300px',

      videoId: 'x5CrknRXWZ0',

      playerVars: { 'autoplay': 1, 'playsinline': 1 },

      events: {

        'onReady': onPlayerReady

      }

    });

  }


  // 4. The API will call this function when the video player is ready.

  function onPlayerReady(event) {

     event.target.mute();

    event.target.playVideo();

  }

</script>

  </body>

</html>

Friday, 20 October 2023

Delete Data From a MySQL Table Using MySQLi in php

 The DELETE statement is used to delete records from a table:

DELETE FROM table_name WHERE some_column = some_value

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully";
else {
  echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

Wednesday, 18 October 2023

email address validator – Email MX DNS Record Check

Validate email instantly with our cutting-edge free online email verification tool: simply enter the email address in the box below, and our advanced email validator will provide you with real-time email deliverability results!

 

<form name="myForm" method="post" action="#">

<center><h1>Please Enter Email Address:</h1></center><br/><br />

<input type="email" style="width: 100%;height:50px;" name="email" id="email" placeholder="admin@adquash.com"><br /><br />

 <center><input type="submit" value="Check" id="dsubmit" class="btn btn-blue" name ="submit"><br/><br/> </center>

</form>

<?php

if (isset($_POST['submit'])) {

$email = $_POST['email'];

/*

* Getting Domain part from user input Email-Address

*/

$domain = substr(strrchr($email, "@"), 1);

/*

* This Function is used for fetching the MX data records to a corresponding

- Email domain

*/


function mxrecordValidate($email, $domain) {


$arr = dns_get_record($domain, DNS_MX);

if ($arr[0]['host'] == $domain && !empty($arr[0]['target'])) {

return $arr[0]['target'];

}

}


echo"<table id ='tid' >";

echo"<th>";

echo"Result";

echo"</th>";

echo"<tr>";

echo"<td>";


if (mxrecordValidate($email, $domain)) {

echo("<br>This MX records exists. <br><b>'$email' is Valid Email Address</b><br>.");

if (checkdnsrr($domain, "A")) {

    echo "$domain has an A record";

} else {

    echo "$domain does not have an A record";

}

$data = dns_get_record($domain, DNS_MX);

foreach ($data as $key1) {

echo "<br>Host:- " . $key1['host'] ;

echo "<br>Class:- " . $key1['class'] ;

echo "<br>TTL:- " . $key1['ttl'] ;

echo "<br>Type:- " . $key1['type'] ;

echo "<br>PRI:- " . $key1['pri'] ;

echo "<br>Target:- " . $key1['target'] ;

echo "<br>Target-IP:- " . gethostbyname($key1['target']) ;

}

echo"</td>";

echo"</tr>";

} else {

echo("<br>No MX record exists. '$email' is Invalid Email Address.");

}

echo"</td>";

echo"</tr>";

echo"</table>";

}

?>

Thursday, 12 October 2023

Redirect to a Random Link with This HTML Code

Copy and paste given code . You can replace link as per your requirement.


<script type="text/javascript">


var urls = new Array();

urls[0] = "https://sakhihosting.in";

urls[1] = "https://sakhihosting.in/domain-registration/index.php";

urls[2] = "https://sakhihosting.in/web-hosting/index.php";

urls[4] = "https://sakhihosting.in/virtualserverlinux-hosting.php";

urls[5] = "https://sakhihosting.in/dedicated-servers.php";

urls[6] = "https://sakhihosting.in/dedicated-servers-windows.php";

urls[7] = "https://sakhihosting.in/web-hosting/windows-hosting.php";

urls[8] = "https://sakhihosting.in/optimized-wordpress-hosting.php";

urls[9] = "https://sakhihosting.in/reseller-hosting.php";

urls[10] = "https://sakhihosting.in/support/contact-us.php";


var random = Math.floor(Math.random()*urls.length);


window.location = urls[random];


</script>

Sunday, 3 September 2023

PHP Email with Attachment by php mail

 <?php 

 

// Recipient 

$to = 'receiver email address'; 

 

// Sender 

$from = 'sender email address'; 

$fromName = 'sender name'; 

 

// Email subject 

$subject = 'PHP Email with Attachment by php mail';  

 

// Attachment file 

$file = "common-600.png"; // attachment file name

 

// Email body content 

$htmlContent = ' 

    <h3>PHP Email with Attachment by php mail</h3> 

    <p>This email is sent from the PHP script with attachment.</p> 

'; 

 

// Header for sender info 

$headers = "From: $fromName"." <".$from.">"; 

 

// Boundary  

$semi_rand = md5(time());  

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  

 

// Headers for attachment  

$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

 

// Multipart boundary  

$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 

"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";  

 

// Preparing attachment 

if(!empty($file) > 0){ 

    if(is_file($file)){ 

        $message .= "--{$mime_boundary}\n"; 

        $fp =    @fopen($file,"rb"); 

        $data =  @fread($fp,filesize($file)); 

 

        @fclose($fp); 

        $data = chunk_split(base64_encode($data)); 

        $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .  

        "Content-Description: ".basename($file)."\n" . 

        "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .  

        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 

    } 

$message .= "--{$mime_boundary}--"; 

$returnpath = "-f" . $from; 

 

// Send email 

$mail = @mail($to, $subject, $message, $headers, $returnpath);  

 

// Email sending status 

echo $mail?"<h1>Email Sent Successfully!</h1>":"<h1>Email sending failed.</h1>"; 

 

?>

send image as content in php mail

 // (A) MAIL SETTINGS

$mailTo = "receiver_email_address@domain_name";

$mailSubject = "इच्छापूर्ति के लिए मन्त्र सिद्ध माला ";


// (B) MAIL MESSAGE

// HOST THE IMAGE ON YOUR OWN SERVER!

// ALSO REMEMBER TO PROVIDE THE DIRECT LINK JUST-IN-CASE

$img = "https://email.aksharmty.in/common-600.png";

$mailBody = "<a href='https://aksharmty.in/mantra-siddh-mala.php'><img src='$img'></a><br>";

$mailBody .= "अधिक जानकारी के लिए वेबसाइट पर जाएं : https://aksharmty.in/mantra-siddh-mala.php<br>";


// (C) HEADER - HTML MAIL

$from = 'sender@domain_name'; 

$fromName = 'sender name'; 

$mailHead = implode("\r\n", [

  "MIME-Version: 1.0",

  "Content-type: text/html; charset=utf-8",

  "From: $fromName"." <".$from.">"

]);


// (D) SEND

echo mail($mailTo, $mailSubject, $mailBody, $mailHead)

  ? "OK" : "ERROR" ;

?>  

Sunday, 6 August 2023

Domain WHOIS Lookup script in php

 For Domain WHOIS Lookup script in php

create two page first index.php other domain-whois-functions.php.

Code for index.php

<------ start --->

<?php

include('domain-whois-functions.php');

$result = '';

$domain= '';

$message = '';

if(isset($_POST['domain'])){ 

$domain = $_POST['domain'];

$domain = trim($domain);

if(substr(strtolower($domain), 0, 7) == "http://") $domain = substr($domain, 7);

if(substr(strtolower($domain), 0, 8) == "https://") $domain = substr($domain, 8);

if(substr(strtolower($domain), 0, 4) == "www.") $domain = substr($domain, 4);

if(validateDomain($domain)) {

$result = lookUpDomain($domain);

} else {

$message = "Invalid Input!";

}

}

?>

<HEAD>

<title>Domain Whois Lookup Script in php</title>

<meta name="Description" content="Domain Whois Lookup Script in php">

<meta name="keywords" content="dns record,nameserver,domain whois,whois">

</HEAD>

<body>

<h2> Search Domain WHOIS Lookup Details</h2>

<label class="text-info">

<?php if($message) { ?>

<span class="text-danger"><strong><?php echo $message; ?></strong></span>

<?php } ?>

</label>

<form name="form" class="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<input type="text" name="domain" style="width:100%; height:50px;" placehoder="Enter your Domain name" value="<?php echo $domain ?>"><br>

<center><br><br>

        <input type="submit" class="btn btn-blue" value="Submit">

    </center></form> 

<?php

if($result) {

echo "<pre>\n" . $result . "\n</pre>\n";

}

?>

</body>

</html>

<---- index.php code end --->

Now create domain-whois-functions.php

<--- start code for domain-whois-functions.php -->

<?php

$whoIsServers = array(

"ac" => "whois.nic.ac",

"ae" => "whois.nic.ae", 

"aero"=>"whois.aero",

"af" => "whois.nic.af", 

"ag" => "whois.nic.ag", 

"ai" => "whois.ai", 

"al" => "whois.ripe.net", 

"am" => "whois.amnic.net",

"arpa" => "whois.iana.org",

"as" => "whois.nic.as",

"asia" => "whois.nic.asia",

"at" => "whois.nic.at", 

"au" => "whois.aunic.net",

"ax" => "whois.ax", 

"az" => "whois.ripe.net", 

"be" => "whois.dns.be",

"bg" => "whois.register.bg",

"bi" => "whois.nic.bi",

"biz" => "whois.biz",

"bj" => "whois.nic.bj",

"bn" => "whois.bn",

"bo" => "whois.nic.bo", 

"br" => "whois.registro.br",

"bt" => "whois.netnames.net",

"by" => "whois.cctld.by", 

"bz" => "whois.belizenic.bz", 

"ca" => "whois.cira.ca", 

"cat" => "whois.cat", 

"cc" => "whois.nic.cc",

"cd" => "whois.nic.cd",

"ch" => "whois.nic.ch", 

"ci" => "whois.nic.ci", 

"ck" => "whois.nic.ck",

"cl" => "whois.nic.cl",

"cn" => "whois.cnnic.net.cn",

"co" => "whois.nic.co",

"com" => "whois.verisign-grs.com",

"coop" => "whois.nic.coop",

"cx" => "whois.nic.cx", 

"cz" => "whois.nic.cz", 

"de" => "whois.denic.de",

"dk" => "whois.dk-hostmaster.dk", 

"dm" => "whois.nic.dm",

"dz" => "whois.nic.dz", 

"ec" => "whois.nic.ec", 

"edu" => "whois.educause.edu",

"ee" => "whois.eenet.ee", 

"eg" => "whois.ripe.net",

"es" => "whois.nic.es", 

"eu" => "whois.eu",

"fi" => "whois.ficora.fi", 

"fo" => "whois.nic.fo", 

"fr" => "whois.nic.fr", 

"gd" => "whois.nic.gd",

"gg" => "whois.gg", 

"gi" => "whois2.afilias-grs.net",

"gl" => "whois.nic.gl", 

"gov" => "whois.nic.gov",

"gs" => "whois.nic.gs",

"gy" => "whois.registry.gy",

"hk" => "whois.hkirc.hk", 

"hn" => "whois.nic.hn", 

"hr" => "whois.dns.hr", 

"ht" => "whois.nic.ht",

"hu" => "whois.nic.hu",

"ie" => "whois.domainregistry.ie", 

"il" => "whois.isoc.org.il", 

"im" => "whois.nic.im", 

"in" => "whois.registry.in", 

"info" => "whois.afilias.net",

"int" => "whois.iana.org",

"io" => "whois.nic.io", 

"iq" => "whois.cmc.iq", 

"ir" => "whois.nic.ir", 

"is" => "whois.isnic.is", 

"it" => "whois.nic.it", 

"je" => "whois.je", 

"jobs" => "jobswhois.verisign-grs.com",

"jp" => "whois.jprs.jp", 

"ke" => "whois.kenic.or.ke", 

"kg" => "www.domain.kg", 

"ki" => "whois.nic.ki", 

"kr" => "whois.kr", 

"kz" => "whois.nic.kz",

"la" => "whois.nic.la",

"li" => "whois.nic.li", 

"lt" => "whois.domreg.lt", 

"lu" => "whois.dns.lu", 

"lv" => "whois.nic.lv", 

"ly" => "whois.nic.ly", 

"ma" => "whois.iam.net.ma", 

"md" => "whois.nic.md",

"me" => "whois.nic.me", 

"mg" => "whois.nic.mg",

"mil" => "whois.nic.mil",

"ml" => "whois.dot.ml",

"mn" => "whois.nic.mn",

"mo" => "whois.monic.mo",

"mobi" => "whois.dotmobiregistry.net",

"mp" => "whois.nic.mp",

"ms" => "whois.nic.ms",

"mu" => "whois.nic.mu", 

"museum" => "whois.museum",

"mx" => "whois.mx", 

"my" => "whois.domainregistry.my",

"na" => "whois.na-nic.com.na",

"name" => "whois.nic.name",

"nc" => "whois.nc",

"net" => "whois.verisign-grs.net",

"nf" => "whois.nic.nf", 

"ng" => "whois.nic.net.ng", 

"nl" => "whois.domain-registry.nl", 

"no" => "whois.norid.no", 

"nu" => "whois.nic.nu", 

"nz" => "whois.srs.net.nz", 

"om" => "whois.registry.om", 

"org" => "whois.pir.org",

"pe" => "kero.yachay.pe", 

"pf" => "whois.registry.pf", 

"pl" => "whois.dns.pl", 

"pm" => "whois.nic.pm", 

"post" => "whois.dotpostregistry.net",

"pr" => "whois.nic.pr", 

"pro" => "whois.dotproregistry.net",

"pt" => "whois.dns.pt", 

"pw" => "whois.nic.pw", 

"qa" => "whois.registry.qa", 

"re" => "whois.nic.re", 

"ro" => "whois.rotld.ro", 

"rs" => "whois.rnids.rs",

"ru" => "whois.tcinet.ru",

"sa" => "whois.nic.net.sa", 

"sb" => "whois.nic.net.sb", 

"sc" => "whois2.afilias-grs.net", 

"se" => "whois.iis.se", 

"sg" => "whois.sgnic.sg", 

"sh" => "whois.nic.sh", 

"si" => "whois.arnes.si", 

"sk" => "whois.sk-nic.sk", 

"sm" => "whois.nic.sm", 

"sn" => "whois.nic.sn", 

"so" => "whois.nic.so", 

"st" => "whois.nic.st", 

"su" => "whois.tcinet.ru",

"sx" => "whois.sx", 

"sy" => "whois.tld.sy", 

"tc" => "whois.meridiantld.net", 

"tel" => "whois.nic.tel",

"tf" => "whois.nic.tf", 

"th" => "whois.thnic.co.th", 

"tj" => "whois.nic.tj", 

"tk" => "whois.dot.tk", 

"tl" => "whois.nic.tl", 

"tm" => "whois.nic.tm", 

"tn" => "whois.ati.tn", 

"to" => "whois.tonic.to", 

"tp" => "whois.nic.tl", 

"tr" => "whois.nic.tr", 

"travel" => "whois.nic.travel",

"tv" => "tvwhois.verisign-grs.com", 

"tw" => "whois.twnic.net.tw", 

"tz" => "whois.tznic.or.tz", 

"ua" => "whois.ua", 

"ug" => "whois.co.ug",

"uk" => "whois.nic.uk",

"us" => "whois.nic.us", 

"uy" => "whois.nic.org.uy", 

"uz" => "whois.cctld.uz", 

"vc" => "whois2.afilias-grs.net", 

"ve" => "whois.nic.ve", 

"vg" => "whois.adamsnames.tc", 

"wf" => "whois.nic.wf", 

"ws" => "whois.website.ws", 

"xxx" => "whois.nic.xxx",

"yt" => "whois.nic.yt", 

"yu" => "whois.ripe.net",

"tech" => "whois.godaddy.com"

);

function lookUpDomain($domain){

global $whoIsServers;

$domainParts = explode(".", $domain);

$tld = strtolower(array_pop($domainParts));

$whoIsServer = $whoIsServers[$tld];

if(!$whoIsServer) {

return "Error: No appropriate Whois server found for $domain domain!";

}

$whoIsResult = getWhoisServerDetails($whoIsServer, $domain);

if(!$whoIsResult) {

return "Error: No results retrieved from $whoIsServer server for $domain domain!";

} else {

while(strpos($whoIsResult, "Whois Server:") !== FALSE){

preg_match("/Whois Server: (.*)/", $whoIsResult, $matches);

$secondary = $matches[1];

if($secondary) {

$whoIsResult = getWhoisServerDetails($secondary, $domain);

$whoIsServer = $secondary;

}

}

}

return "$domain domain lookup results from $whoIsServer server:\n\n" . $whoIsResult;

}

function validateDomain($domain) {

if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,8})$/i", $domain)) {

return false;

}

return $domain;

}

function getWhoisServerDetails($whoIsServer, $domain) {

$port = 43;

$timeout = 10;

$whoIsInfo = @fsockopen($whoIsServer, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);

fputs($whoIsInfo, $domain . "\r\n");

$output = "";

while(!feof($whoIsInfo)){

$output .= fgets($whoIsInfo);

}

fclose($whoIsInfo);

$whosIsResults = "";

if((strpos(strtolower($output), "error") === FALSE) && (strpos(strtolower($output), "not allocated") === FALSE)) {

$whoIsRecords = explode("\n", $output);

foreach($whoIsRecords as $whoIsRecord) {

$whoIsRecord = trim($whoIsRecord);

if(($whoIsRecord != '') && ($whoIsRecord{0} != '#') && ($whoIsRecord{0} != '%')) {

$whosIsResults .= $whoIsRecord."\n";

}

}

}

return $whosIsResults;

}

?>

<--- end code for domain-whois-functions.php -->


Wednesday, 10 May 2023

Generic htaccess redirect www to non-www

 redirect www to non-www using htaccess 


RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]


Redirect non-www to www (both: http + https)

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Saturday, 15 April 2023

Image Slider

 <!DOCTYPE html>

<html lang="en">

<head>

  <title>Bootstrap Example</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>

<body>


<div class="container">

  <h2>Carousel Example</h2>  

  <div id="myCarousel" class="carousel slide" data-ride="carousel">

    <!-- Indicators -->

    <ol class="carousel-indicators">

      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>

      <li data-target="#myCarousel" data-slide-to="1"></li>

      <li data-target="#myCarousel" data-slide-to="2"></li>

    </ol>


    <!-- Wrapper for slides -->

    <div class="carousel-inner">

      <div class="item active">

        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitKL481el5wleb7jASdL6ixIPR89pqPhzKOhCItTc7gV42tPOwfh-Ks7UE6e3HCnQj77JUOaK43QuyD3EqPLNfj3oc6G3gvAaVbMFwlY7GGR7sF-Zvy7OA9eDpFEvHHT01_HRO8WL4DCNC7IbSSsSIk4syH0ah4qSbRe4xCzLXBBiZIAkA8iJhTewF/s320/slide0.png" alt="Los Angeles" style="width:100%;">

      </div>


      <div class="item">

        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhapGQFqW7zdUKM9u5JNXXuI491HW0-miN7k87MludiJD3PbZBZGcw9Jq3NaSlNn1kbWsEyfBAOiyH9wJsIznoR_9wEzOhpV5Z8XwAc9LzufOLOFortcKDHqWzqX566_75nwIka2iiYMY-7xemyr6Gvc55BVuy6-RPEJ30JoaDOZ2WHE9xMMJyQ9_uX/s320/slide1.png" alt="Chicago" style="width:100%;">

      </div>

    

      <div class="item">

        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgExGIdRz-TeV_nobiuZtN032gKA_0p2-vXN8aHuV6oEDDYk0w8E9Zauc1jqI62kBpgAFA-b6jEKv_Pr7U8WEZdh9K2joUQpiDL_2nAt_9U6_0yob2QGJV6LbJL2ubrBBmX_bUgWfmywdXb0YGTxCnQyu2kssyjyaZKFGz_GU4-gJty99NOFFflM-3S/s320/slide2.png" alt="New york" style="width:100%;">

      </div>

    </div>


    <!-- Left and right controls -->

    <a class="left carousel-control" href="#myCarousel" data-slide="prev">

      <span class="glyphicon glyphicon-chevron-left"></span>

      <span class="sr-only">Previous</span>

    </a>

    <a class="right carousel-control" href="#myCarousel" data-slide="next">

      <span class="glyphicon glyphicon-chevron-right"></span>

      <span class="sr-only">Next</span>

    </a>

  </div>

</div>


</body>

</html>





Saturday, 8 April 2023

Copy file from external url using curl

 Copy file from external url using curl

if you want copy from https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvQdRe8XOy4RKAcBgzs2Cgggrj2PVg9A2hQTtcu34hQRi_7eQwwUixXYJXoFBoMPRp5B2x7ld98q4fnibANy9dtWZJyxg-Jj-btX-wzETe1SXBwhkXo6Kbr5lmzr8DFuUI20c-CeS7owUtDeLVL-__jBWK_Hrd4ct8aIByT51gSFffLW2LTUO41y3S/s1600/logo.gif

replace with https:// your  external url 


You want save this as sakhihosting.gif replace with  save as giving file name 

<?php

$ch = curl_init('https:// your  external url '); 

 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));

 $return = curl_exec($ch); 

  curl_close($ch); 

 print_r($return);

// $data = json_decode(file_get_contents($ch), true);

$file = fopen(" save as giving file name ","w");

echo fwrite($file,$return);

fclose($file);

?>


Wednesday, 22 March 2023

simple calculator in php

An HTML form is shown in the following example code to display the calculator program:

<form method="post" action="">

        <div class="row row-cols-1 row-cols-sm-2 row-cols-md-2 row-cols-lg-2 row-cols-xl-2 justify-content-center">

                <div class="col text-center mb-3 mb-md-5">

                        <label for="Operand1" class="form-label fs-3">First Number</label>

                        <input id="Operand1" name="Operand1" type="number" step="any" class="form-control form-control-custom" value="<?php echo isset($Operand1)?$Operand1:''; ?>">

                </div>

                <div class="col text-center mb-3 mb-md-4">

                        <label for="Operand2" class="form-label fs-3">Second Number</label>

                        <input id="Operand2" name="Operand2" type="number" step="any" class="form-control form-control-custom" value="<?php echo isset($Operand2)?$Operand2:''; ?>">

                </div>

        </div>

        <div class="row justify-content-center mb-3">

                <div class="col-auto">

                        <input class="btn btn-success fs-2" type="submit" name="Calculate" value="+">

                        <input class="btn btn-success fs-2" type="submit" name="Calculate" value="-">

                        <input class="btn btn-success fs-2" type="submit" name="Calculate" value="x">

                        <input class="btn btn-success fs-2" type="submit" name="Calculate" value="/">

                </div>

        </div>

</form>


<?php if(isset($Result) && is_numeric($Result)){?><!-- Display Result -->

<div class="row justify-content-center">

        <div class="col text-center">

                <label for="Result" class="fs-4">Result</label>

                <input id="Result" name="Result" type="number" step="any" class="form-control form-control-custom" value="<?php echo $Result; ?>">

        </div> 

</div>

<?php } if(isset($Error)){?><!-- Display Error Messages -->

<div class="row justify-content-center">

        <div class="col">

                <div class="alert alert-danger shadow-sm" role="alert">Error: <?php echo $Error; ?></div>

        </div>

</div>

<?php } ?>


Once the form is submitted, the PHP $_POST super global variable receives all input values. After that, it validates the input and displays it if an error occurs. Then, comparison and arithmetic operators within the conditional statements are used to calculate the expected value.

PHP Code:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $Operand1=$_POST['Operand1'];
    $Operand2=$_POST['Operand2'];
    $Operator=$_POST['Calculate'];

    /*Validation begins from here.*/
    if($Operand1 == '' || $Operand2 == ''){
        $Error = "The input values are required.";
    }
    elseif (filter_var($Operand1, FILTER_VALIDATE_FLOAT) === false || filter_var($Operand2, FILTER_VALIDATE_FLOAT) === false) {
        $Error = "The input value must be a number only.";
    }
    elseif($Operator=="/" && ($Operand1 == 0 || $Operand2 == 0)){
        $Error = "Cannot divide by zero.";
    }
    else{
        /*Calculation begins from here.*/
        if($Operator=="+")
            $Result=$Operand1+$Operand2;
        else if($Operator=="-")
            $Result=$Operand1-$Operand2;
        else if($Operator=="x")
            $Result=$Operand1*$Operand2;
        else if($Operator=="/")
            $Result=$Operand1/$Operand2;
    }
} ?>