Powered By Blogger
Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, August 27, 2019

curse word OR bad words validation in php




https://github.com/expalmer/php-bad-words

Example 1:


require_once 'PhpBadWords.php';
use \Expalmer\PhpBadWords\PhpBadWords as BadWords;


        $myDictionary = array(
                                array("ass","among"),
                                array("porn","among"),
                                array("faggot","among"),
                                array("sex","among"),
                                array("nigger","among"),
                                array("fuck","among"),
                                array("cunt","among"),
                                array("dick","among"),
                                array("gay","among"),
                                "anal",
                                "porn",
                                "faggot",
                                "sex",
                                "nigger",
                                "fuck",
                                "cunt",
                                "dick",
                                "gay",
                                "butt"
                              );

        $badwords = new BadWords();
        $badwords->setDictionaryFromArray( $myDictionary )
               ->setText( $comment );

        $check_curse =  $badwords->check();
        // output: TRUE.
        // Because the dictionary has a word `ass` with `among` rule.

        $check_curse =  $badwords->checkAlone();
        // output: FALSE.
        // Because now it verified by word `ass` alone, and it does not exist alone.
        // ( It ignores dictionary word rules )

        $check_curse = $badwords->checkAmong();



PhpBadWords.php :


<?php
namespace Expalmer\PhpBadWords;

class PhpBadWords {

  private $dictionary = array(
    "anal",
    "ass",
    array("asshole", "among"),
    "butt"
  );

  private $text;
  private $textOriginal;
  private $dictionaryWords = array();

  public function __construct() {
    $this->fillDictionaryWords();
  }

  /**
   * Fill the variable with only the words of the dictionary, without the original word rules
   *
   * @return void
   */
  private function fillDictionaryWords() {
    foreach($this->dictionary as $w):
      $this->dictionaryWords[] = is_array($w) ? $w[0] : $w;
    endforeach;
  }

  /**
   * Set the bad words list from an array
   *
   * @param  array
   * @return this
   * @throws \Exception
   */
  public function setDictionaryFromArray( $array ) {
    if( is_array($array) ) {
      $this->dictionary = $array;
      $this->fillDictionaryWords();
      return $this;
    }
    throw new \Exception('Invalid dictionary, try to send an array or a file path!');
  }

  /**
   * Set the bad words list from a file
   *
   * @param  string
   * @return this
   * @throws \Exception
   */
  public function setDictionaryFromFile( $path ) {
    if ( file_exists( $path ) ) {
      $dict = include $path;
      if( is_array($dict) ) {
        $this->dictionary = $dict;
        $this->fillDictionaryWords();
        return $this;
      }
      throw new \Exception('The file content must be an array!');
    }
    throw new \Exception('File not found in ' . $path );
  }

  /**
   * Set the text to be checked
   *
   * @param string
   * @return this
   */
  public function setText( $text ) {
    $this->textOriginal = $text;
    $this->text = preg_replace("/([^\w ]*)/iu", "", $text);
    return $this;
  }

  /**
   * Checks for bad words in the text but verifies each dictionary word rule,
   * like alone ou among each word in the text.
   *
   * @return boolean
   */
  public function check() {
    foreach( $this->dictionary as $word ):
      $rule = "alone";
      if( is_array($word) ) {
        $rule = isset($word[1]) ? $word[1] : $rule;
        $word = $word[0];
      }
      $word = preg_replace("/([^\w ]*)/iu", "", $word);
      if( "among" === $rule ) {
        if( preg_match("/(" . $word . ")/iu", $this->text ) ) return true;
      } else {
        if( preg_match("/(\b)+(" . $word . ")+(\b)/iu", $this->text ) ) return true;
      }
    endforeach;
    return false;
  }

  /**
   * Checks if the text has a bad word among each word
   *
   * @return boolean
   */
  public function checkAmong() {
    return !!preg_match("/(" . join("|", $this->dictionaryWords ) . ")/iu", $this->text );
  }

  /**
   * Checks if the text has a bad word exactly how it appears in the dictionary
   *
   * @return boolean
   */
  public function checkAlone() {
    return !!preg_match("/(\b)+(" . join("|", $this->dictionaryWords ) . ")+(\b)/iu", $this->text );
  }

}

Wednesday, October 10, 2018

Custom pagination create OR only show before and after three page in pagination links in PHP

