Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

September 1, 2023

Integrating Google reCAPTCHA v3 in HTML Form with PHP

 

What is Google reCAPTCHA v3?

Google reCAPTCHA is a free service that helps protect websites from spam and abuse. reCAPTCHA v3 is the latest version of this service, and it's designed to work silently in the background without requiring any user interaction, such as solving puzzles or clicking checkboxes. It assigns a score to each user and lets you take action based on that score.

HTML form security with reCAPTCHA v3 | Protecting forms from spam with reCAPTCHA v3 | How to add reCAPTCHA v3 to PHP forms | Website form security best practices | Google reCAPTCHA setup and usage guide | PHP form validation with reCAPTCHA v3

Step 1: Sign Up for reCAPTCHA

Before you can integrate reCAPTCHA v3 into your HTML form, you need to sign up for an API key. Here's how:

  1. Go to the reCAPTCHA website.
  2. Click on the "Admin Console" button.
  3. Sign in to your Google account or create one if you don't have one already.
  4. Once signed in, click the "+" button to create a new site.

Step 2: Add reCAPTCHA to Your HTML Form

Now that you have your API keys, you can add reCAPTCHA to your HTML form:

<!DOCTYPE html>
<html>
<head>
    <!-- Add the reCAPTCHA script -->
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <form action="process.php" method="POST">
        <!-- Your other form fields here -->

        <!-- Add the reCAPTCHA widget -->
        <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

Replace "YOUR_SITE_KEY_HERE" with the actual site key you obtained in Step 1.

Step 3: Verify reCAPTCHA Score with PHP

Now, let's process the form submission on the server-side using PHP and verify the reCAPTCHA score. Create a PHP file (e.g., process.php) and add the following code:

<?php
$recaptcha_secret = 'YOUR_SECRET_KEY_HERE';
$recaptcha_response = $_POST['g-recaptcha-response'];

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$recaptcha_secret&response=$recaptcha_response");
$responseKeys = json_decode($response, true);

if (intval($responseKeys["score"]) >= 0.5) {
    // reCAPTCHA score is good, process the form data
    // Your form processing code here
    echo "Form submitted successfully!";
} else {
    // reCAPTCHA score is low, consider this submission suspicious
    echo "Please complete the reCAPTCHA to submit the form.";
}
?>

Make sure to replace "YOUR_SECRET_KEY_HERE" with your actual reCAPTCHA secret key.

Step 4: Test Your Form

Now, you have successfully integrated reCAPTCHA v3 into your HTML form with PHP. Test your form to ensure everything is working as expected. When users submit the form, reCAPTCHA will silently evaluate their interaction with your website and provide a score. You can adjust the threshold (0.5 in this example) to determine what level of risk you're willing to accept.


March 27, 2023

What's new in the latest version 8.0.12 of PHP

 

What's new in the latest version 8.0.12 of PHP

Introduction

The latest stable release of PHP is version 8.0.12, which was released on September 30, 2021. Below are new features and improvements in PHP 8.0 include:

  • Named arguments: This feature lets developers pass function arguments by name, rather than relying on their position.
  • Union types: This allows developers to declare a parameter or return type as accepting multiple types, for example int|string.
  • Constructor property promotion: This feature simplifies the syntax for defining class properties and initializing them in the constructor.
  • Match expression: Similar to the switch statement, the match expression provides more powerful and concise syntax for matching a value against multiple possible conditions.
  • Attributes: This feature allows developers to add metadata to classes, properties, methods, and functions, providing a more structured way to annotate code.
  • Nullsafe operator: This operator provides a shorthand way to check for null values in a chain of property or method calls.
  • JIT compiler: PHP 8.0 introduces a just-in-time (JIT) compiler, which can improve performance by compiling frequently executed code to native machine code.
  • Improved error handling: PHP 8.0 introduces a new "throw" expression that allows exceptions to be thrown without needing to wrap them in a separate statement. This feature makes error handling more concise and easier to read.
  • Improved type system: PHP 8.0 includes improvements to the type system, including stricter type checking for certain operations, better support for mixed types, and more consistent handling of type errors.
  • New capabilities and classes: PHP 8.0 presents a few new capabilities and classes, including the str_contains() capability for checking whether a string contains a substring, the fdiv() capability for performing drifting point division, and the Stringable point of interaction for objects that can be switched over completely to a string.
These are only a couple of the new highlights and upgrades in PHP 8.0. Engineers are urged to survey the authority discharge notes for a full rundown of changes and new highlights.

Enjoy!

September 23, 2018

How to draw different type of pyramid in PHP using short code?



To draw a simple pyramid:
Example:

<pre>
<?php
 $no = $i = 5;
 while ($i--)
    echo str_repeat(' ', $i).str_repeat('*', $no - $i)."\n";
