php Recaptcha Ajax - 完整的工作演示

Recaptcha Ajax - 完整的工作演示

new_gist_file.php
============================= the index file =============================

<?php include 'config.php'  ; ?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>

<body>

<form action="" method="POST" id="leadform">
    <input type="text" id="name" name="name" value="" placeholder="Name">
    <input type="text" id="email" name="email" value="" placeholder="Email">
    <div><textarea type="text" id="message" name="message" placeholder="Message"></textarea></div>
    <div class="g-recaptcha" data-sitekey="6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT"></div>
    <input type="submit" name="submit" value="SUBMIT">
</form>

<div id="result" style="display:none;"></div>

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

<script>
$(document).ready(function() {
	$("#leadform").submit(function(event) {
	    /* Stop form from submitting normally */
	    event.preventDefault();
	    /* Get from elements values */
	    var name = $('#name').val();
	    var email = $('#email').val();
	    var message = $('#message').val();
	    var g_recaptcha_response  = $('#g-recaptcha-response').val();

	    /* Clear result div*/
	    $("#result").html('');
	    
        ajaxRequest = $.ajax({
            url: "process_ajax.php",
            type: "post",
            data: {name:name,email:email,message:message, g_recaptcha_response: g_recaptcha_response }
        });

        /*  request cab be abort by ajaxRequest.abort() */

        ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          console.log("SUCCESS") ;
          $('#result').show() ;
          $("#result").html(response);
        });

        /* On failure of request this function will be called  */
        ajaxRequest.fail(function (response){
        // show error
        console.log("ERROR") ;
        $("#result").html('Error found trying to submit the form: ' + response );
        });

	});

}); // end document ready
</script>

</body>

</html>



=================  the process ajax file process_ajax.php =====================

<?php
// require 'Recaptcha.php';
// if ( ! class_exists('Recaptcha') ) die('Class Recaptcha not found') ; 

require_once dirname(__FILE__) . '/Recaptcha.php';

$name  = $_POST['name'] ;
$email  = $_POST['email'] ;
$message  = $_POST['message'] ;
$recaptcha = $_POST['g_recaptcha_response'];

$recobj = new Recaptcha();
$response = $recobj->verifyResponse($recaptcha);

if( isset($response['success']) && $response['success'] != true )  {
	echo "An Error Occured and Error code is :".$response['error-codes'];
}
else {
	echo 'Correct Recaptcha<br>
	 Name: ' . $name . '<br>' .
	'Email: ' . $email . '<br>'  .
	'Message: ' . $message . '<br>'  .
	'recaptcha value: ' . $recaptcha ;
}

?>

===================  the Recaptcha class: Recaptcha.php =====================

<?php
class Recaptcha {
	
	public function __construct(){
		// retrieve config array values
        $this->config = require('config.php');
    }

	public function verifyResponse($recaptcha){
		
		$remoteIp = $this->getIPAddress();

		// Discard empty solution submissions and return
		if (empty($recaptcha)) {
			return array(
				'success'     => false,
				'error-codes' => 'Recaptcha is required',
			);
		}

		// get a JSON response
		$jsonresponse = $this->getJSONResponse(
			array(
				'secret'   => $this->config['secret-key'],
				'remoteip' => $remoteIp,
				'response' => $recaptcha,
			)
		);

		// decoded JSON reCAPTCHA server response
		$responses = json_decode($jsonresponse, true);

		// Set array keys for success/failure
		if ( isset($responses['success']) and $responses['success'] == true ) {
			$status = true;
		} else {
			$status = false;
			$error = (isset($responses['error-codes'])) ? $responses['error-codes']
				: 'invalid-input-response';
		}

		// return the status and if error-codes (if any)
		return array(
			'success'     => $status,
			'error-codes' => (isset($error)) ? $error : null,
		);
	}

	private function getJSONResponse($data){
		// we use http_build_query to generate a URL encoded query string , ex:
		// https://www.google.com/recaptcha/api/siteverify?secret=".$this->secret. "&response=".$response;
		// remoteip is optional, but its passed if needed by our app requirements
		$url = 'https://www.google.com/recaptcha/api/siteverify?'.http_build_query($data);
		$response = file_get_contents($url);

		return $response;
	}

	private function getIPAddress(){
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} 
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  	{
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} 
		else  {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
		return $ip;
	}

}

?>


===================== the config file: config.php  =========================

<?php
// these will work on Localhost
return [
	'client-key' => '6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT',
	'secret-key' => '6LeT7h8UAAAAAOoLSh0t6tPgv8D3hCMUeJN5FxRY'
];

?>







php Recaptcha Ajax - 完整的工作演示

Recaptcha Ajax - 完整的工作演示

new_gist_file.php
============================= the index file =============================

<?php include 'config.php'  ; ?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>

<body>

<form action="" method="POST" id="leadform">
    <input type="text" id="name" name="name" value="" placeholder="Name">
    <input type="text" id="email" name="email" value="" placeholder="Email">
    <div><textarea type="text" id="message" name="message" placeholder="Message"></textarea></div>
    <div class="g-recaptcha" data-sitekey="6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT"></div>
    <input type="submit" name="submit" value="SUBMIT">