function smartsimple_pagination($pages = '', $current_page, $range = 2)
{
    $showitems = ($range * 2)+1;
    $paginationHTML = '';

 
    if (empty($current_page)) {
        $current_page = 1;
    }

   /* if ($pages == '') {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if (!$pages) {
            $pages = 1;
        }
    }*/

    if (1 != $pages) {
        $paginationHTML = "<div class='pagination'>Page:&nbsp;";
        if ($current_page > 2 && $current_page > $range+1 && $showitems < $pages) {
            $paginationHTML .= "<a class='btn btn-sm btn-default' href='".get_pagenum_link(1)."'><i class='fa fa-angle-double-left'></i></a>";
        }
        if ($current_page > 1 && $showitems < $pages) {
            $paginationHTML .= "<a class='btn btn-sm btn-default' href='".get_pagenum_link($current_page - 1)."'><i class='fa fa-angle-left'></i></a>";
        }

        for ($i=1; $i <= $pages; $i++) {
            if (1 != $pages &&(!($i >= $current_page+$range+1 || $i <= $current_page-$range-1) || $pages <= $showitems)) {
                $paginationHTML .= ($current_page == $i)? "<span class='btn btn-warning btn-sm'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='btn btn-default btn-sm' >".$i."</a>";
            }
        }

        if ($current_page < $pages && $showitems < $pages) {
            $paginationHTML .= "<a class='btn btn-default btn-sm' href='".get_pagenum_link($current_page + 1)."'><i class='fa fa-angle-right'></i></a>";
        }
        if ($current_page < $pages-1 &&  $current_page+$range-1 < $pages && $showitems < $pages) {
            $paginationHTML .= "<a class='btn btn-default btn-sm' href='".get_pagenum_link($pages)."'><i class='fa fa-angle-double-right'></i></a>";
        }
        global $wp_query;
        $paginationHTML .= "&nbsp;of&nbsp;";
        $paginationHTML .= $pages;
        $paginationHTML .= "&nbsp;total pages</div>";
    }

    return $paginationHTML;
}




WordPress


//begin pagination
function gic_pagination($pages = '', $range = 2)
{
    $showitems = ($range * 2)+1;

    global $paged;
    if (empty($paged)) {
        $paged = 1;
    }

    if ($pages == '') {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if (!$pages) {
            $pages = 1;
        }
    }

    if (1 != $pages) {
        echo "<div class='pagination'>Page:&nbsp;";
        if ($paged > 2 && $paged > $range+1 && $showitems < $pages) {
            echo "<a class='btn btn-sm btn-default' href='".get_pagenum_link(1)."'><i class='fa fa-angle-double-left'></i></a>";
        }
        if ($paged > 1 && $showitems < $pages) {
            echo "<a class='btn btn-sm btn-default' href='".get_pagenum_link($paged - 1)."'><i class='fa fa-angle-left'></i></a>";
        }

        for ($i=1; $i <= $pages; $i++) {
            if (1 != $pages &&(!($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems)) {
                echo ($paged == $i)? "<span class='btn btn-warning btn-sm'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='btn btn-default btn-sm' >".$i."</a>";
            }
        }

        if ($paged < $pages && $showitems < $pages) {
            echo "<a class='btn btn-default btn-sm' href='".get_pagenum_link($paged + 1)."'><i class='fa fa-angle-right'></i></a>";
        }
        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) {
            echo "<a class='btn btn-default btn-sm' href='".get_pagenum_link($pages)."'><i class='fa fa-angle-double-right'></i></a>";
        }
        global $wp_query;
        echo "&nbsp;of&nbsp;";
        echo $wp_query->max_num_pages;
        echo "&nbsp;total pages</div>";
    }
}

//end pagination


Friday, September 16, 2016

How can I measure the speed of code written in PHP?

How can I measure the speed of code written in PHP?
$startTime= microtime(true);
/** Write here you code to check **/
/** Write here you code to check **/
$endTime= microtime(true);
echo ‘Time Taken to execute the code:’.$endTime-$startTime

change the name of the variable dynamically. or diff between $$message and $message

2. Explain the difference between $message and $$message?
• $message is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.
Example:
$var1 = ‘Variable 1’
$$var1= ‘variable2’
This can be interpreted as $ Variable 1=‘variable2’;
For me to print value of both variables, I will write
$var1 $($var1)
• $message is a variable and $$message is a variable of another variable.
Example
$Message = "YOU";
$you= "Me";
echo $message //Output:- you
echo $$message //output :-Me
$$message allows the developer to change the name of the variable dynamically.