?>
</pre>

Output:

    *
   **
  ***
 ****
*****

Note: If you want display in middle like below

    *
   * *
  * * *
 * * * *
* * * * *

- You need just give space after start in while loop in ablove example like:
Example:
<pre>
<?php
 $no = $i = 5;
 while ($i--)
    echo str_repeat(' ', $i).str_repeat('* ', $no - $i)."\n";
?>
</pre>


- The next example for display below pyramid:
Example:

<?php
$num=1;
for($i=1;$i<5;$i++){
   for($j=1;$j<=$i;$j++){
       echo $num;
       $num=$num+1;
   }
   echo "<br />";
}
?>

Output:
1
23
456
78910

September 20, 2017

How to display image from an undisclosed folder using PHP?



You can easly display image using another PHP file.

You can pass image name after .php file.

Instead of linking directly to the image in your web page, the <img> tag links to the proxy script, and passes the name of the image as a query string.

Example:

<img src="proxy.php?img=profile.jpg" alt="This is drawn from a hidden folder" ... />

Enjoy!

November 18, 2016

PHP Toolkit retrieve Item Fulfillment record attached to a Sales Order



As the subject says, I would like to be able to retrieve the Item Fulfillment records attached to a Sales Order record, if any, using the PHP Toolkit.

The code below will retrieve the Sales Order and Cash Sale records based on the value of a custom field, but I cannot get it to include an Item Fulfillment record. Any help will be greatly appreciated.


$ts = new TransactionSearch();
$tsb = new TransactionSearchBasic();
$csf = new SearchStringCustomField();
$csf->internalId = '69';
$csf->searchValue = '100000137';
$csf->operator = 'is';
$scfl = new SearchCustomFieldList();
$scfl->customField = array($csf);
$tsb->customFieldList = $scfl;
$ts->basic = $tsb;
$request = new SearchRequest();
$request->searchRecord = $ts;
$searchResponse = $service->search($request);

Enjoy!

August 1, 2016

PHP - Call to undefined method PDF_HTML::FPDF()..



Before one day I realize this error and I find a simple solution, See below:

On included file 'html2pdf.php' you should just rename one function name as per below:

Approx line no: 52

1. Line no: 49
Replace function PDF_HTML with function __construct

2. Line no 52
Replace $this->FPDF with parent::__construct

Enjoy!

July 14, 2016

New PHP 7 Alpha for version released this week PHP 7.1.0



One good news for  PHP Fans,

The latest Alpha for PHP 7 has been released this week. PHP 7.1.0 Alpha 3 is available immediately.

Also this week, has your company decided it's time to "do community"? Get some tips on how to build a community presence.

We take a look at the brilliant tiny computer Raspberry Pi, and how to use it to power projects with PHP.

Plus Adam Culp and Cal Evans gave a question and answer session, from a conference organiser's perspective, on how conference talks are selected.

And finally, PHP South Africa has been announced, taking place over three days in September, in Johannesburg. Early Bird tickets are currently on sale.

Click Here for read more.

Enjoy!

January 21, 2016

jQuery data Tables how to set record per page?




- If you want to set 10 records per page on jQuery data Tables then please see below example:

$('#tableID').dataTable( {

  "pageLength": 10

} );

In above example define no of records you want per page on pageLength parameter,

Enjoy!

January 16, 2016

jQuery select chosen validation not working with PHP




- I find best solution for that and its very simple for select chosen validation,

- The jQuery validation ignore default hidden fields,

- Just pass one parameter as per below example like: ignore: hidden:not,

Example!

$(document).ready(function(){
    $('#se;ectid').chosen();
    $('#formid').validate({ ignore: ":hidden:not(select)" });
    $('#validateIt').click(function(){
        if($('#formid').valid())
            alert('This is Valid');
        else
            alert('This is Invalid');
    });
});

Enjoy!

January 7, 2016

PHP - How to send email using Gmail SMTP?



Following example help you to send email using Gmail SMTP with PHP,

You can download PHP mailer function from here GitHub.


require 'PHPMailerAutoload.php';

$from = '<yourname@gmail.com>';
$to = '<sendto@yahoo.com>';
$subject = 'Hello!';
$body = "Hello,\n\nHow are you?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => 'johndoe@gmail.com',
        'password' => 'passwordxxx'
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}

Enjoy!

January 3, 2016

PHP - How to get YouTube video image from YouTube URL?




- When I face this problem to display YouTube video image display from URL/link, then I find one solution as below:

- For each YouTube have unique video ID so you can get 5 type of images using that ID,

- Here I explain with example for all type of YouTube images how to display?