</form>

<div id="result" style="display:none;"></div>

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

<script>
$(document).ready(function() {
	$("#leadform").submit(function(event) {
	    /* Stop form from submitting normally */
	    event.preventDefault();
	    /* Get from elements values */
	    var name = $('#name').val();
	    var email = $('#email').val();
	    var message = $('#message').val();
	    var g_recaptcha_response  = $('#g-recaptcha-response').val();

	    /* Clear result div*/
	    $("#result").html('');
	    
        ajaxRequest = $.ajax({
            url: "process_ajax.php",
            type: "post",
            data: {name:name,email:email,message:message, g_recaptcha_response: g_recaptcha_response }
        });

        /*  request cab be abort by ajaxRequest.abort() */

        ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          console.log("SUCCESS") ;
          $('#result').show() ;
          $("#result").html(response);
        });

        /* On failure of request this function will be called  */
        ajaxRequest.fail(function (response){
        // show error
        console.log("ERROR") ;
        $("#result").html('Error found trying to submit the form: ' + response );
        });

	});

}); // end document ready
</script>

</body>

</html>



=================  the process ajax file process_ajax.php =====================

<?php
// require 'Recaptcha.php';
// if ( ! class_exists('Recaptcha') ) die('Class Recaptcha not found') ; 

require_once dirname(__FILE__) . '/Recaptcha.php';

$name  = $_POST['name'] ;
$email  = $_POST['email'] ;
$message  = $_POST['message'] ;
$recaptcha = $_POST['g_recaptcha_response'];

$recobj = new Recaptcha();
$response = $recobj->verifyResponse($recaptcha);

if( isset($response['success']) && $response['success'] != true )  {
	echo "An Error Occured and Error code is :".$response['error-codes'];
}
else {
	echo 'Correct Recaptcha<br>
	 Name: ' . $name . '<br>' .
	'Email: ' . $email . '<br>'  .
	'Message: ' . $message . '<br>'  .
	'recaptcha value: ' . $recaptcha ;
}

?>

===================  the Recaptcha class: Recaptcha.php =====================

<?php
class Recaptcha {
	
	public function __construct(){
		// retrieve config array values
        $this->config = require('config.php');
    }

	public function verifyResponse($recaptcha){
		
		$remoteIp = $this->getIPAddress();

		// Discard empty solution submissions and return
		if (empty($recaptcha)) {
			return array(
				'success'     => false,
				'error-codes' => 'Recaptcha is required',
			);
		}

		// get a JSON response
		$jsonresponse = $this->getJSONResponse(
			array(
				'secret'   => $this->config['secret-key'],
				'remoteip' => $remoteIp,
				'response' => $recaptcha,
			)
		);

		// decoded JSON reCAPTCHA server response
		$responses = json_decode($jsonresponse, true);

		// Set array keys for success/failure
		if ( isset($responses['success']) and $responses['success'] == true ) {
			$status = true;
		} else {
			$status = false;
			$error = (isset($responses['error-codes'])) ? $responses['error-codes']
				: 'invalid-input-response';
		}

		// return the status and if error-codes (if any)
		return array(
			'success'     => $status,
			'error-codes' => (isset($error)) ? $error : null,
		);
	}

	private function getJSONResponse($data){
		// we use http_build_query to generate a URL encoded query string , ex:
		// https://www.google.com/recaptcha/api/siteverify?secret=".$this->secret. "&response=".$response;
		// remoteip is optional, but its passed if needed by our app requirements
		$url = 'https://www.google.com/recaptcha/api/siteverify?'.http_build_query($data);
		$response = file_get_contents($url);

		return $response;
	}

	private function getIPAddress(){
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} 
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  	{
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} 
		else  {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
		return $ip;
	}

}

?>


===================== the config file: config.php  =========================

<?php
// these will work on Localhost
return [
	'client-key' => '6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT',
	'secret-key' => '6LeT7h8UAAAAAOoLSh0t6tPgv8D3hCMUeJN5FxRY'
];

?>







php 这将在登录WooCommerce时将客户的引用URL重定向。

这将在登录WooCommerce时将客户的引用URL重定向。

wc-custom-login-redirect.php
function wc_custom_login_redirect() {
	// This will redirect the customer the referring url on login to WooCommerce..
	$location = $_SERVER['HTTP_REFERER']; 
	wp_safe_redirect($location); 
	exit(); 
}
add_filter('woocommerce_login_redirect', 'wc_custom_login_redirect');

php 这将在登录WooCommerce时将客户的引用URL重定向。

这将在登录WooCommerce时将客户的引用URL重定向。

wc-custom-login-redirect.php
function wc_custom_login_redirect() {
	// This will redirect the customer the referring url on login to WooCommerce..
	$location = $_SERVER['HTTP_REFERER']; 
	wp_safe_redirect($location); 
	exit(); 
}
add_filter('woocommerce_login_redirect', 'wc_custom_login_redirect');