Thursday, June 30, 2016

set cron use php





file_put_contents('crontab.txt','* * * * * php /var/www/html/autopostwpp/twitter/twitter-api-php-master/index.php'.PHP_EOL);
echo exec('crontab crontab.txt');
$output = exec('crontab -l');
echo $output;
$myFile = "crontab.txt";
//unlink($myFile);


ref:
http://w3schools.invisionzone.com/index.php?showtopic=45340





98
down voteaccepted
crontab command usage
usage:  crontab [-u user] file
        crontab [-u user] [ -e | -l | -r ]
                (default operation is replace, per 1003.2)
        -e      (edit user's crontab)
        -l      (list user's crontab)
        -r      (delete user's crontab)
        -i      (prompt before deleting user's crontab)
So,
$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.'* * * * * NEW_CRON'.PHP_EOL);
echo exec('crontab /tmp/crontab.txt');
The above can be used for both create and edit/append provided the user has the adequate file write permission.
To delete jobs:
echo exec('crontab -r');
Also, take note that apache is running as a particular user and that's usually not root, which means the cron jobs can only be changed for the apache user unless given crontab -u privilege to the apache user.

Friday, June 17, 2016

add value in header and send in curl

http://www.omaroid.com/php-get-and-set-custom-http-headers/



Sender: 

<?php

$post_url = 'innotech.innoppldesigns.com/useraddapi.php';
$post_string = array(
'names' => 'gnana',
'emails'=> 'gnana@gmail.com',
'password'=> 'gnana',
'role' => 'drupal',
'tech' => 'drupal'
);
$request = curl_init($post_url); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
curl_setopt($request,CURLOPT_HTTPHEADER,array('AUTHORIZATION: innotechhrm'));
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
$post_response = curl_exec($request); // execute curl post and store results in $post_response
curl_close ($request); // close curl object 

echo '<pre>';
print_r($post_response);

?>



Receiver : 

if php is installed as an Apache module: 
apache_request_headers()["Authorization"];
else, go to .htaccess file and add:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
You can then access request headers using any of these:
$_SERVER["HTTP_AUTHORIZATION"]; // using super global

Monday, June 13, 2016

Set super global variable in the server

Please add below code within <VirtualHost> </VirtualHost> tag.
File Path = /etc/apache2/sites-enabled/000-default.conf

# enabled b_rst security encryption key 
SetEnv B_RST_SEC_KEY BRST123456 
SetEnv B_RST_DB b_rst 
SetEnv B_RST_DB_USER_NAME root 
SetEnv B_RST_DB_PASS root 

<Directory /var/www/html> 
Options Indexes FollowSymLinks 
AllowOverride All 
require env B_RST_SEC_KEY 
require env B_RST_DB 
require env B_RST_DB_USER_NAME 
require env B_RST_DB_PASS 
Require all granted 
</Directory>

Monday, April 18, 2016

Scripts — Full Featured PHP Browser Detection


<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Browser Detection Script - digitalaps.com</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">

<?php

function get_browser_info()
{
$http_useragent = $_SERVER['HTTP_USER_AGENT'];
$browser_name = 'Unknown';
$version= "";
if(preg_match('/MSIE/i',$http_useragent) && !preg_match('/Opera/i',$http_useragent))
{
$browser_name = 'Internet Explorer Browser';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$http_useragent))
{
$browser_name = 'Mozilla Firefox Browser';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$http_useragent))
{
$browser_name = 'Google Chrome Browser';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$http_useragent))
{
$browser_name = 'Apple Safari Browser';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$http_useragent))
{
$browser_name = 'Opera Browser';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$http_useragent))
{
$browser_name = 'Netscape Browser';
$ub = "Netscape";
}
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $http_useragent, $matches)) {
// we have no matching number just continue
}
$i = count($matches['browser']);
if ($i != 1) {
if (strripos($http_useragent,"Version") < strripos($http_useragent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
if ($version==null || $version=="") {$version="?";}
return array(
'userAgent' => $http_useragent,
'name' => $browser_name,
'version' => $version
);
}
$ua=get_browser_info();

?>

<div class="alert alert-success">
  <p><strong>Congratulations!</strong></p>
  <p>Your browser information has been detected.<br /> Please check below details about your browser.</p>
  <p><strong>Browser Name: </strong><? echo $ua['name']; ?></p>
  <p><strong>Browser Version: </strong><? echo $ua['version']; ?></p>
</div>

 
</div>

</body>
</html>