1. For video default image but not high resolution of image:

   http://img.youtube.com/vi/<YouTube-Video-Unique-ID>/default.jpg


2. For the high resolution of image use below link:

   http://img.youtube.com/vi/<YouTube-Video-Unique-ID>/hqdefault.jpg


3. For the medium quality of the thumbnail image use below example:

   http://img.youtube.com/vi/<YouTube-Video-Unique-ID>/mqdefault.jpg


4. For the standard version of the image use a link similar to this:

   http://img.youtube.com/vi/<YouTube-Video-Unique-ID>/sddefault.jpg


5. For the maximum resolution of the video thumbnail image use a url like this:

   http://img.youtube.com/vi/<YouTube-Video-Unique-ID>/maxresdefault.jpg

- And one more thing for above all URLs you can also used https instead of http.

Enjoy!

December 23, 2015

PHP - When submit form string replace space to Â



Today I working on a PHP project and I face one spacing problem like when I submit form with CKeditor then all space &nbsp; replace with  undefined character,

So I find a best solution for that and share it here.

Fist please include following meta line in <head> tag:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

And second thing is when you submit CKeditor field then used 'utf8_decode' function, see in below example:

$message=utf8_decode($_REQUEST['message']);

Here 'message' is your field name.

Enjoy!

December 15, 2015

PHP - SQL select query return array with used ID field as a key


                                               



In SQL select query while loop you can used ID fields as array key, it's simple. Here is example for that:

<?php
$selRes=mysql_query("SELECT id, name FROM TableName order by id DESC";
if(mysql_affected_rows()>0)
{
$data=array();
while($rowSale=mysql_fetch_array($selRes))
{
    $data[$row[0]] = $rowSale[1];
}
}

//Output
print_r($data);
array([1]=>'name1',[2]=>'name2',[3]=>'name3');

?>

Enjoy!

October 23, 2015

PHP - Dynamic IP block script.



Please enter the following script in header file of your site which call in all pages for e.g. header.php file,

And also define IP addressed which you want to redirect to another page/link,

Example

<?php $blacklist = array("111.222.333", "444.555.666", "777.888.999");

if(in_array($_SERVER['REMOTE_ADDR'], $blacklist)) {

header("Location: http://sitename.com/404");

exit();
} ?>

Enjoy!

September 11, 2015

PHP send email and when click on any link of that email than how to track.



Following is example for track email viewed OR not?

<?php
$user_id = $_GET['user_id'];

If ( $user_id )
{
    $FileName = $id.".txt";
    $ourFileHandle = fopen($FileName, 'w') or die("can't open file");
    fclose($ourFileHandle);
}
else
{
    $to = "jhon@gmail.com"; //to address

    $subject ="Read Receipt Email";

    $message = "Testing whether the read receipt script works or not";
    $message = "<img src=\"http://www.example.com/email.php?user_id=".$to." width=\"0\" height=\"0\" >";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: kelly@ymail.com' . "\r\n";

    if (mail($to, $subject, $message, $headers) )
    {
        echo "Mail sent successfully";
    }
    else
    {
        echo "failed to send mail";
    }
}

?>

Enjoy!

August 16, 2015

php how to get all files name from folder?


<?php
$insArr=array();
if ($handle = opendir('here is folder path name')) {
while (false !== ($file = readdir($handle)))
{
echo $file;
echo '<br>';
}
closedir($handle);}
?>

Its display name of all file/images from specific folder/directory,

Just change the folder/directory name what ever you want, and if you want any help then comment here!

Enjoy!

July 28, 2015

How to open a browse any file dialog when click on link using javascript?

- Is there any way to open browse file window open when I click on any <a href> link? Please help me for that I have issue in a site and I want some help!

July 18, 2015

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker?

Use the dateFormat function for that:

Example:
$(function(){
$("#to").datepicker({ dateFormat: 'yy-mm-dd' });
$("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
minValue.setDate(minValue.getDate()+1);
$("#to").datepicker( "option", "minDate", minValue );
})
});


Demo : http://jsfiddle.net/gaby/WArtA/

Enjoy!

PHP- full calendar how to remove extra slots when week view?


Please do following change in .js file where calendar function call like: calendar.js file:

$('#calendar').fullCalendar({ //re-initialize the calendar
header: h,
        slotMinutes: 30,
});


Enjoy!

July 12, 2015

jQuery ui datepicker set default calendar is a last month

Yes, it's possible using faultDate function:

<?php
$('#selectdate').datepicker({
    defaultDate: '-1m' //Here you can define how many month(s) you want less from current month.
});
?>

Enjoy!

The Future of Technology: Emerging Trends to Watch in 2025

Introduction As we navigate through 2025, the technological landscape continues to evolve at an unprecedented pace. Innovations that once se...