php ACF链接插件使用示例(在转发器中)

ACF链接插件使用示例(在转发器中)

acf-link-plugin.php
<!--start button item repeater-->
				<?php 

				// loop through rows (sub repeater)
				while( have_rows('tib_buttons') ): the_row(); ?>

                <?php $tib_buttons = get_sub_field('tib_button'); ?>
				
					<?php if( $tib_buttons['url'] ): ?>	
					<a href="<?php echo $tib_buttons['url'] ?>" class="btn btn-warning hidden-xs ripple-effect"><?php echo $tib_buttons['title'] ?></a>
				<?php endif; ?>

				<!--end looping through sub repeater-->
			<?php endwhile; ?>

php 从单选按钮字段获取Acf Conditional H1

从单选按钮字段获取Acf Conditional H1

acf-conditional-h1.php
<<?php if (get_sub_field('tib_is_h1') == 'Yes'): ?>h1 <?php else: ?>h2 <?php endif; ?> class="page-title"><?php the_sub_field('tib_title'); ?></<?php if (get_sub_field('tib_is_h1') == 'Yes'): ?>h1<?php else: ?>h2<?php endif; ?>>

php 获取假日日期功能

获取假日日期功能

get_holiday.php
<?php

  function observed_date($holiday){
    $day = date("w", strtotime($holiday));
    if($day == 6) {
        $observed_date = $holiday -1;
    } elseif ($day == 0) {
        $observed_date = $holiday +1;
    } else {
        $observed_date = $holiday;
    }
    return $observed_date;
  }

  function get_holiday($holiday_name) {

    $currentYear = date('Y');

    switch ($holiday_name) {
        // New Years Day
        case "new_year":
            $holiday = observed_date(date('l, F d, Y', strtotime("first day of january $currentYear")));
            break;
        // Martin Luther King, Jr. Day
        case "mlk_day":
            $holiday = date('l, F d, Y', strtotime("january $currentYear third monday"));
            break;
        // President's Day
        case "presidents_day":
            $holiday = date('l, F d, Y', strtotime("february $currentYear third monday"));
            break;
        // Memorial Day
        case "memorial_day":
            $holiday = (new DateTime("Last monday of May"))->format("l, F d, Y");
            break;
        // Independence Day
        case "independence_day":
            $holiday = observed_date(date('l, F d, Y', strtotime("july 4 $currentYear")));
            break;
        // Labor Day
        case "labor_day":
            $holiday = date('l, F d, Y', strtotime("september $currentYear first monday"));
            break;
        // Columbus Day
        case "columbus_day":
            $holiday = date('l, F d, Y', strtotime("october $currentYear second monday"));
            break;
        // Veteran's Day
        case "veterans_day":
            $holiday = observed_date(date('l, F d, Y', strtotime("november 11 $currentYear")));
            break;
        // Thanksgiving Day
        case "thanksgiving_day":
            $holiday = date('l, F d, Y', strtotime("november $currentYear fourth thursday"));
            break;
        // Christmas Day
        case "christmas_day":
        $holiday = observed_date(date('l, F d, Y', strtotime("december 25 $currentYear")));
            break;

        default:
            $holiday = "";
            break;
    }
    return $holiday;

  }
  
  echo get_holiday('independence_day');
?>

php Esconde o editor de texto de uma。 Para isso adicioneessafunçãoemfunctions.php e substituia“page-model.php”pelo nome desuapágina

Esconde o editor de texto de uma。 Para isso adicioneessafunçãoemfunctions.php e substituia“page-model.php”pelo nome desuapágina。

hide-editor-page.php

/**
 * Hide editor on specific pages.
 *
 */

function remove_editor_init() {
if ( is_admin() ) {
    $post_id = 0;
    if(isset($_GET['post'])) $post_id = $_GET['post'];
    $template_file = get_post_meta($post_id, '_wp_page_template', TRUE);
    if ($template_file == 'page-model.php') {
        remove_post_type_support('page', 'editor');
    }
}
}
add_action( 'init', 'remove_editor_init' );

php WordPress - 上传时清除特殊字符的文件名

WordPress - 上传时清除特殊字符的文件名

surbma-clean-file-names.php
<?php

add_filter( 'sanitize_file_name', 'surbma_clean_file_names', 10 );
function surbma_clean_file_names ( $filename ) {
    $tmp = explode( '.', $filename );
    $ext = end( $tmp );
    $file = substr( $filename, 0, -( strlen( $ext )+1 ) );
    $file = str_replace(' ', '-', $file);
    $file = str_replace('_', '-', $file);
    $file = str_replace('.', '-', $file);
    $file = preg_replace('/-+/', '-', $file);
    $file = remove_accents( $file );
    $file = preg_replace('/[^A-Za-z0-9\-]/', '', $file);
    $file = strtolower( $file );
    return $file . '.' . $ext;
}

php PODS按自定义日期排序

PODS按自定义日期排序

new_gist_file.php
$params = array( 
  'orderby' => 'custom_date.meta_value ASC',
  'limit' => 15
);