Snippets Collections
<script>
jQuery(document).ready(function($) {
  
  $.urlParam = function (name) {
    var results = new RegExp('[?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('id')); //registration
console.log($.urlParam('email')); //bobo@example.com
    var email = decodeURI($.urlParam('email'));
var replaced = email.replace("%40", "@"); 
  var type = decodeURI($.urlParam('type'));

  var replaced2 = type.replace("+", " ");  

  $("#wpforms-2228-field_0").val($.urlParam('id'));
    $("#wpforms-1770-field_4").val(replaced);
    $("#wpforms-1770-field_6").val("Suite a votre demande de devis  nous vous prions de trouver ci joint notre proposition de tarif pour   '" + replaced2 +  "'.... ");


  })
</script>
if (is_page( 'tablefirrstpagenolimit' ) ):
$limit = 20; 
else : $limit = 8;
endif;
// Setup
$post_objects = get_field('acf_post_object_field');
$slug_array = array();

// Loop
if($post_objects) {
  foreach($post_objects as $post_object):
  
  	// Get slug and place into the array
  	$slug_array[] = $post_object->post_name;
  
  endforeach;
}

// Echo
<?= implode(' ', $slug_array); ?>
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    function index() {
        $d=['name' => "Ayo", 'email' => "ayo.com", 'address' => 'Nigeria'];
        return view('users', ['data' => $d]);
    }
}
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', 'UsersController@index');

Route::view('home', 'home');
Route::view('profile', 'profile');
if ($user->wasRecentlyCreated) {
    // user just created in the database; it didn't exist before.
} else {
    // user already existed and was pulled from database.
}
 array_multisort(array_column($array, 'datetime'), SORT_DESC, $array);
// THE HTML/PHP

// Categories Nav START
<? $terms = get_terms( array(
    'taxonomy' => 'category-name', // <-- update this
    'orderby' => 'ID',
  )); 
  if ( $terms && !is_wp_error( $terms ) ){ ?>
   <ul class="CHANGEME-categories-nav">
      <? foreach( $terms as $term ) { ?>
        <li id="cat-<?php echo $term->term_id; ?>">
           <a href="#" class="<?= $term->slug; ?> ajax" data-term-number="<?= $term->term_id; ?>" title="<?= $term->name;?>"><?= $term->name; ?></a>
        </li>
      <? } ?>
   </ul>
<? } ?>
// Categories Nav END
                                       
// Results Container START
<div id="CHANGEME-results-container" class="CHANGEME-filter-result">
   <? // post query
     $query = new WP_Query( array(
        'post_type' => 'post-name', // <-- update this
        'posts_per_page' => -1,
      ) ); 
   if( $query->have_posts() ): while( $query->have_posts()): $query->the_post(); ?>
    
      // POST TEMPLATE HERE
    
   <? endwhile; endif; wp_reset_query(); ?>
</div>                      
// Results Container END

// The onpage JS for the page template
<script>
(function($) {
        'use strict';
        function cat_ajax_get(catID) {
            jQuery.ajax({
                type: 'POST',
                url: raindrop_localize.ajaxurl,
                data: {"action": "filter", cat: catID },
                success: function(response) {
                    jQuery("#CHANGEME-results-container").html(response);
                    return false;
                }
            });
        }
        $( ".CHANGEME-categories-nav a.ajax" ).click(function(e) {
            e.preventDefault();
            $("a.ajax").removeClass("current");
            $(this).addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
            var catnumber = $(this).attr('data-term-number');
            cat_ajax_get(catnumber);
        });

    })(jQuery);
</script>
                                       
// Callback function for functions.php or some other functions specific php file like theme.php
// Aside from the inital add actions and a few other things, the actual query and post template should be the same as what is on the page.
                                       
add_action( 'wp_ajax_nopriv_filter', 'CHANGEME_cat_posts' );
add_action( 'wp_ajax_filter', 'CHANGEME_cat_posts' );
                                       
function CHANGEME_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
    $args = array (
	  'tax_query' => array(
		    array(
		      'taxonomy' => 'category-name', // <-- update this
		      'field' => 'term_id',
		      'terms' => array( $cat_id )
		    )
		  ),
	    'post_type' => 'post-name', // <-- update this
	    'posts_per_page' => -1,
	  );
	global $post;
    $posts = get_posts( $args );
    ob_start ();
    foreach ( $posts as $post ) { 
	    setup_postdata($post); ?>

	    // POST TEMPLATE HERE

   <?php } wp_reset_postdata();
   $response = ob_get_contents();
   ob_end_clean();
   echo $response;
   die(1);
}
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );
function filter_dropdown_option_html( $html, $args ) {
    $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );
    $show_option_none_html = '<option value="">' . esc_html( $show_option_none_text ) . '</option>';

    $html = str_replace($show_option_none_html, '', $html);

    return $html;
}
<script>
    $('#ProjectSubType{{$class->id}}').appendTo("body");
</script>
postgres-# ( terminal commands)
- list all databases : \l
- list of all tables : \d
- list only the tables : \dt
- list all fields in a table : \d person (name of the table)
- import from external file : \i c:/postgrescourse/person.sql

- datatypes info:
bigserial : increment int in sequence
date : year,month,day



- create database : create database test;
- drop database : drop database test;
- drop table : drop table person;
- connect to a database ( two forms ) :  
\c test (or) -h localhost -p 5432 -U postgres test
- create table sintax : create table table_name ( column name + data type + constraints if any ) 

- create table : 
create table person ( 
	id int,
	first_name varchar(50),
  	last_name varchar(50),
    gender varchar(6),
    date_of_birth date
    );
- create table w/constraints ( need to satisfied rules): 
create table person (
 	id bigserial not null primary key,
 	first_name varchar(50) not null,
 	last_name varchar(50) not null,
    gender varchar(6) not null, 
    date_of_birth date not null
	);

- create table : 
insert into person ( first_name, last_name, gender, date_of_birth) values ('Anne','Smith','Female',date '1988-01-09');

- Using OFFSET and LIMIT : select * from person OFFSET 5 LIMIT 5;
- Using OFFSET and FETCH : select * from person OFFSET 5 FETCH 5 ROW ONLY;
- Using BETWEEN : select * from person where date_of_birth BETWEEN DATE '2000-01-01' and '2015-01-01';
- Diferences between LIKE and ILIKE : ILIKE is case insensitive. 

- Using Group By : select country_of_birth, count(*) from person group by country_of_birth; ( will count how many people are from that country )
- Using Having with Group By : select country_of_birth, count(*) from person having count(*) > 5 group by country_of_birth; ( must have above 5 to show )





function load_animate_css() {
  // Load Boostrap CSS
  wp_enqueue_style( 'animate-css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css' );

  // Load Css
  wp_enqueue_style( 'style', get_stylesheet_uri() );

}
add_action( 'wp_enqueue_scripts', 'load_animate_css' );
/**
     * Query Public schema and return any req'd settings.
     */
    public static function getSettingsFromPublic()
    {
        if (Schema::connection('public')->hasTable('pubs')) {
            DB::table('public.pubs_settings')->select('ps.id, LOWER(ps.name) AS name, ps.description, ps.value, ps.resolve_include_path, ps.set_as_null, psc.name AS category, cst.name AS type, cse.name AS element')->join('components_settings_types_elements cste', 'cste.id', 'ps.components_settings_types_elements_id')->where('psc.name', 'css')->orderBy('ps.name', 'ASC')->get();
            $statement = "SELECT ps.id, LOWER(ps.name) AS name, ps.description, ps.value, ps.resolve_include_path, ps.set_as_null, psc.name AS category, cst.name AS type, cse.name AS element FROM pubs_settings ps JOIN pubs_settings_categories psc ON (psc.id = ps.pubs_settings_categories_id) JOIN components_settings_types_elements cste ON (cste.id = ps.components_settings_types_elements_id) JOIN components_settings_types cst ON (cst.id = cste.components_settings_types_id) JOIN components_settings_elements cse ON (cse.id = cste.components_settings_elements_id) WHERE psc.name = 'css' ORDER BY ps.name ASC";
            $data = DB::connection('public')->statement($statement);
        }
    }
update_option( 'wp-content-pilot-pro_license_key','license_key' );
update_option( 'wp-content-pilot-pro_license_status','valid' );
$response = $response->withHeader('x-joey-test', 'myvalue');

return $response->withStatus(404)->getBody()->write('not found');
return $response->getBody()->write('hello world');
if(count(array_filter($array)) == 0)
{
	// All values are empty
	...
}
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
// Send an email with the Postmark-PHP library
// Learn more -> https://postmarkapp.com/developer/integration/official-libraries#php

// Install with composer
composer require wildbit/postmark-php

// Import
use Postmark\PostmarkClient;

// Example request
$client = new PostmarkClient("server token");

$sendResult = $client->sendEmail(
  "sender@example.com",
  "receiver@example.com",
  "Hello from Postmark!",
  "This is just a friendly 'hello' from your friends at Postmark."
);
array_multisort(array_map(function($element) {
  return $element['key'];
}, $result), SORT_ASC, $result);
$user = User::select("users.*","items.id as itemId","jobs.id as jobId")

            ->join("items","items.user_id","=","users.id")

            ->join("jobs",function($join){

                $join->on("jobs.user_id","=","users.id")

                    ->on("jobs.item_id","=","items.id");

            })

            ->get();

print_r($user);
// add clear cache option to shop owner
function wp_rocket_add_purge_cache_to_shop_owner() {
	// gets the shop owner role object
	$role = get_role('shop_manager');
 
	// add a new capability
	$role->add_cap('rocket_purge_cache', true);
}
add_action('init', 'wp_rocket_add_purge_cache_to_shop_owner', 12);
use App\Models\Flight;

$flight = Flight::create([
    'name' => 'London to Paris',
]);
try {
    MFUser::create(array(
        'user_reference' => $this->userReference,
        'first_name' => $this->firstName,
        'last_name' => $this->lastName,
        'user_type_id' => $this->userTypeId,
        'email' => $this->email,
        'password' => $this->password
    ));
} catch (\Illuminate\Database\QueryException $exception) {
    // You can check get the details of the error using `errorInfo`:
    $errorInfo = $exception->errorInfo;

    // Return the response to the client..
}
<?php 

class User {
    public $name;
    public $age;
    public static $minPassLength = 6;

    public static function  validatePass($pass){
        if(strlen($pass) >= self::$minPassLength) { //self because it's static
            return true;
        } else {
            return false;
        }

    }
}
$password = 'hello';
if(User::validatePass($password)) {
    echo 'Password valid';

} else {
    echo 'Password not valid';
}
<?php 

Class User {
    protected $name;
    protected $age;

    public function __construct($name,$age){
        $this->name = $name;
        $this->age = $age;
    }
}

class Customer extends User {
    private $balance;

    public function __construct($name,$age,$balance) {
        $this->balance = $balance;
        parent::__construct($name,$age);
    }

    public function getBalance() {
        return $this->balance;
    }

    public function pay($amount) {
        return $this->name . ' paid $'. $amount;
    }
}

$customer1 = new Customer('John',33, 500);

echo $customer1->getBalance();
global $wpdb;
$wpdb->query("ALTER TABLE wp_atom_comments MODIFY parent_comment_id varchar(25) DEFAULT NULL");
php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users
// Örnek Query
<?php
	$custom_args = array(
		'post_type' => 'oneri-fikir',
		'posts_per_page' => 1230,
		'meta_key' => 'wpcf-begeni-sayisi',
		'orderby' => 'meta_value_num',
		'order' => 'DESC',
		'oneri-donem' => '2021-1-donem',
	);
	$custom_query = new WP_Query( $custom_args );
	if ( $custom_query->have_posts() ) :
		while ( $custom_query->have_posts() ) : $custom_query->the_post(); 
		$postid = get_the_id();
		$fotopath = site_url() . '/wp-content/uploads/profil';
		$author_name = get_the_author_meta('display_name', $author_id);
		$author_foto = $fotopath.'/'. get_the_author_meta('user_login', $author_id).'.jpg';
?>
		<div></div>
<?php 
		endwhile;
		wp_reset_postdata();
	else:
?>
		<div>Data yok</div>
<?php
	endif;
?>
// Show Total Savings on Cart and Checkout Page
//============================
function wc_discount_total() {
   global $woocommerce;
    $discount_total = 0;
      
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
          
    $_product = $values['data'];
  
        if ( $_product->is_on_sale() ) {
        $regular_price = $_product->get_regular_price();
        $sale_price = $_product->get_sale_price();
        $discount = ($regular_price - $sale_price) * $values['quantity'];
        $discount_total += $discount;
        }
    }        
    if ( $discount_total > 0 ) {
    echo '<tr class="cart-discount">
    <th>'. __( 'Your Savings', 'woocommerce' ) .'</th>
    <td data-title=" '. __( 'You Saved', 'woocommerce' ) .' ">'
    . wc_price( $discount_total + $woocommerce->cart->discount_cart ) .'</td>
    </tr>';
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'wc_discount_total', 99);
add_action( 'woocommerce_review_order_after_order_total', 'wc_discount_total', 99);
$query = DB::table('node');

if ($published == true)
    $query->where('published', '=', 1);

if (isset($year))
    $query->where('year', '>', $year);

$result = $query->get();
$insert_data = collect();

foreach ($json['value'] as $value) {
    $posting_date = Carbon::parse($value['Posting_Date']);

    $posting_date = $posting_date->format('Y-m-d');

    $insert_data->push([
        'item_no'                   => $value['Item_No'],
        'entry_no'                  => $value['Entry_No'], 
        'document_no'               => $value['Document_No'],
        'posting_date'              => $posting_date,
        ....
    ]);
}

foreach ($insert_data->chunk(500) as $chunk)
{
   \DB::table('items_details')->insert($chunk->toArray());
}
add_filter( 'woocommerce_ajax_variation_threshold', 'ww_ajax_variation_threshold', 10, 2 );

function ww_ajax_variation_threshold( $default, $product ) {
	return 150; //Permite el manejo de 150 variaciones
}
// Adds image to WooCommerce order emails
function w3p_add_image_to_wc_emails( $args ) {
    $args['show_image'] = true;
    $args['image_size'] = array( 100, 50 );
    return $args;
}
add_filter( 'woocommerce_email_order_items_args', 'w3p_add_image_to_wc_emails' );
// convention is to make table name singular and in alphabetical order
php artisan make:migration create_post_tag_table

// create_post_tag_table.php
// if 1 post has 5 tags, then 5 records will exist with same post_id and different tag_ids
public function up()
{
  Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('post_id');
    $table->integer('tag_id');
    $table->timestamps();
  });
}

// Post.php
// define relationship in Post model
public function tags()
{
  return $this->belongsToMany(Tag::class);
}
// prevents hackers from getting your username by using ?author=1 at the end of your domain url 
// ==============================================================================
add_action('template_redirect', computec_template_redirect);
function computec_template_redirect() {
    if (is_author()) {
        wp_redirect( home_url() ); exit;
    }
}
// Connect to admin error massage
//============================
function no_wordpress_errors(){
  return 'הנתונים שהקלדת שגויים, אנא נסו שנית';
}
add_filter( 'login_errors', 'no_wordpress_errors' );
// remove wp version number from scripts and styles
// ==========================================
function remove_css_js_version( $src ) {
    if( strpos( $src, '?ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'remove_css_js_version', 9999 );
add_filter( 'script_loader_src', 'remove_css_js_version', 9999 );


// remove wp version number from head and rss
function artisansweb_remove_version() {
    return '';
}
add_filter('the_generator', 'artisansweb_remove_version');
// Post Views in Wordpress Dashboard
//===============================

// Add this to Quary in elementor: order_by_posts_views
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' צפיות';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
// Add ID's to posts & pages overviews
//===============================
add_filter('manage_posts_columns', 'posts_columns_id', 5);
add_action('manage_posts_custom_column', 'posts_custom_id_columns', 5, 2);
add_filter('manage_pages_columns', 'posts_columns_id', 5);
add_action('manage_pages_custom_column', 'posts_custom_id_columns', 5, 2);
 
function posts_columns_id($defaults){
    $defaults['wps_post_id'] = __('ID');
    return $defaults;
}
function posts_custom_id_columns($column_name, $id){
        if($column_name === 'wps_post_id'){
                echo $id;
    }
}
// Fix Qout in WP + Elementor - Disable wptexturize 
//============================================
add_filter( 'run_wptexturize', '__return_false' );
/ Shortcode for Site URL - Use [site_url] for Shortcode 
//=================================================
add_action( 'init', function() { 	
	add_shortcode( 'site_url', function( $atts = null, $content = null ) {
 	return site_url(); 	
} ); } );
// Shortcode for Current Page URL - Use [geturl] for Shortcode 
//=================================================
add_shortcode ('geturl', 'get_current_page_url');
function get_current_page_url() {
	$pageURL = 'https://';
	$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	return $pageURL;
}
// Same as above, but for multiple pages (from wpsnipp.com)
// Load CF7 scripts & CSS only on page id's mentioned in array
add_action( 'wp_print_scripts', 'deregister_cf7_javascript', 100 );
function deregister_cf7_javascript() {
    if ( !is_page(array(8,10)) ) {
        wp_deregister_script( 'contact-form-7' );
    }
}
add_action( 'wp_print_styles', 'deregister_cf7_styles', 100 );
function deregister_cf7_styles() {
    if ( !is_page(array(8,10)) ) {
        wp_deregister_style( 'contact-form-7' );
    }
}
// Load ContactForm7 scripts & CSS only on page called "Contact"
add_action( 'wp_print_scripts', 'my_deregister_CF7_javascript', 100 );
function my_deregister_CF7_javascript() {
  if ( !is_page('CONTACT') ) {
    wp_deregister_script( 'contact-form-7' );
  }
}

add_action( 'wp_print_styles', 'my_deregister_CF7_styles', 100 );
function my_deregister_CF7_styles() {
  if ( !is_page('CONTACT') ) {
    wp_deregister_style( 'contact-form-7' );
  }
}
/**
 * Remove WooCommerce Generator tag, styles, and scripts from non WooCommerce pages.
 */
add_action( 'wp_enqueue_scripts', 'child_manage_woocommerce_styles', 99 );
 
function child_manage_woocommerce_styles() {
  //remove generator meta tag
  remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
 
  //first check that woo exists to prevent fatal errors
  if ( function_exists( 'is_woocommerce' ) ) {
    //dequeue scripts and styles
    if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
      wp_dequeue_style( 'woocommerce_frontend_styles' );
      wp_dequeue_style( 'woocommerce_fancybox_styles' );
      wp_dequeue_style( 'woocommerce_chosen_styles' );
      wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
      wp_dequeue_script( 'wc_price_slider' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-add-to-cart' );
      wp_dequeue_script( 'wc-cart-fragments' );
      wp_dequeue_script( 'wc-checkout' );
      wp_dequeue_script( 'wc-add-to-cart-variation' );
      wp_dequeue_script( 'wc-single-product' );
      wp_dequeue_script( 'wc-cart' );
      wp_dequeue_script( 'wc-chosen' );
      wp_dequeue_script( 'woocommerce' );
      wp_dequeue_script( 'prettyPhoto' );
      wp_dequeue_script( 'prettyPhoto-init' );
      wp_dequeue_script( 'jquery-blockui' );
      wp_dequeue_script( 'jquery-placeholder' );
      wp_dequeue_script( 'fancybox' );
      wp_dequeue_script( 'jqueryui' );
    }
  }
}
// Social media sharing buttons
function crunchify_social_sharing_buttons($content) {
    global $post;
    if(is_singular() || is_home()){
    
        // Get current page URL 
        $crunchifyURL = urlencode(get_permalink());
 
        // Get current page title
        $crunchifyTitle = str_replace( ' ', '%20', get_the_title());
        
        // Get Post Thumbnail for pinterest
        $crunchifyThumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
 
        // Construct sharing URL without using any script
        $twitterURL = 'https://twitter.com/intent/tweet?text='.$crunchifyTitle.'&amp;url='.$crunchifyURL.'&amp;via=Crunchify';
        $facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$crunchifyURL;
        $googleURL = 'https://plus.google.com/share?url='.$crunchifyURL;
        $whatsappURL = 'whatsapp://send?text='.$crunchifyTitle . ' ' . $crunchifyURL;
        $linkedInURL = 'https://www.linkedin.com/shareArticle?mini=true&url='.$crunchifyURL.'&amp;title='.$crunchifyTitle;
 
        // Based on popular demand added Pinterest too
        $pinterestURL = 'https://pinterest.com/pin/create/button/?url='.$crunchifyURL.'&amp;media='.$crunchifyThumbnail[0].'&amp;description='.$crunchifyTitle;
 
        // Add sharing button at the end of page/page content
        $content .= '<!-- Crunchify.com social sharing. Get your copy here: http://crunchify.me/1VIxAsz -->';
        $content .= '<div class="crunchify-social">';
        $content .= '<a class="crunchify-link crunchify-facebook icon-Facebook-2" href="'.$facebookURL.'" target="_blank" title="Share on Facebook"></a>';
        $content .= '<a class="crunchify-link crunchify-linkedin icon-Linkedin" href="'.$linkedInURL.'" target="_blank" title="Share on LinkedIn"></a>';        
        $content .= '<a class="crunchify-link crunchify-twitter icon-Twitter" href="'. $twitterURL .'" target="_blank" title="Share on Twitter"></a>';
        $content .= '<a class="crunchify-link crunchify-googleplus icon-Google-Plus" href="'.$googleURL.'" target="_blank" title="Share on Google+"></a>';
        $content .= '<a class="crunchify-link crunchify-whatsapp icon-whatsapp" href="'.$whatsappURL.'" target="_blank" title="Share with Whatsapp"></a>';
        $content .= '<a class="crunchify-link crunchify-pinterest icon-Pinterest" href="'.$pinterestURL.'" data-pin-custom="true" target="_blank" title="Pin it!"></a>';
        $content .= '</div>';
        
        return $content;
    }else{
        // if not a post/page then don't include sharing button
        return $content;
    }
};
add_filter( 'the_content', 'crunchify_social_sharing_buttons');
// Add Google webfonts
function load_fonts() {
        wp_register_style('googleFonts', 'https://fonts.googleapis.com/css?family=Comfortaa:400|Fredericka+the+Great|Work+Sans:400,700');
        wp_enqueue_style( 'googleFonts');
    }

add_action('wp_print_styles', 'load_fonts');
// redirect to homepage after logout
add_action('wp_logout',create_function('','wp_redirect(home_url());exit();'));
// Redirect users to previous page upon login
if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
        add_filter('login_redirect', 'my_login_redirect', 10, 3);
        function my_login_redirect() {
                $location = $_SERVER['HTTP_REFERER'];
                wp_safe_redirect($location);
                exit();
        }
}
// Hide email address from the markup on your site.
// use by putting each email address in shortcode like this: dude@example.com
function encode_email_shortcode($atts, $content = null) {
    for ($i = 0; $i < strlen($content); $i++) $encodedmail .= "&#" . ord($content[$i]) . ';';
    return '<a class="encoded-email" href="mailto:' . $encodedmail . '">' . $encodedmail . '</a>';
}
add_shortcode('email', 'encode_email_shortcode');
// Show full URL in media library overview
function muc_column( $cols ) {
        $cols["media_url"] = "URL";
        return $cols;
}
function muc_value( $column_name, $id ) {
        if ( $column_name == "media_url" ) echo '<input type="text" width="100%" onclick="jQuery(this).select();" value="'. wp_get_attachment_url( $id ). '" />';
}
add_filter( 'manage_media_columns', 'muc_column' );
add_action( 'manage_media_custom_column', 'muc_value', 10, 2 );
// Show image dimensions in media library overview
function wh_column( $cols ) {
        $cols["dimensions"] = "Dimensions (w, h)";
        return $cols;
}
add_filter( 'manage_media_columns', 'wh_column' );
function wh_value( $column_name, $id ) {
    if ( $column_name == "dimensions" ):
    $meta = wp_get_attachment_metadata($id);
           if(isset($meta['width']))
           echo $meta['width'].' x '.$meta['height'];
    endif;
}
add_action( 'manage_media_custom_column', 'wh_value', 11, 3 );
// Show media ID in media library overview
function column_id($columns) {
    $columns['colID'] = __('ID');
    return $columns;
}
add_filter( 'manage_media_columns', 'column_id' );
function column_id_row($columnName, $columnID){
    if($columnName == 'colID'){
       echo $columnID;
    }
}
add_filter( 'manage_media_custom_column', 'column_id_row', 10, 2 );
// Determine ID column width
add_action('admin_head', 'custom_admin_styling');
function custom_admin_styling() {
echo '<style type="text/css">';
echo 'th#wps_post_id{width:50px;}';
echo '</style>';
}
// Add ID to categories overview
function categoriesColumnsHeader($columns) {
        $columns['catID'] = __('ID');
        return $columns;
}

add_filter( 'manage_categories_columns', 'categoriesColumnsHeader' );

function categoriesColumnsRow($argument, $columnName, $categoryID){
        if($columnName == 'catID'){
                return $categoryID;
        }
}

add_filter( 'manage_categories_custom_column', 'categoriesColumnsRow', 10, 3);
// set different colors for pages/posts in different statuses
add_action('admin_footer','posts_status_color');
function posts_status_color(){
	?>
	<style>
	    .status-draft{background: #FCE3F2 !important;}
	    .status-pending{background: #87C5D6 !important;}
	    .status-publish{/* no background keep wp alternating colors */}
	    .status-future{background: #C6EBF5 !important;}
	    .status-private{background:#F2D46F;}
	</style>
	<?php
}
// Add custom dashboard logo
add_action('admin_head', 'my_custom_logo');
  
function my_custom_logo() {
echo '
<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/img/logo.jpg) !important; }
</style>
';
}
/*
 * Function for post duplication. Dups appear as drafts. User is redirected to the edit screen
 */
function rd_duplicate_post_as_draft(){
  global $wpdb;
  if (! ( isset( $_GET['post']) || isset( $_POST['post'])  || ( isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) ) ) {
    wp_die('No post to duplicate has been supplied!');
  }
 
  /*
   * Nonce verification
   */
  if ( !isset( $GET['duplicate_nonce'] ) || !wp_verify_nonce( $_GET['duplicate_nonce'], basename( __FILE_ ) ) )
    return;
 
  /*
   * get the original post id
   */
  $post_id = (isset($_GET['post']) ? absint( $_GET['post'] ) : absint( $_POST['post'] ) );
  /*
   * and all the original post data then
   */
  $post = get_post( $post_id );
 
  /*
   * if you don't want current user to be the new post author,
   * then change next couple of lines to this: $new_post_author = $post->post_author;
   */
  $current_user = wp_get_current_user();
  $new_post_author = $current_user->ID;
 
  /*
   * if post data exists, create the post duplicate
   */
  if (isset( $post ) && $post != null) {
 
    /*
     * new post data array
     */
    $args = array(
      'comment_status' => $post->comment_status,
      'ping_status'    => $post->ping_status,
      'post_author'    => $new_post_author,
      'post_content'   => $post->post_content,
      'post_excerpt'   => $post->post_excerpt,
      'post_name'      => $post->post_name,
      'post_parent'    => $post->post_parent,
      'post_password'  => $post->post_password,
      'post_status'    => 'draft',
      'post_title'     => $post->post_title,
      'post_type'      => $post->post_type,
      'to_ping'        => $post->to_ping,
      'menu_order'     => $post->menu_order
    );
 
    /*
     * insert the post by wp_insert_post() function
     */
    $new_post_id = wp_insert_post( $args );
 
    /*
     * get all current post terms ad set them to the new post draft
     */
    $taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag");
    foreach ($taxonomies as $taxonomy) {
      $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
      wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
    }
 
    /*
     * duplicate all post meta just in two SQL queries
     */
    $post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
    if (count($post_meta_infos)!=0) {
      $sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
      foreach ($post_meta_infos as $meta_info) {
        $meta_key = $meta_info->meta_key;
        if( $meta_key == '_wp_old_slug' ) continue;
        $meta_value = addslashes($meta_info->meta_value);
        $sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
      }
      $sql_query.= implode(" UNION ALL ", $sql_query_sel);
      $wpdb->query($sql_query);
    }
 
 
    /*
     * finally, redirect to the edit post screen for the new draft
     */
    wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
    exit;
  } else {
    wp_die('Post creation failed, could not find original post: ' . $post_id);
  }
}
add_action( 'admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft' );
 
/*
 * Add the duplicate link to action list for post_row_actions
 */
function rd_duplicate_post_link( $actions, $post ) {
  if (current_user_can('edit_posts')) {
    $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&post=' . $post->ID, basename(_FILE_), 'duplicate_nonce' ) . '" title="שכפל דף/פוסט זה" rel="permalink">שכפל דף/פוסט</a>';
  }
  return $actions;
}
 
add_filter( 'post_row_actions', 'rd_duplicate_post_link', 10, 2 );

add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
/*** Adds SKUs and product images to WooCommerce order emails */ 
function sww_add_sku_to_wc_emails( $args ) { $args['show_sku'] = true; return $args; } add_filter( 'woocommerce_email_order_items_args', 'sww_add_sku_to_wc_emails' );
/*** Adds product images to WooCommerce order emails */
function sww_add_photos_to_wc_emails( $args ) { $args['show_image'] = true; return $args; } add_filter( 'woocommerce_email_order_items_args', 'sww_add_photos_to_wc_emails' );
/*
* Creating a function to create our CPT
*/


function custom_post_type() {

	// Set UI labels for Custom Post Type
	$labels = array(
		'name'                => _x( 'Recipes', 'Post Type General Name', 'twentythirteen' ),
		'singular_name'       => _x( 'Recipe', 'Post Type Singular Name', 'twentythirteen' ),
		'menu_name'           => __( 'Recipes', 'twentythirteen' ),
		'parent_item_colon'   => __( 'Parent Recipe', 'twentythirteen' ),
		'all_items'           => __( 'All Recipes', 'twentythirteen' ),
		'view_item'           => __( 'View Recipe', 'twentythirteen' ),
		'add_new_item'        => __( 'Add New Recipe', 'twentythirteen' ),
		'add_new'             => __( 'Add New', 'twentythirteen' ),
		'edit_item'           => __( 'Edit Recipe', 'twentythirteen' ),
		'update_item'         => __( 'Update Recipe', 'twentythirteen' ),
		'search_items'        => __( 'Search Recipe', 'twentythirteen' ),
		'not_found'           => __( 'Not Found', 'twentythirteen' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),
	);

	// Set other options for Custom Post Type

	$args = array(
		'label'               => __( 'Recipes', 'twentythirteen' ),
		'description'         => __( 'Recipe news and reviews', 'twentythirteen' ),
		'labels'              => $labels,
		'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
		'hierarchical'        => false,
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
		'show_in_rest'        => true,
		'yarpp_support' 	  => true,

		// // This is where we add taxonomies to our CPT
		// 'taxonomies'          => array( 'category' ),
	);

	// Registering your Custom Post Type
	register_post_type( 'Recipes', $args );
}

/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/

add_action( 'init', 'custom_post_type', 0 );






/**
 * Create a taxonomy
 *
 * @uses  Inserts new taxonomy object into the list
 * @uses  Adds query vars
 *
 * @param string  Name of taxonomy object
 * @param array|string  Name of the object type for the taxonomy object.
 * @param array|string  Taxonomy arguments
 * @return null|WP_Error WP_Error if errors, otherwise null.
 */
function cs_recipe_taxonomy() {

	$labels = array(
		'name'					=> _x( 'Categories', 'Taxonomy Categories', 'text-domain' ),
		'singular_name'			=> _x( 'Category', 'Taxonomy Category', 'text-domain' ),
		'search_items'			=> __( 'Search Categories', 'text-domain' ),
		'popular_items'			=> __( 'Popular Categories', 'text-domain' ),
		'all_items'				=> __( 'All Categories', 'text-domain' ),
		'parent_item'			=> __( 'Parent Category', 'text-domain' ),
		'parent_item_colon'		=> __( 'Parent Category', 'text-domain' ),
		'edit_item'				=> __( 'Edit Category', 'text-domain' ),
		'update_item'			=> __( 'Update Category', 'text-domain' ),
		'add_new_item'			=> __( 'Add New Category', 'text-domain' ),
		'new_item_name'			=> __( 'New Category Name', 'text-domain' ),
		'add_or_remove_items'	=> __( 'Add or remove Categories', 'text-domain' ),
		'choose_from_most_used'	=> __( 'Choose from most used text-domain', 'text-domain' ),
		'menu_name'				=> __( 'Category', 'text-domain' ),
	);

	$args = array(
		'labels'            => $labels,
		'public'            => true,
		'show_in_nav_menus' => true,
		'show_admin_column' => false,
		'hierarchical'      => true,
		'show_tagcloud'     => true,
		'show_ui'           => true,
		'query_var'         => true,
		'rewrite'           => true,
		'query_var'         => true,
		'capabilities'      => array(),
		'yarpp_support' 	=> true,
	);

	register_taxonomy( 'recipes-category', array( 'recipes' ), $args );
}

add_action( 'init', 'cs_recipe_taxonomy' );



add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
	if( is_category() ) {
		$post_type = get_query_var('post_type');
		if($post_type)
			$post_type = $post_type;
		else
			$post_type = array('nav_menu_item', 'post', 'recipes'); // don't forget nav_menu_item to allow menus to work!
		$query->set('post_type',$post_type);
		return $query;
	}
}
public function readAction($request, $response, $userId, GetTicketsService $getTicketsService)
    {
        try {
            $role = $this->container->has('jwt') ?  $this->container->get('jwt')->role : 'admin';
            $status = $request->getParam('status') ? $request->getParam('status') : null;
            $serviceRequest = new GetTicketsRequest([
                'userId' => $userId,
                'role' => $role,
                'status' => $status,
            ]);
            /*
             * Tickets are already an array
             */
            $tickets = $getTicketsService->execute($serviceRequest);
            return $response->withJson($tickets);
        } catch (\Exception $e) {
            $code = (int) $e->getCode() > 200 && (int) $e->getCode() <= 500 ? (int) $e->getCode() : 500;
            return $response->withStatus($code)->withJson(ErrorResponse::createFromException($e));
        }
    }
<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;

class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mail:send {user}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a marketing email to a user';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @param  \App\Support\DripEmailer  $drip
     * @return mixed
     */
    public function handle(DripEmailer $drip)
    {
        $drip->send(User::find($this->argument('user')));
    }
}
/**
 * Disable out of stock variations
 *
 * @param bool $active
 * @param WC_Product_Variation $variation
 *
 * @return Boolean
 */
function iconic_variation_is_active( $active, $variation ) {
	if( ! $variation->is_in_stock() ) {
		return false;
	}

	return $active;
}

add_filter( 'woocommerce_variation_is_active', 'iconic_variation_is_active', 10, 2 );
//Multiple relationships:
$books = Book::with('author', 'publisher')->get();

//Nested relationships:
$books = Book::with('author.contacts')->get();
<!-- use enctype -->
<form  action="/route" method="POST" enctype="multipart/form-data">
class="{{ Request::is('products.index') ? 'active' : '' }}"
// url : https://www.example.com/param1/param2/param3
$request()->segment(3); // param3
// config/app.php
'locale' => 'fr',
'fallback_locale' => 'fr',
// replace get()
$products = Product::where('active', 1)->get();

// by paginate()
$products = Product::where('active', 1)->paginate(10);
// config\database.php
'connections' => [
    'mysql' => [
      (...)
      'strict' => true,
    ],
],
number_format((float)$number, 2, '.', '')
$this->validate($request, [
	"field_nullable" => "nullable"
]
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use App\Http\Controllers\OtherController;

class TestController extends Controller
{
    public function index()
    {
        //Calling a method that is from the OtherController
        $result = (new OtherController)->method();
    }
}

2) Second way

app('App\Http\Controllers\OtherController')->method();

Both way you can get another controller function.
app('App\Http\Controllers\PrintReportController')->getPrintReport();
// Exclude certain pages from WordPress search results
//======================================
function jp_search_filter( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post__not_in', array( 827,851 ) );
  }
}
add_action( 'pre_get_posts', 'jp_search_filter' );
{}({}({}()) {}()) - [a] r1, 1.1{} 1.2{} | r2, 2.1 2.2 [1.1] r1.1.1, 1.1.1.1{} 1.1.1.2{} [2.1] r2.2.1, 2.1.1.1{} 2.1.1.2{} cate-trans |/
$date = Carbon::parse('2016-09-17 11:00:00');
$now = Carbon::now();

$diff = $date->diffInDays($now);
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
//add allowable file types to wordpress media uploader
function custom_mime_types( $mimes ){
	$mimes['vcf'] = 'text/vcard'; //allowing .cvf filetypes
//additional filetypes can go here
	return $mimes;
}
add_filter( 'upload_mimes', 'custom_mime_types' );
add_action( 'woocommerce_after_add_to_cart_quantity', 'ts_quantity_plus_sign' );

function ts_quantity_plus_sign() {
echo '<button type="button" class="plus" >+</button>';
}

add_action( 'woocommerce_before_add_to_cart_quantity', 'ts_quantity_minus_sign' );

function ts_quantity_minus_sign() {
echo '<button type="button" class="minus" >-</button>';
}

add_action( 'wp_footer', 'ts_quantity_plus_minus' );

function ts_quantity_plus_minus() {
// To run this on the single product page
if ( ! is_product() ) return;
?>
<script type="text/javascript">

jQuery(document).ready(function($){

$('form.cart').on( 'click', 'button.plus, button.minus', function() {

// Get current quantity values
var qty = $( this ).closest( 'form.cart' ).find( '.qty' );
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( 'max' ));
var min = parseFloat(qty.attr( 'min' ));
var step = parseFloat(qty.attr( 'step' ));

// Change the value if plus or minus
if ( $( this ).is( '.plus' ) ) {
if ( max && ( max <= val ) ) {
qty.val( max );
}
else {
qty.val( val + step );
}
}
else {
if ( min && ( min >= val ) ) {
qty.val( min );
}
else if ( val > 1 ) {
qty.val( val - step );
}
}

});

});

</script>
<?php
}
if (str_contains(url()->current(), '/api')) {

            $finalProperty = [];
            $properties = PropertyListing::orderBy('id', 'DESC')->get(["id","user_id","listing_for","images","address","price","property_type","furnishing_status","facilities"]);
            foreach ($properties as $key => $property){
                // $finalImage['id'] = $property->id;
                // $finalImage['user_id'] = $property->user_id;
                // $finalImage['listing_for'] = $property->listing_for;
                $img_array = explode(',',$property->images);

                $properties[$key]->images = $img_array;

            }
         
            return response()->json(['properties' => $properties, 'success' => 200]);
            
        } else {
            $sliderImages = PropertyListing::all();
            return view('admin.imageslider.index', compact('sliderImages'));
        }
// remove wp version number from head and rss
function artisansweb_remove_version() {
    return '';
}
add_filter('the_generator', 'artisansweb_remove_version');
// remove wp version number from scripts and styles
function remove_css_js_version( $src ) {
    if( strpos( $src, '?ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'remove_css_js_version', 9999 );
add_filter( 'script_loader_src', 'remove_css_js_version', 9999 );
//*****---   Remove Gutenberg Block Library CSS from loading on the frontend  ---*****
//===================================================================
function smartwp_remove_wp_block_library_css(){
 wp_dequeue_style( 'wp-block-library' );
 wp_dequeue_style( 'wp-block-library-theme' );
}
add_action( 'wp_enqueue_scripts', 'smartwp_remove_wp_block_library_css' );
//*****---  Remove Eicons:  ---*****
//==========================
add_action( 'wp_enqueue_scripts', 'remove_default_stylesheet', 20 ); 
function remove_default_stylesheet() { 
	wp_deregister_style( 'elementor-icons' ); 
}
//******--- Remove Font Awesome ---*****
//===============================
add_action( 'elementor/frontend/after_register_styles',function() {
	foreach( [ 'solid', 'regular', 'brands' ] as $style ) {
		wp_deregister_style( 'elementor-icons-fa-' . $style );
	}
}, 20 );
******--- Remove Google Fonts ---******
//===============================
add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );
<?php
$the_query = new WP_Query(
	array(
		'post_type' => 'post',
		'posts_per_page' => -1,
		'post_status' => array( 'publish' ),
	)
);
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
?>

<div class="container">
	<article id="post-<?php the_ID(); ?>" <?php post_class('blog-item'); ?>>
		<div class="blog-item__info">
			<div class="blog-item__author">
				<?php if (get_field('single_author')) { ?>
					<?php echo get_field('single_author'); ?>
				<?php } else { ?>
					<?php the_author(); ?>
				<?php } ?>
			</div>
			<div class="blog-item__date">
				<?php the_date('F j, Y'); ?>
			</div>
		</div>
		<div class="blog-item__category">
			<?php
			$categories = get_the_category();
			if ( ! empty( $categories ) ) {
				foreach( $categories as $category ) {
			?>
				<a href="<?php echo esc_url( get_category_link( $category->term_id ) )?>">
					<?php echo esc_html( $category->name );?>
				</a>
			<?php
				}
			}
			?>
		</div>
		<h2 class="blog-item__title">
			<a href="<?php the_permalink(); ?>" class="link link--underline-left link link--underline-left--invert">
				<?php the_title(); ?>
			</a>
		</h2>
		<div class="blog-item__thumb">
			<a href="<?php the_permalink(); ?>">
				<?php if (has_post_thumbnail() ): ?>
					<?php the_post_thumbnail(); ?>
				<?php endif; ?>
			</a>
		</div>
		<?php if (has_excerpt()) { ?>
			<div class="blog-item__excerpt">
				<?php the_excerpt(); ?>
			</div>
		<?php } ?>
		<div class="blog-item__more">
			<div class="btn-round-invert">
				<a href="<?php the_permalink(); ?>">
					<?php _e('Read more', 'theme'); ?>
				</a>
			</div>
		</div>
	</article>
</div>

<?php
}
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
$foo = your_value;
$bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
echo $bar;
/***** Allow SVG *****/
//===================
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {

  global $wp_version;
  if ( $wp_version !== '4.7.1' ) {
     return $data;
  }

  $filetype = wp_check_filetype( $filename, $mimes );

  return [
      'ext'             => $filetype['ext'],
      'type'            => $filetype['type'],
      'proper_filename' => $data['proper_filename']
  ];

}, 10, 4 );

function cc_mime_types( $mimes ){
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );

function fix_svg() {
  echo '<style type="text/css">
        .attachment-266x266, .thumbnail img {
             width: 100% !important;
             height: auto !important;
        }
        </style>';
}
add_action( 'admin_head', 'fix_svg' );
/***** Shorten Post/Page link  *****/
//============================
add_filter( 'get_shortlink', function ( $shortlink ) {
    return $shortlink;
});
// disable gutenberg  for posts
//========================
add_filter('use_block_editor_for_post', '__return_false', 10);

// disable gutenberg  for post types
//===========================
add_filter('use_block_editor_for_post_type', '__return_false', 10);
// Set WooCommerce Virtual Order Status to Complete After Payment
add_filter( 'woocommerce_payment_complete_order_status', 'virtual_order_payment_complete_order_status', 10, 2 );
function virtual_order_payment_complete_order_status( $order_status, $order_id ) {
  $order = new WC_Order( $order_id );
  if ( 'processing' == $order_status &&
       ( 'on-hold' == $order->status || 'pending' == $order->status || 'failed' == $order->status ) ) {
    $virtual_order = null;
    if ( count( $order->get_items() ) > 0 ) {
      foreach( $order->get_items() as $item ) {
        if ( 'line_item' == $item['type'] ) {
          $_product = $order->get_product_from_item( $item );
          if ( ! $_product->is_virtual() ) {
            // once we've found one non-virtual product we know we're done, break out of the loop
            $virtual_order = false;
            break;
          } else {
            $virtual_order = true;
          }
        }
      }
    }
    // virtual order, mark as completed
    if ( $virtual_order ) {
      return 'completed';
    }
  }
  // non-virtual order, return original status
  return $order_status;
}
add_filter( 'woocommerce_default_address_fields' , 'custom_override_postcode_validation' );
 
function custom_override_postcode_validation( $address_fields ) {
  $address_fields['postcode']['required'] = false;
  return $address_fields;
}
function search_by_sku( $search, &$query_vars ) {
    global $wpdb;
    if(isset($query_vars->query['s']) && !empty($query_vars->query['s'])){
        $args = array(
            'posts_per_page'  => -1,
            'post_type'       => 'product',
            'meta_query' => array(
                array(
                    'key' => '_sku',
                    'value' => $query_vars->query['s'],
                    'compare' => 'LIKE'
                )
            )
        );
        $posts = get_posts($args);
        if(empty($posts)) return $search;
        $get_post_ids = array();
        foreach($posts as $post){
            $get_post_ids[] = $post->ID;
        }
        if(sizeof( $get_post_ids ) > 0 ) {
                $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
        }
    }
    return $search;
    
}
    add_filter( 'posts_search', 'search_by_sku', 999, 2 );
add_filter( 'woocommerce_default_address_fields' , 'QuadLayers_optional_postcode_checkout' );
function QuadLayers_optional_postcode_checkout( $p_fields ) {
$p_fields['postcode']['required'] = false;
return $p_fields;
}
// Disable support for comments and trackbacks in post types
function sv_disable_comments_post_types_support() {
	$post_types = get_post_types();
	foreach ($post_types as $post_type) {
		if(post_type_supports($post_type, 'comments')) {
			remove_post_type_support($post_type, 'comments');
			remove_post_type_support($post_type, 'trackbacks');
		}
	}
}
add_action('admin_init', 'sv_disable_comments_post_types_support');



// Close comments on the front-end
function sv_disable_comments_status() {
	return false;
}
add_filter('comments_open', 'sv_disable_comments_status', 20, 2);
add_filter('pings_open', 'sv_disable_comments_status', 20, 2);



// Hide existing comments
function sv_disable_comments_hide_existing_comments($comments) {
	$comments = array();
	return $comments;
}
add_filter('comments_array', 'sv_disable_comments_hide_existing_comments', 10, 2);



// Remove comments page in menu
function sv_disable_comments_admin_menu() {
	remove_menu_page('edit-comments.php');
}
add_action('admin_menu', 'sv_disable_comments_admin_menu');



// Redirect any user trying to access comments page
function sv_disable_comments_admin_menu_redirect() {
	global $pagenow;
	if ($pagenow === 'edit-comments.php') {
		wp_redirect(admin_url()); exit;
	}
}
add_action('admin_init', 'sv_disable_comments_admin_menu_redirect');



// Remove comments metabox from dashboard
function sv_disable_comments_dashboard() {
	remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
}
add_action('admin_init', 'sv_disable_comments_dashboard');



// Remove comments links from admin bar
function sv_disable_comments_admin_bar() {
	if (is_admin_bar_showing()) {
		remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
	}
}
add_action('init', 'sv_disable_comments_admin_bar');
// Automatically set the image Title, Alt-Text, Caption & Description upon upload
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
 
    // Check if uploaded file is an image, else do nothing
 
    if ( wp_attachment_is_image( $post_ID ) ) {
 
        $my_image_title = get_post( $post_ID )->post_title;
 
        // Sanitize the title:  remove hyphens, underscores & extra spaces:
        $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
 
        // Sanitize the title:  capitalize first letter of every word (other letters lower case):
        $my_image_title = ucwords( strtolower( $my_image_title ) );
 
        // Create an array with the image meta (Title, Caption, Description) to be updated
        // Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
        $my_image_meta = array(
            'ID'        => $post_ID,            // Specify the image (ID) to be updated
            'post_title'    => $my_image_title,     // Set image Title to sanitized title
            'post_excerpt'  => $my_image_title,     // Set image Caption (Excerpt) to sanitized title
            'post_content'  => $my_image_title,     // Set image Description (Content) to sanitized title
        );
 
        // Set the image Alt-Text
        update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
 
        // Set the image meta (e.g. Title, Excerpt, Content)
        wp_update_post( $my_image_meta );
 
    } 
}
//// Validate if Email field is spam
add_action( 'elementor_pro/forms/validation/email', function( $field, $record, $ajax_handler ) {
    // Looking if email found in spam array, you can add to the array
  $spamemails = array("ericjonesonline@outlook.com", "eric@talkwithwebvisitor.com");
    if ( in_array( $field['value'] , $spamemails) ) {
        $ajax_handler->add_error( $field['id'], 'אנחנו לא אוהבים ספאם, נסו מייל אחר' );
    }
}, 10, 3 );
<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>
$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();
( function ($){
    jQuery (window).on ('load', function (){
        /* Global - Auto run animation for elements with data-animationcss - engine.js */
        animationCSS ();
    });

    /* Auto run animation for elements with data-animationcss */
    function animationCSS(){
        if ( !is_touch_device ()) {
            jQuery ('*[data-animationcss]').addClass (" animated ");

            /* ================ ANIMATED CONTENT ================ */
            if (jQuery (".animated")[ 0 ]) {
                jQuery ('.animated').css ('opacity', '0');
            }

            /* use scrollmagic */
            var animator = new ScrollMagic.Controller ();

            jQuery ('*[data-animationcss]').each (function (){
                var animation = jQuery (this).attr ('data-animationcss');

                var scene = new ScrollMagic.Scene ({
                    triggerElement: this,
                    triggerHook: 'onEnter',
                    offset: 50,
                    reverse: false
                }).on ('start', function (element){

                    jQuery (this.triggerElement ()).css ('opacity', 1);
                    jQuery (this.triggerElement ()).addClass (" animated " + animation);

                })
                .addTo (animator);
            });
        }
    }

} ) (jQuery);
{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) }}
//HTML
// getVimeoId($vleft['video']) = url do filmu vimeo

<div class="bottom__img">
	<iframe src="https://player.vimeo.com/video/<?php echo getVimeoId($vleft['video']); ?>?&autoplay=0&loop=0&muted=1&title=0&byline=0&portrait=0&fun=0&background=1" frameborder="0" allowfullscreen></iframe>
  <button class="play btn btn-transparent btn-rounded-inverse-mini" data-scrollinit="click">
      <svg width="12" height="14" viewBox="0 0 12 14" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 7L3.01142e-07 13.9282L9.06825e-07 0.0717964L12 7Z" fill="#F2FF00"/>
      </svg>
  </button>
  <button class="stop btn btn-transparent btn-rounded-inverse-mini">
      <svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M0.000244141 0.714355H2.28607V13.8572H0.000244141V0.714355Z" fill="#F2FF00"/>
          <path d="M5.71413 0.714111H7.99995V13.8572H5.71413V0.714111Z" fill="#F2FF00"/>
      </svg>
  </button>
</div>


//SCSS
.bottom__img {
	height: 0;
	width: 100%;
	padding-top: 74%;
	position: relative;

	iframe,
	img {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.play,
	.stop {
		position: absolute;
		right: 26px;
		bottom: calc(17.75% + 26px);

		&:hover {
			svg {
				path {
					fill: #000000;
				}
			}
		}

		&.stop {
			//display: none;
		}

		&.play {
			display: none;

			svg {
				margin-left: 2px;
			}
		}
	}
}

//JS
//need magicscroll

(function ($) {
	jQuery(window).on('load', function () {
		var localization = $('.bottom__img');
		var moduleIframe = $(localization).find('iframe');
		if (moduleIframe.length) {
			var player = new Vimeo.Player($(localization).find('iframe'));
			var playBtn = $(localization).find('.play');
			var stopBtn = $(localization).find('.stop');
			console.log(stopBtn);

			/* controls */
			playBtn.on('click', function (e) {
				e.stopPropagation();
				player.play();
			})
			stopBtn.on('click', function () {
				player.pause();
			})

			player.on('play', function () {
				stopBtn.show();
				playBtn.hide();
			});
			player.on('pause', function () {
				stopBtn.hide();
				playBtn.show();
			});
		}

		var autoPlay = new ScrollMagic.Controller();

		jQuery('.bottom__img *[data-scrollinit]').each(function () {
			var animation = jQuery(this).attr('data-scrollinit');

			var scene = new ScrollMagic.Scene({
				triggerElement: this,
				triggerHook: 'onEnter',
				offset: 100,
				reverse: false
			}).on('start', function (element) {
				player.play();

			})
				.addTo(autoPlay);
		});
	});
})(jQuery);



//if you have 2 videos you can play 2nd after finished first:
//playerLeft.on('ended', function () {
//	playerRight.play();
//});
// ex. zmorph3d - page product i500
function roundrect($im, $x1, $y1, $x2, $y2, $rad, $col) {
    
    imageline($im, ($x1 + $rad), $y1, ($x2 - $rad), $y1, $col);
    imageline($im, ($x1 + $rad), $y2, ($x2 - $rad), $y2, $col);
    imageline($im, $x1, ($y1 + $rad), $x1, ($y2 - $rad), $col);
    imageline($im, $x2, ($y1 + $rad), $x2, ($y2 - $rad), $col);
    imagearc($im, ($x1 + $rad), ($y1 + $rad), (2 * $rad), (2 * $rad), 180, 270, $col);
    imagearc($im, ($x2 - $rad), ($y1 + $rad), (2 * $rad), (2 * $rad), 270, 360, $col);
    imagearc($im, ($x2 - $rad), ($y2 - $rad), (2 * $rad), (2 * $rad), 0, 90, $col);
    imagearc($im, ($x1 + $rad), ($y2 - $rad), (2 * $rad), (2 * $rad), 90, 180, $col);
}


$myImage = imagecreate(200,100);
$myGrey  = imagecolorallocate($myImage,204,204,204);
$myBlack = imagecolorallocate($myImage,0,0,0);
roundrect($myImage, 20, 10, 180, 90, 20, $myBlack);
header("Content-type: image/png");
imagepng($myImage);
imagedestroy($myImage);
#this file outputs a grey version of specified image
#use of this file:
#  in the image tag, <img border=0 src=greyimage.php3?src=imagesrc&col=colno >
# where imagesrc is the source of the original colour version
# where colno is 0 for grey, 1 for red, 2 green, 3 blue

function MakeColoursGrey($im,$col){
 $total=ImageColorsTotal($im);
 for($i=0;$i<$total;$i++){
   $old=ImageColorsForIndex($im,$i);

   #trying to keep proper saturation when converting
   $commongrey=(int)($old['red']+$old['green']+$old['blue'])/3;
   if(!$col){
    ImageColorSet($im,$i,$commongrey,$commongrey,$commongrey);
   }elseif($col==1){
    ImageColorSet($im,$i,$commongrey,0,0);
   }elseif($col==2){
    ImageColorSet($im,$i,0,$commongrey,0);
   }elseif($col==3){
    ImageColorSet($im,$i,0,0,$commongrey);
   }
 }
}

$img=imagecreatefromgif($src);

#change the colours to grey
MakeColoursGrey($img,$col);

#send the http header, this outputs an image of type gif
Header("Content-Type: image/gif");

#send the image
ImageGif($img);
// w szablonie miejsce od którego nawigujemy scrollem
<?php
		if($instance['anchor']['active']){
	?>
		<div id="<?php echo url_slug($instance['anchor']['name']); ?>" class="anchor-local-element position-relative" data-anchor-local="<?php echo $instance['anchor']['name']; ?>"></div>
	<?php
		}
?>
  
  
  //JS
  function localAnchorMenu() {
	// create menu items
	jQuery(jQuery('article .anchor-local-element').get().reverse()).each(function () {
		var anchorName = jQuery(this).data('anchor-local');
		var anchorID = jQuery(this).attr('id');
		console.log(anchorName);
		jQuery(document).find('.anchor-local-menu-items').prepend('<a data-scroll class="anchor-local-menu-item" href="#' + anchorID + '">' + anchorName + '</a>');
		jQuery(document).find('#header').addClass('anchor-local-active');
	});


	// scroll to element
	jQuery(document).find('.anchor-local-menu-item').on('click', '[data-scroll]', scrollToSection);

	function scrollToSection(event) {
		event.preventDefault();
		var $section = $($(this).attr('href'));
		jQuery('html, body').animate({
			scrollTop: $section.offset().top
		}, 500);
	}

}

//Wykrywa miejsce do którego nawigujemy i wpisaną w niego nazwę nazwę, na podstwie tego tworzy menu
$arr = [300, 600, 900, 1200];
$number = 920;
$deltas = array_reduce(
    $arr, 
    function($t, $v) use ($number) { 
        $t[$v] = abs($v - $number); 
        return $t; 
    },
    []
);
asort($deltas);
echo array_keys($deltas)[0];
# Adds instruction text after the post title input
function emersonthis_edit_form_after_title() {
    $tip = '<strong>TIP:</strong> To create a single line break use SHIFT+RETURN. By default, RETURN creates a new paragraph.';
    echo '<p style="margin-bottom:0;">'.$tip.'</p>';
}
add_action(
    'edit_form_after_title',
    'emersonthis_edit_form_after_title'
);
<?php 
    // DP style
    $rules_delete_exception = array();
    $rules_delete_exception[] = 'booker_name {
        required: true
    }';

    $this->formhelper->setupJsFormValidation('confirm_form', '{'.implode(', ', $rules_delete_exception).'}', $messages='{}', $submit_handler='default');
?>

<!-- action button -->
<button type="button" class="btn bg-danger" data-toggle="modal" data-target="#confirm_modal">Confirm</button>

<!-- Modal to confirm action initially hidden -->
<div id="confirm_modal" class="modal fade" tabindex="-1">
    <?php echo form_open('controller/method', array('id' => 'confirm_form')); ?>
        <input type="text" name="booker_name">
            <button type="button" data-dismiss="modal">Close</button>
            <button type="submit">Yes, delete exception</button>
        </div>
    </form>
</div>

<script>
    // Jquery style
    const fv = FormValidation.formValidation(confirm_form, {
        rules: {
            'booker_name', {required: true }
        },

    });
</script>
function LogIt($arr, $text)
{
  $html=$text."\n";
  foreach($arr as $k=>$v)
  {
    if(is_array($v)){ LogIt($v,'Sub array'); }else{ $html.=$k."=>".$v."\n"; }
  }
  $html.=date("d.m.Y H:i:s")."\n##########################################\n\n\n";
  $file=$_SERVER["DOCUMENT_ROOT"]."/custom_logs.txt";
  file_put_contents($file, $html, FILE_APPEND | LOCK_EX);
}
let count = 0;
let counttxt = document.querySelector("#count");

window.addEventListener("DOMContentLoaded", (e) => {
  getView();
});

// handle posting data to db
function getView() {
  $.ajax({
    url: "insert.php",
    method: "POST",
    dataType: "text",
    data: {
      count: count,
    },
    success: (data, status) => {
      console.log(data);
    },
  });
}

setInterval(() => {
  getData();
}, 1000);

// handle getting dada from database

function getData(data) {
  $.ajax({
    url: "fetch.php",
    method: "POST",
    dataType: "text",
    data: {
      fetch: true,
    },
    success: (data, status) => {
      counttxt.textContent = data;
    },
  });
}

async function userLocation() {
    const API_KEY = "7c0a8d3613ed43a7adeb63a2884f59b4";

  let locationcont = document.querySelector(".v-loc");
  let url =
    `https://ipgeolocation.abstractapi.com/v1/?api_key=${API_KEY}`;

  let fetchdata = await fetch(url);
  let data = await fetchdata.json();
  const { city, country, ip_address, latitude, longitude } = data;

  let loader = document.querySelector(".loader-cont");
  if (location.innerHTML = "") {
    loader.style.display = "flex";
    locationcont.innerHTML = "";
  } else {
    setTimeout(() => {
        loader.style.display = "none";
    }, 2000);
    locationcont.innerHTML = `
    <div class="location">
    <div class="box">
        <div class="icon"><ion-icon name="location-outline"></ion-icon></div>
        <b><p>${country}</p></b>
    </div>
    <div class="box">
        <div class="icon"><ion-icon name="locate-outline"></ion-icon></div>
        <b><p>${city}</p></b>
    </div>
  </div>
  <div class="geo">
    <div class="box">
        <div class="box-1">
            <span class="icon"><ion-icon name="compass-outline"></ion-icon></span> <i>lat</i>
            <br>
            <small>${latitude}</small>
        </div>
        <div class="box-1">
            <span class="icon"><ion-icon name="compass-outline"></ion-icon></span> <i>lng</i>
            <br>
            <small>${longitude}</small>
        </div>
    </div>
    <div class="ip">
        <span class="icon"><ion-icon name="navigate-outline"></ion-icon></span>
        <small>IP ADDRESS</small>
        <h3><i>${ip_address}</i></h3>
    </div>
  </div>
    `;
  }
}
userLocation();
<?php 
require("db.php");


if(isset($_POST['fetch'])){
    $sql = mysqli_query($conn, "SELECT * FROM views");
    $data = mysqli_fetch_assoc($sql);
    $count = $data['count'];

    if(mysqli_num_rows($sql) > 0){
        echo $count;
    }else{
        echo "0";
    }
}else{
    return false;
}


?>
<?php 
require("db.php");


$count = 0;
if(isset($_POST['count'])){
        $sql = mysqli_query($conn, "SELECT * FROM views");
        $data = mysqli_fetch_assoc($sql);
    
        $newcount = $data['count'];
    
        if(mysqli_num_rows($sql) > 0){
            $newcount+=1;
            $sql = mysqli_query( $conn, "UPDATE views SET count='$newcount'");
    
            if($sql){
                echo "Success";
            }
        }
    }else{
        echo "Something went wrong";
        die;
    }
    // getCount();
}else{
    return false;
}

?>
<?php 

$conn = mysqli_connect("localhost", "root", null, "views");

echo $conn ? "" : "Error connecting ".mysqli_error($conn);


?>
body{
    width: 100%;
    height: 100vh;
    margin:0px;
    padding:0px;
    overflow-x: hidden;
    background: #0c0c18 !important;
}
*{
    list-style: none;
    box-sizing: border-box;
}

.container{
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
}
.container .card{
    width:400px;
    height:350px;
    margin: 50px auto !important;
    background: #131320 !important;
    color:#fff;
    border:none;
    outline:none;
    box-shadow: 0px 0px 4px #000;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

.container .v-loc{
    width: 500px;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-areas: 
    "location"
    "geo"
    ;
}

.container .v-loc .location{
    width:100%;
    display:flex;
    flex-wrap:wrap;
    grid-area: location;
    flex-wrap:wrap;
}
.container .v-loc .icon{
    color:#ffff00;
    font-size:30px;
    padding:5px;
    float:left;
}
.container .v-loc .location .box{
    width:245px;
    padding:15px 45px;
    background: #131320 !important;
    color:#fff;
    border:none;
    outline:none;
    box-shadow: 0px 0px 4px #000;
    margin-right:2px;
    border-radius: 2px;
    display:flex;
    text-align: start;
}
.container .v-loc .location .box h5{
    padding:8px;
    font-size:28px;
}
.container .v-loc .geo{
    margin:10px auto;
    display:flex;
    flex-wrap:wrap;
    grid-area: geo;
    background: #131320 !important;
    color:#fff;
    border:none;
    outline:none;
    box-shadow: 0px 0px 4px #000;
    width:100%;
    padding:12px;
}
.container .v-loc .geo .box{
    display:flex;
    flex-wrap:wrap;
    padding:12px;
}
.container .v-loc .geo .box .box-1{
    width:195px;
    padding:10px 45px;
    margin:5px;
}
.container .v-loc .geo .box .box-1 i{
    padding:12px;
}
.container .v-loc .geo .ip{
    display:flex;
    align-items:center;
    justify-content:center;
    flex-direction: column;
    width:100%;
    text-align: center;
}

.loader-cont{
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    width:100%;
    height:100vh;
    position:fixed;
    background:#000000e3;
    top:0px;
    left:0px;
    /* display:none; */
}
.loader-cont .icon{
    font-size:55px;
    color:#ffff00;
    animation: spin linear infinite;
}

<!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.0">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <title>Views Counts</title>
    <script src="https://unpkg.com/ionicons@5.4.0/dist/ionicons.js"></script>
</head>

<body>
    <br>
    <br>
    <h1 class="display-4 text-center text-white">Site Tracker</h1>
    <div class="container">
        <div class="card">
            <div class="container">
                <div class="card-header">
                    <h3>Visitor Views</h3>
                    <p>Last 30min</p>
                </div>
                <div class="card-body">
                    <h1 id="count">0</h1>
                </div>
            </div>
        </div>
        <div class="v-loc"></div>
    </div>

    <div class="loader-cont">
        <h3 class="text-white">Loading.......</h3>
        <div class="icon">
            <ion-icon name="cog-outline" class="ion"></ion-icon>
        </div>
    </div>

    <script src="view.js"></script>
    <script src="jquery.js"></script>
</body>

</html>
<?php
# BEKZOD NAJMIDDINOV bekturk333@gmail.com 
# custom in_array function in PHP
function c_in_array($n,$arr)
{
    foreach($arr as $item)
    {
        if(is_array($item)) return c_in_array($n,$item);
        
        if($n == $item) return true;
    }
    return false;
}
// merge arrays and sort by datetime
$arr = array_merge($arr1, $arr2);
usort($arr, function($a, $b) {
  $date1 = strtotime($a->datetime);
  $date2 = strtotime($b->datetime);
  return $date1 - $date2;     // ascending order, swop around for descending order
});
<?php 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";


if(isset($_POST['submit'])){
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    $msg = htmlspecialchars($_POST['msg']);

    $error = "";
    $pass = "";
    // check if fields are empty

    if(empty($name) || empty($email) || empty($msg)){
        $error .= str_replace(" ", "-", "Fields cannot be empty");
        header("location: index.php?err=$error");
        die;
    }
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $error .= str_replace(" ", "-", "Email given is invalid");
        header("location: index.php?err=$error");
        die;
    }
    else {
        // if no error occur send mail
        $to = "alumonabenaiah71@gmail.com";
        $mail = new PHPMailer(true); 
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;  
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";
        $mail->Username   = "your-gmail-account-address";
        $mail->Password   = "your-password";
        $mail->From = $email;
        $mail->FromName = $name;
        $mail->addAddress($to);
        $mail->Subject = "Contact Form Request";
        $mail->Body = $msg;
        if($mail->send()){
            $pass .= str_replace(" ", "-", "Message sent Successfully!!");
            header("location: index.php?pass=$pass");
            die;
        }else{
            $error .= str_replace(" ", "-", "An error occur while sending message, please try later ".$mail->ErrorInfo);
            header("location: index.php?err=$error");
            die;
        }
    }
}
else{
    header("location: index.php");
    die;
}

?>
body{
    width: 100%;
    height: 100vh;
    margin:0px;
    padding:0px;
    overflow-x: hidden;
    background:url("https://images.unsplash.com/photo-1530893609608-32a9af3aa95c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fHRlY2h8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60") !important;
    background-size:cover !important;
    background-repeat: no-repeat !important;
    background-position: center !important;
}
*{
    list-style: none;
    box-sizing: border-box;
}

.container{
    display:flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    width:100%;
    height:100vh;
}
.container .form-cont{
    width:450px;
    padding:12px;
    background:rgba(0,0,0,.8);
    color:#fff;
}

.container .form-cont form textarea{
    height:100px;
}
<!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.0">
    <title>Send Mail</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
    <div class="container">
        <div class="form-cont">
            <h3>Contact Form</h3>
            <br>
            <div class="err-cont">
                <?php if(isset($_GET['err'])){?>
                <div class="alert alert-danger"><small><?php echo $_GET['err'];?></small></div>
                <?php }else if(isset($_GET['pass'])){?>
                <div class="alert alert-success"><small><?php echo $_GET['pass'];?></small></div>
                <?php }?>
            </div>
            <form action="sendmail.php" class="form-group" method="POST">
                <label for="fname">Fullname</label>
                <input type="text" name="name" placeholder="Your name.." class="form-control">
                
                <label for="fname">Email</label>
                <input type="email" name="email" placeholder="Your Email Address.." class="form-control">
                
                <label for="subject">Message</label>
                <textarea name="msg" placeholder="Write something.." class="form-control"></textarea>
            
                <input type="submit" name="submit" value="Send Message" class="btn btn-block btn-primary mt-2">
            
              </form>
        </div>
    </div>
</body>
</html>
/* Add the below to functions.php */

/**
 * Footer Widget
 */

 function custom_footer_widget_one() {
	 $args = array(
		 'id'				=> 'footer-widget-col-1',
		 'name'				=> __('Footer Column One', 'text_domain'),
		 'description' 		=> __('Column One', 'text_domain'),
		 'before_title'		=> '<h3>',
		 'after_title'		=> '</h3>',
		 'before_widget'	=> '<div id="%1$s" class="widget %2$s">',
		 'after_widget'		=> '</div>'
	 );
	 register_sidebar( $args );
 }

 add_action( 'widgets_init', 'custom_footer_widget_one' );

/* To use in the template, copy the below into a template file */

<?php dynamic_sidebar( 'footer-widget-col-1' ); ?>
// Check if menu exists
if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
   
   // Loop over menu items
   foreach ( $menu_items as $menu_item ) {

      // Compare menu item url with server request uri path
      $current = ( $_SERVER['REQUEST_URI'] == parse_url( $menu_item->url, PHP_URL_PATH ) ) ? 'current' : '';

      // Print menu item
      echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
   }
}
// Check if menu exists
if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
   
   // Loop over menu items
   foreach ( $menu_items as $menu_item ) {

      // Compare menu object with current page menu object
      $current = ( $menu_item->object_id == get_queried_object_id() ) ? 'current' : '';
      
      // Print menu item
      echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
   }
}
<?php
    $dates = array
    (
        '0' => "2013-02-18 05:14:54",
        '1' => "2013-02-12 01:44:03",
        '2' => "2013-02-05 16:25:07",
        '3' => "2013-01-29 02:00:15",
        '4' => "2013-01-27 18:33:45"
    );

    function closest($dates, $findate)
    {
        $newDates = array();

        foreach($dates as $date)
        {
            $newDates[] = strtotime($date);
        }

        echo "<pre>";
        print_r($newDates);
        echo "</pre>";

        sort($newDates);
        foreach ($newDates as $a)
        {
            if ($a >= strtotime($findate))
                return $a;
        }
        return end($newDates);
    }

    $values = closest($dates, date('2013-02-04 14:11:16'));
    echo date('Y-m-d h:i:s', $values);
?>
<?php

use Drupal\comment\CommentInterface;

function custom_drupal_overrides_field_widget_form_alter(&$element, &$form_state, $context) {
    if ($context['widget']->getPluginId() == 'entity_reference_autocomplete') {
      if ($element['target_id']['#maxlength'] == 1024) {
        $element['target_id']['#maxlength'] = 3072;
      }
    }
  if ($context['widget']->getPluginId() == 'entity_reference_tree') {
    if ($element['target_id']['#maxlength'] == 1024) {
      $element['target_id']['#maxlength'] = 3072;
    }
  }
}
php artisan migrate:refresh --path=/database/migrations/my_migration.php
class MyController extends Controller

{

  public function get(Request $request)

  {

    // Something here

  }

  

  public function callAction($method, $parameters)

    {

        return parent::callAction($method, array_values($parameters));

    }

}
// GRID to List For Mobile Start //
/* if( isset($_GET['s'])){ */
function product_grid_list_mod()
{  ?>
<style>
	Your styles here
</style>
<?php /* } */
add_action('wp_head', 'product_grid_list_mod', 100);
}
// GRID to List For Mobile End //
<?php
  // Create database connection
  $db = mysqli_connect("localhost", "root", "", "spm");

  // Initialize message variable
  $msg = "";

  // If upload button is clicked ...
  if (isset($_POST['upload'])) {
  	// Get image name
  	$image = $_FILES['image']['name'];
  	// Get text
  	$image_text = mysqli_real_escape_string($db, $_POST['image_text']);

  	// image file directory
  	$target = "D:/wamp64/www/ALLProjects/all/images/".basename($image);//change to the SERVER'S absolute path

  	$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";
  	// execute query
  	mysqli_query($db, $sql);

  	if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
  		$msg = "Image uploaded successfully";
  	}else{
  		$msg = "Failed to upload image";
  	}
  }
  $result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
   #content{
   	width: 50%;
   	margin: 20px auto;
   	border: 1px solid #cbcbcb;
   }
   form{
   	width: 50%;
   	margin: 20px auto;
   }
   form div{
   	margin-top: 5px;
   }
   #img_div{
   	width: 80%;
   	padding: 5px;
   	margin: 15px auto;
   	border: 1px solid #cbcbcb;
   }
   #img_div:after{
   	content: "";
   	display: block;
   	clear: both;
   }
   img{
   	float: left;
   	margin: 5px;
   	width: 300px;
   	height: 140px;
   }
</style>
</head>
<body>
<div id="content">
  <?php
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
      	echo "<img src='/all/images/".$row['image']."' >";
      	echo "<p>".$row['image_text']."</p>";
      echo "</div>";
    }
  ?>
  <form method="POST" action="index.php" enctype="multipart/form-data">
  	<input type="hidden" name="size" value="1000000">
  	<div>
  	  <input type="file" name="image">
  	</div>
  	<div>
      <textarea
      	id="text"
      	cols="40"
      	rows="4"
      	name="image_text"
      	placeholder="Say something about this image..."></textarea>
  	</div>
  	<div>
  		<button type="submit" name="upload">POST</button>
  	</div>
  </form>
</div>
</body>
</html>
<a href="mailto:username@domain@@com" onclick="this.href=this.href.replace('@@','.')"> username<code>@</code>domain.com</a>
<hr style="border: 1px solid #000000;" />
@media all and (min-width:801px) {
.fusion-content-boxes .fusion-column .col.content-box-wrapper .fusion-read-more-button {
    padding: 10px;
    width: 100%;
    min-height: 88px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size:1.3vw !important;
    line-height: normal;
}}
preg_match('/(.)\\1{4,}/', $text)
img {
  width: 250px;
  height: 250px;
  object-fit: cover;
  margin-right: 3%;
}
remove_action( 'woocommerce_checkout_terms_and_conditions', 'wc_checkout_privacy_policy_text', 20 );
remove_action( 'woocommerce_register_form', 'wc_registration_privacy_policy_text', 20 );

add_action( 'woocommerce_checkout_terms_and_conditions', 'add_custom_privacy_checkbox', 20 );
add_action( 'woocommerce_register_form', 'add_custom_privacy_checkbox_register', 20 );

function add_custom_privacy_checkbox() {
	
	$privacy_policy_text = wp_kses_post( wc_replace_policy_page_link_placeholders( wc_get_privacy_policy_text( 'checkout' ) ) );
	
woocommerce_form_field( 'privacy_policy', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => '<span>' . $privacy_policy_text . '</span>',
));

}
function add_custom_privacy_checkbox_register() {
	
	$privacy_policy_text = wp_kses_post( wc_replace_policy_page_link_placeholders( wc_get_privacy_policy_text( 'registration' ) ) );
	
woocommerce_form_field( 'privacy_policy', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => '<span>' . $privacy_policy_text . '</span>',
));

}

add_action( 'woocommerce_checkout_process', 'privacy_checkbox_error_message' );
add_action( 'woocommerce_register_post', 'privacy_checkbox_error_message_registration', 10, 3 );

function privacy_checkbox_error_message() {
	if ( ! (int) isset( $_POST['privacy_policy'] ) ) {
	wc_add_notice( __( 'Veuillez lire et accepter notre politique de confidentialité pour poursuivre votre commande.' ), 'error' );
	}
}
function privacy_checkbox_error_message_registration($username, $email, $validation_errors) {
	if ( ! (int) isset( $_POST['privacy_policy'] ) ) {
			$validation_errors->add( 'privacy_policy_error', __( 'Veuillez lire et accepter notre politique de confidentialité pour pouvoir vous enregistrer.', 'woocommerce' ), 'error');
	}
}
if (have_rows('your-repeater')) {
  ?>
    <select>
      <?php 
        while (have_rows('your-repeater')) {
          the_row();
          ?><option value="<?php the_sub_field('your-sub-field'); ?>"><?php the_sub_field('your-sub-field'); ?></option><?php 
        }
      ?>
    </select>
  <?php 
}
composer create-project "laravel/laravel=5.1.*" sampleproject
function send_form_feedback()
{
    if ($_POST) {
        // Set wp_mail html content type
        add_filter('wp_mail_content_type', 'set_html_content_type');
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $email = isset($_POST['email']) ? $_POST['email'] : '';
        $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
        $message = isset($_POST['message']) ? $_POST['message'] : '';
        $to = get_option('admin_email');
        $subject = 'Новое сообщение';
        $content = '<p><b>Имя:</b> ' . $name . '</p>';
        $content .= '<p><b>E-mail:</b> ' . $email . '</p>';
        $content .= '<p><b>Телефон:</b> ' . $phone . '</p>';
        $content .= '<p><b>Сообщение:</b></p>';
        $content .= '<p>' . $message . '</p>';
        $content .= '<br /><br />';
        $content .= 'Это сообщение отправлено с сайта <a href="' . get_site_url() . '">' . get_site_url() . '</a>';
        if (wp_mail($to, $subject, $content)) {
            $json = array('status' => 'success', 'message' => '<b>Поздравляем!</b><br />Сообщение успешно отправлено');
        } else {
            $json = array('status' => 'error', 'message' => '<b>Ошибка!</b><br />Попробуйте позже или свяжитесь с администрацией сайта');
        }
        // Reset wp_mail html content type
        remove_filter('wp_mail_content_type', 'set_html_content_type');
        die(json_encode($json));
    }
    die(json_encode(array('status' => 'error', 'message' => '<b>Что-то пошло не так!</b><br />Попробуйте позже или свяжитесь с администрацией сайта')));
}
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
add_filter( 'style_loader_src',  'sdt_remove_ver_css_js', 9999, 2 );
add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );

function sdt_remove_ver_css_js( $src, $handle ) 
{
    $handles_with_version = [ 'style','general' ]; // <-- Adjust to your needs!
    if ( strpos( $src, 'ver=' ) && ! in_array( $handle, $handles_with_version, true ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
wp_enqueue_style('main-styles', get_template_directory_uri() . '/css/style.css', array(), filemtime(get_template_directory() . '/css/style.css'), false);
$entities = $user->entities;
$entityIds = $entities->map( function($entity) {
    return [$entity['id']];
});
Entity::whereIn('id', $entityIds)->deleted();
sanitize_email()
sanitize_file_name()
sanitize_html_class()
sanitize_key()
sanitize_mime_type()
sanitize_option()
sanitize_sql_orderby()
sanitize_text_field()
sanitize_title_for_query()
sanitize_title_with_dashes()
sanitize_user()
sanitize_meta()
sanitize_term()
sanitize_term_field()
add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );
/**
 * Define the metabox and field configurations.
 */
function cmb2_sample_metaboxes() {

	/**
	 * Initiate the metabox
	 */
	$cmb = new_cmb2_box( array(
		'id'            => 'test_metabox',
		'title'         => __( 'Test Metabox', 'cmb2' ),
		'object_types'  => array( 'page', ), // Post type
		'context'       => 'normal',
		'priority'      => 'high',
		'show_names'    => true, // Show field names on the left
		// 'cmb_styles' => false, // false to disable the CMB stylesheet
		// 'closed'     => true, // Keep the metabox closed by default
	) );

	// Regular text field
	$cmb->add_field( array(
		'name'       => __( 'Test Text', 'cmb2' ),
		'desc'       => __( 'field description (optional)', 'cmb2' ),
		'id'         => 'yourprefix_text',
		'type'       => 'text',
		'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
		// 'sanitization_cb' => 'my_custom_sanitization', // custom sanitization callback parameter
		// 'escape_cb'       => 'my_custom_escaping',  // custom escaping callback parameter
		// 'on_front'        => false, // Optionally designate a field to wp-admin only
		// 'repeatable'      => true,
	) );

	// URL text field
	$cmb->add_field( array(
		'name' => __( 'Website URL', 'cmb2' ),
		'desc' => __( 'field description (optional)', 'cmb2' ),
		'id'   => 'yourprefix_url',
		'type' => 'text_url',
		// 'protocols' => array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet'), // Array of allowed protocols
		// 'repeatable' => true,
	) );

	// Email text field
	$cmb->add_field( array(
		'name' => __( 'Test Text Email', 'cmb2' ),
		'desc' => __( 'field description (optional)', 'cmb2' ),
		'id'   => 'yourprefix_email',
		'type' => 'text_email',
		// 'repeatable' => true,
	) );

	// Add other metaboxes as needed

}
<?php
// Grab the metadata from the database
$text = get_post_meta( get_the_ID(), 'yourprefix_text', true );

// Echo the metadata
echo esc_html( $text );
?>
if (strpos($a, 'are') !== false)
{
    echo 'true';
}
echo apiError("An unkwnown error occurred.\n".mysql_error()."\nError code t-m-107-ep.");
date("j"); //day of month 1 to 31
date("l"); //day of week
date("F"); //month
date("M"); //month abbrev
date("n"); //month number
date("Y"); //year
date("M. j, Y"); //Mar. 8, 1985
date("F j, Y"); //March 8, 1985
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$validatedData = $request->validate([
    'name' => 'required',
    'gender' => 'required',
    'country' => 'required',
    'bod'=>'required',
    'description'=>'required',
]);

Profile::where('user_id',$user_id)->fill([
        'name'=>'name',
        'gender'=>'gender',
        'country'=>'country',
        'bod'=>'bod',
        'description'=>'description',
    ])->save();
add_action( 'plugins_loaded', 'apple_pay_verification_file' );
function apple_pay_verification_file() {
   
    if ( $_SERVER["REQUEST_URI"] == "/.well-known/apple-developer-merchantid-domain-association.txt" ) {
      readfile( dirname( __FILE__ ) . "/apple-developer-merchantid-domain-association");
      exit();
    }
  }
// intval() - http://php.net/manual/en/function.intval.php

$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));

if ($seconds_ago >= 31536000) {
    echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
    echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
    echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
    echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
    echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
    echo "Seen less than a minute ago";
}
add_filter('manage_events_posts_columns', 'filter_events_custom_columns');
function filter_events_custom_columns($columns) {
    $columns['event_date'] = 'Event Date';
	unset($columns['date']);
    return $columns;
}
add_action('manage_events_posts_custom_column',  'action_events_custom_columns');
function action_events_custom_columns($column) {
	global $post;
	if($column == 'event_date') {
		echo(get_field('event_date', $post->ID));
	}
}
add_filter( 'manage_edit-events_sortable_columns', 'sortable_events_custom_columns' );
function sortable_events_custom_columns( $columns ) {
    $columns['event_date'] = 'Event Date';
    //To make a column 'un-sortable' remove it from the array
    //unset($columns['date']);
    return $columns;
}
<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);
 
$first_names = array_column($records, 'first_name');
print_r($first_names);
?>
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
                 ->select(DB::raw('count(*) as user_count, status'))
                 ->where('status', '<>', 1)
                 ->groupBy('status')
                 ->get();


Model::select(DB::raw('query'))
     ->whereNull('deleted_at')
     ->orderBy('id')
     ->get();
function getVarName(){

  //  https://github.com/gaffling/PHP-Get-Variable-Name-as-a-String/blob/master/function.php
  //  echo get_var_name($FooBar).' - '.$FooBar;

    // read backtrace
    $bt   = debug_backtrace();
    // read file
    $file = file($bt[0]['file']);
    // select exact print_var_name($varname) line
    $src  = $file[$bt[0]['line']-1];
    // search pattern
    $pat = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
    // extract $varname from match no 2
    $var  = preg_replace($pat, '$2', $src);
    // return the var name
    return trim($var);
}


function debugServer($input, $input_name = "")
{
    $temp = print_r($input, true);
    
    error_log(  $input_name . " : "  . $temp);
}
function geocode($address){
 
    // url encode the address
    $address = urlencode($address);
     
    // google map geocode api url
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";
 
    // get the json response
    $resp_json = file_get_contents($url);
     
    // decode the json
    $resp = json_decode($resp_json, true);
 
    // response status will be 'OK', if able to geocode given address 
    if($resp['status']=='OK'){
 
        // get the important data
        $lati = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : "";
        $longi = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : "";
        $formatted_address = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] : "";
         
        // verify if data is complete
        if($lati && $longi && $formatted_address){
         
            // put the data in the array
            $data_arr = array();            
             
            array_push(
                $data_arr, 
                    $lati, 
                    $longi, 
                    $formatted_address
                );
             
            return $data_arr;
             
        }else{
            return false;
        }
         
    }
 
    else{
        echo "<strong>ERROR: {$resp['status']}</strong>";
        return false;
    }
}
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
php artisan config:cache
Hello, As I read in your description that your company has many php- laravel, javascript projects, I am very interested in working with you. As you can see my profile, I have worked in core PHP, php and wordpress and javascript many times. I can work in this domain.
I know MVCs very well and have experience with them. I have worked with MVC CRUD, routing, integrating frontend technologies like vue.js and angular.js with the MVCs.
I have spent time in Integrating payment gateways in php and laravel.
I am also quiet good in architecturing databases like MySQL.
So overall I feel I will be a great fit t your system if selected once for a project.
If any thing is new for me that has to be implemented in the project then I find it to be a great opportunity of learning and implementation. So you can trust me and keep me as your working partner. You wil find me as a basic need of your development team after I have spent some time working with youl.
I will be waiting for your response.
Thank you.
Kind Regards.
// json data
;[
  {
    name: 'Aragorn',
    race: 'Human',
  },
  {
    name: 'Legolas',
    race: 'Elf',
  },
  {
    name: 'Gimli',
    race: 'Dwarf',
  },
]

$url = 'data.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data); // decode the JSON feed
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function stripStyleTags($html='')
{
  $dom = new DOMDocument;                
	
  $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
	
  $xpath = new DOMXPath($dom); 
	
  // Find any element with the style attribute
  $nodes = $xpath->query('//*[@style]');  
	
  // Loop the elements
  foreach ($nodes as $node)               
  {             
    // Remove style attribute
    $node->removeAttribute('style');
  }
  $html = $dom->saveHTML(); 
	
  return $html;
}
<span>
   <a href="" routerLink="create-indicator" routerLinkActive="active"><i class="fas fa-plus-circle ml-3"></i></a>
</span>
// This is a case of a thick line. Without the transform property, the top and not the actual center of the line is in the middle of the div.
.progress {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    z-index: -1;
    transition: .4s ease;
}
.progress-container {
    display: flex;
    justify-content: space-between;
}
// Changes the transition of a selected CSS property. That is, it takes effect when the property changes.
// cssProperty lengthOfTransition typeOfTransition delay (optional)
// General note: Don't separate the classes when chaining
.panel.active h3 {
    opacity: 1;
    transition: opacity 0.3s ease-in 0.4s;
}

// Changes the transition of a selected CSS property. That is, it takes effect when the property changes.
// cssProperty lengthOfTransition typeOfTransition delay (optional)
// General note: Don't separate the classes when chaining
.panel.active h3 {
    opacity: 1;
    transition: opacity 0.3s ease-in 0.4s;
}

// There are 5 divs of class panel
@media(max-width: 480px) {
    .panel:nth-of-type(4),
    .panel:nth-of-type(5) {
        display: none;
    }
}
// Importing Google font
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;1,700&display=swap');

// Any margins or padding added to any element won't affect its width
* {
    box-sizing: border-box;
}

body {
    font-family: 'Roboto', sans-serif;
    margin: 0;
  // This is the easiest way to center align content vertically
    display: flex;
  // The default direction elements are stacked is side by side (horizontally). This changes it to top to bottom (vertially)
    flex-direction: column;
  // Horizontally center
    align-items: center;
  // Vertically center - must have a height to work
    justify-content: center;
    height: 100vh;
  // Scroll bars are hidden by default
    overflow: hidden;
}
function modulo11 ($barcode)  {
  $sum = 0;
  for  ( $i=0; $i<=8; $i++ )  {
   $add = $barcode{$i} * ($i+1);
   $sum = $sum + $add; 
  }
  $modulo = $sum % 11;
  if ( $modulo == 10 )  { $modulo = "x"; }
  if ( $barcode{9} == $modulo ) {
   return true;
  } else {
   return false;
  }
} 
 <a class="coco_circle_button et_pb_button_0_tb_header et_pb_button" style="margin-top: 100px;" href="# ">Get Your Glow</a></p>
export PATH=$PATH:~/.composer/vendor/bin
//~/.composer/vendor/bin is the path
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}
<?php

$valid = true;
$errors = array();

$contact = array(
    'name' => null,
    'email' => null,
    'message' => null
);

// Check if the form has been posted
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
    $contact = filter_input_array(INPUT_POST, array(
        'name'   => FILTER_SANITIZE_STRING,
        'email'   => FILTER_SANITIZE_STRING,
        'message'   => FILTER_SANITIZE_STRING,
    ), true);
    if (empty($contact['name'])) {
        $valid = false;
        $errors['name'] = "You must enter your name.";
    }
    if (empty($contact['email'])) {
        $valid = false;
        $errors['email'] = "You must enter your email address.";
    } elseif (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)) {
        $valid = false;
        $errors['email'] = "You must enter a valid email address.";
    }
    if (empty($contact['message'])) {
        $valid = false;
        $errors['message'] = "You must enter a message.";
    }
    if ($valid) {
        // The email address the email will be sent to
        $to = "business@example.com";
        // The email subject
        $subject = "Contact Form Submission";
        // Set the from and reply-to address for the email
        $headers = "From: website@example.com\r\n"
                 . "Reply-To: " . $contact['email'] . "\r\n"
                 . "X-Mailer: PHP/" . phpversion();
        // Build the body of the email
        $mailbody = "The contact form has been filled out.\n\n"
                  . "Name: " . $contact['name'] . "\n"
                  . "Email: " . $contact['email'] . "\n"
                  . "Message:\n" . $contact['message'];
        // Send the email
        mail($to, $subject, $mailbody, $headers);
        // Go to the thank you page
        header("location: thankyou.html");
        exit;
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Contact Us</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <form action="contact.php" method="post" accept-charset="utf-8">
        <fieldset>
            <legend>Contact Us</legend>
            <?php if (!$valid): ?>
                <div class="error">
                    <?php foreach($errors as $message):?>
                        <div><?php echo htmlspecialchars($message); ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <div class="row">
                <label for="name">Name: </label>
                <input id="name" type="text" name="name" value="<?php echo htmlspecialchars($contact['name']);?>">
            </div>
            <div class="row">
                <label for="email">Email Address: </label>
                <input id="email" type="text" name="email" value="<?php echo htmlspecialchars($contact['email']);?>">
            </div>
            <div class="row">
                <label for="message">Message:</label>
                <textarea id="message" name="message"><?php echo htmlspecialchars($contact['message']);?></textarea>
            </div>
            <div class="row">
                <input type="submit" value="Submit">
            </div>
        </fieldset>
    </form>
</body>
</html>
define("MAX_GEN",5);

function detail($number) {
    $d = mysql_query("select * from table where number = '$number'");
    if(mysql_num_rows($d) == 0) {
        $p[name] = "N/A";
        $p[number] = "N/A";
        $p[m_number] = "N/A";
        $p[f_number] = "N/A";
    }
    else $p = mysql_fetch_assoc($d);
    return $p;
}

function gen($number, $generation = 0, $out) {

    if ($generation >= MAX_GEN) {
        return false;
    }

    $record = detail($number);

    if ($generation == 0) $out[0][] = $record; // first man

    $generation++; // next generation

    if (!$out[$generation] && ($generation != MAX_GEN)) $out[$generation] = array();

    $x_mother = gen($record[m_number], $generation ); // continue with mother
    $x_father = gen($record[f_number], $generation ); // continue with father

    if ($out[$generation]) {
        $out[$generation][] = $x_mother;
        $out[$generation][] = $x_father;
    }
    return $out;
}
$oneDimensionalArray = array_map('current', $twoDimensionalArray);

/*
current() function returns the value of the current element in an array. for ex : $fruits = array("banana", "apple", "orange"); echo current($fruits) //will return "banana" since current pointer is on index 0 which is banana
*/
<?php
	$dbc = mysqli_connect('localhost', 'root', '');	//connect database
	mysqli_select_db($dbc, 'news');	//select database
	
	$errorsUpdNewsArr = array();
	
	if(isset($_POST['updNewsData'])){
		$newsID = $_POST['update_id'];
		$newsTitle = $_POST['txtNewsTitle'];
		$newsDetails = $_POST['txtNewsDetails'];
		$newsCategory = $_POST['selectNewsCategory'];
		
		$targetImage = "/205CDE/Assignment/".basename($_FILES['uploadNewsImg']['name']);
		$newsImage = $_FILES['uploadNewsImg']['name'];
		$newsImageExt = pathinfo($newsImage, PATHINFO_EXTENSION);
		
		//ensure form fields are filled properly
		if(empty($newsTitle)){
			array_push($errorsUpdNewsArr, "News title is required! Please try again!");
		}
		if(empty($newsDetails)){
			array_push($errorsUpdNewsArr, "News details is required! Please try again!");
		}
		if($_FILES["uploadNewsImg"]["error"] == 4){
			//no upload image
			//uploading news image is not mandatory
		}else{
			//check uploaded image file type
			if($newsImageExt !== 'jpg' && $newsImageExt !== 'jpeg' && $newsImageExt !== 'png' && $newsImageExt !== 'jfif'){
				array_push($errorsUpdNewsArr, "Invalid news image file type! Please try again!");
			}
		}
		
		//no errors
		if(count($errorsUpdNewsArr) == 0){
			$query = "UPDATE news SET news_title='$newsTitle', news_details='$newsDetails', news_category='$newsCategory', news_image='$newsImage' WHERE news_id='$newsID'";
			
			//Move uploaded image into a folder
			if(move_uploaded_file($_FILES['name']['tmp_name'], $targetImage)){
				$msg = "Image uploaded successfully!";
				}else{
				$msg = "Image uploaded unsuccessfully!";
			}
			
			$runQuery = mysqli_query($dbc, $query);
			
			if($runQuery){
				echo '<script> alert("Data updated!"); </script>';
				header('Location: /205CDE/Assignment/manageNews.php');
				}else{
				echo '<script> alert("Data not update yet!"); </script>';
			}
			}else{
			//display error message in alert
			foreach($errorsUpdNewsArr as $errorsUpdNewsMsg){
				echo '<script type="text/javascript">alert("'.$errorsUpdNewsMsg.'");</script>'; 
			}
			
			//redirect to manageNews.php
			echo '<script type="text/javascript">window.location.href = "/205CDE/Assignment/manageNews.php";</script>'; 
		}
	}
	mysqli_close($dbc);
?>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html'); ?>
		
		<title>U Chen Daily | All News</title>
	</head>
	<style>
		@media only screen and (min-width: 893px) {
		.card-img-top{
		width: 100%;
		height: 15vw; 
		object-fit: cover;
		}
		}
		
		.card-body{
		background: #1f52a3;
		}
		
		.card-footer{
		background: #1f52a3;
		}
		
		.h5{
		color: #1f52a3;
		}
		
		.card-text{
		font-size: 12px;
		}
	</style>
	<body class="bg-light">
		<!--using external files-->
		<?php require('header.php'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">All News</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row d-flex justify-content-start" style="margin: 0 10px;">
			<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
				<div class="card" style="width: 22rem; margin: 20px 30px;">
					<img class="card-img-top" src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
					<div class="card-body">
						<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
					</div>
					<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
				</div>
				<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>		
<?php
	session_start();
	
	$errorsArr = array();
	
	if(isset($_POST['submittedLogin'])){
		$username = $_POST['usernameLogin'];
		$password = $_POST['passwordLogin'];
		
		//ensure form fields are filled properly
		if(empty($username)){
			array_push($errorsArr, "Username is required! Please try again!");
		}
		if(empty($password)){
			array_push($errorsArr, "Password is required! Please try again!");
		}
		if((!empty($username)) && (!empty($password)) && ($username != 'admin') && ($password != 'admin')){
			array_push($errorsArr, "Incorrect username or password! Please try again!");
		}
		
		//no errors
		if(count($errorsArr) == 0){
			$_SESSION['username'] = $username;
			$_SESSION['success'] = "You are now logged in!";
			header('Location: /205CDE/Assignment/manageNews.php');
		}
	}
	
	//logout
	if(isset($_GET['logout'])){
		session_destroy();
		unset($_SESSION['username']);
		header('Location: /205CDE/Assignment/home.php');
	}
?>
<div class="container-fluid" style="background: #1f52a3;">
	<div class="row">
		<div class="col-2"></div>
		<div class="col-8">
			<a href="/205CDE/Assignment/home.php"><h1 style="text-align: center; color: #e6e8eb; margin: 20px 0;">U Chen Daily</h1></a>
		</div>
		<div class="col-2 d-flex justify-content-center align-items-center">
			<?php if(isset($_SESSION['username'])){ ?>
				<a href="/205CDE/Assignment/home.php?logout='1'" class="btn btn-outline-light">LOGOUT</a>
				<?php }else{ 
				?>
				<button type="button" class="btn btn-outline-light" data-toggle="modal" data-target="#loginFormModal">
					LOGIN AS ADMIN
				</button>
			<?php } ?>
			<!--<a href="/205CDE/Assignment/manageNews.php" target="_blank" class="btn btn-outline-light">LOGIN</a>-->
		</div>
	</div>
</div>
<!--login form modal START-->
<!-- Modal -->
<div class="modal fade" id="loginFormModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalCenterTitle">Login</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form action="/205CDE/Assignment/home.php" method="post" id="loginModalForm">
				<div class="modal-body">
					<?php
						if(count($errorsArr) > 0){?>
						<div class="form-group">
							<?php
								foreach($errorsArr as $errorMsg){
									//echo "<p class=\"text-danger\">$errorMsg</p>";
									echo "<script>alert(\"$errorMsg\")</script>";
								}
							?>
						</div>
						<?php }
					?>
					<div class="form-group">
						<label for="exampleInputEmail1">Username</label>
						<input type="text" class="form-control" name="usernameLogin" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter username" value="<?php if(isset($username)){echo $username;} ?>">
					</div>
					<div class="form-group">
						<label for="exampleInputPassword1">Password</label>
						<input type="password" class="form-control" name="passwordLogin" id="exampleInputPassword1" placeholder="Enter password">
					</div>
					<br>
					<div class="form-group">
						<button type="submit" class="btn btn-lg btn-block text-light" style="background: #1f52a3;">LOGIN</button>
						<input type="hidden" name="submittedLogin">
					</div>
				</div>
				<!--<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
					<button type="button" class="btn btn-primary">Login</button>
				</div>-->
			</form>
		</div>
	</div>
</div>
<!--login form modal END-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
	<a class="navbar-brand" href="/205CDE/Assignment/home.php"><i class="fas fa-home" style="font-size: 30px; color: #1f52a3;"></i></a>
	<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
		<span class="navbar-toggler-icon"></span>
	</button>
	
	<div class="collapse navbar-collapse" id="navbarSupportedContent">
		<ul class="navbar-nav mr-auto">
			<li class="nav-item dropdown" style="margin: 0 15px;">
				<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">News</a>
				<div class="dropdown-menu" aria-labelledby="navbarDropdown">
					<?php
						$newsCategoryArr = array(
						'All', 'Nation', 'World',
						'Sport', 'Entertainment',
						);
						foreach($newsCategoryArr as $newsType){
							echo "<a class=\"dropdown-item\" href=\"/205CDE/Assignment/news$newsType.php\" target=\"_blank\">$newsType</a>";
						}
					?>
				</div>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/aboutUs.php" target="_blank">About Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/contactUs.php" target="_blank">Contact Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/faqs.php" target="_blank">FAQs</a>
			</li>
			<!-- <li class="nav-item"> -->
			<!-- <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> -->
			<!-- </li> -->
		</ul>
		<!-- <form class="form-inline my-2 my-lg-0"> -->
		<!-- <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> -->
		<!-- <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> -->
		<!-- </form> -->
	</div>
</nav>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | News</title>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.php'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">News</h3></div>
			</div>
		</div>
		<?php
			$dbc = mysqli_connect('localhost', 'root', '');
			mysqli_select_db($dbc, 'news');
			
			if(isset($_GET['id']) && is_numeric($_GET['id'])){
				$query = "SELECT * FROM news WHERE news_id={$_GET['id']}";
				
				if($r = mysqli_query($dbc, $query)){
					$row = mysqli_fetch_array($r);
				?>
				<div class="container-fluid bg-light" style="padding: 50px 20px">
					<div class="row d-flex justify-content-between" style="margin: 0 50px;">
						<div class="col-lg-8 col-md-12">
							<div class="row mb-3">
								<h2 style="color: #1f52a3;"><?php echo $row['news_title'] ?></h2>
							</div>
							<div class="row">
								<div class="col mb-3" style="font-size: 18px; color:#1f52a3;">
									<i class="far fa-clock"></i>&nbsp
									<?php echo date('d-M-Y', strtotime($row['news_datetime'])); ?>&nbsp&nbsp&nbsp
									<i class="fas fa-tag"></i>&nbsp
									<?php echo strtoupper($row['news_category']); ?>
								</div>
							</div>
							<div class="row">
								<div class="col-12"  style="margin-bottom: 10px;">
									<img class="card-img-top" src="<?php 
										if(empty($row['news_image'])){
											echo 'https://via.placeholder.com/350x250';
											}else{
											echo $row['news_image'];
										}
									?>" alt="Card image cap" style="width:80%;">
								</div>
								
							</div>
							<div class="row" style="margin: 10px 0; font-size: 20px;">
								<p class="font-weight-normal"><?php echo $row['news_details'] ?></p>
							</div>
						</div>
						<?php
						}
					}
					mysqli_close($dbc);
				?>
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC LIMIT 5';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<div class="col-lg-4 col-md-12">
					<div class="list-group list-group-flush" style="border: 2px solid #1f52a3; border-top: 0;">
						<h4 class="list-group-item text-light text-center" style="background: #1f52a3;">Top 5 Latest News</h4>
						<?php
							if($runQuery){
								foreach($runQuery as $row){?>
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>" class="list-group-item list-group-item-action" target="_blank">
									<div class="row">
										<div class="col-3">
											<img src="<?php 
												if(empty($row['news_image'])){
													echo 'https://via.placeholder.com/200x200';
													}else{
													echo $row['news_image'];
												}?>" alt="Thumbnail News Image" class="img-thumbnail">
											</div>
											<div class="col-8" style="font-size: 15px;">
												<?php echo $row['news_title']; ?>
											</div>
										</div>
									</a>	
									<?php }
									}else{
									echo "ERROR! No record found!";
								}
								mysqli_close($dbc);
							?>
						</div>
					</div>
					<!--<div class="col-3" style="">
						<img class="card-img-top" src="https://via.placeholder.com/350x200" alt="Card image cap">
					</div>-->
				</div>
			</div>
			
			
			<!--using external files-->
			<?php require('footer.html'); ?>
		</body>
	</html>	
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | FAQs</title>
	</head>
	<style>
		.card-header{
		background: #1f52a3;
		}
		.card-body{
		color: #1f52a3;
		}
		h3{
		color: #1f52a3;
		margin: 20px 0;
		}
	</style>
	<body>
		<!--using external files-->
		<?php require('header.php'); ?>
		<div class="container" style="margin: 5px 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">FAQs</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 10px 10px 50px;">
			<div class="row bg-light" style="margin: 10px 35px; font-size: 18px;">
				<div class="col-lg-6">
					<h3>General</h3>
					<div class="accordion" id="accordionExample">
						<!--first faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingOne">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
										There is something wrong with TheUChen.com.my and/or app. What should I do? (example: broken link, error page, spotted some issues)
									</button>
								</h2>
							</div>
							<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
								<div class="card-body bg-white">
									We are sorry for the inconvenience caused. Please report your issue to us and include as much information as possible.
								</div>
							</div>
						</div>
						<!--first faq END-->
						<!--second faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTwo">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
										I want to publish articles or pictures from U Chen Daily. How do I get copyright permission?
									</button>
								</h2>
							</div>
							<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Write to us and get permission. Granting or refusal of permission is at our sole and absolute discretion.
								</div>
							</div>
						</div>
						<!--second faq END-->
						<!--third faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingThree">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
										Why can I only read a limited number of articles on TheUChen.com.my and app?
									</button>
								</h2>
							</div>
							<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Effective Feb 24, 2020, we will be offering a paid digital membership for unlimited access to TheUChen.com.my and app (“Digital Access”). This will ensure that we continue to provide reliable, relevant, and compelling content while maintaining the quality of journalism that readers trust us to uphold. The membership, called U Chen Daily Digital Access, also includes personalisation features to improve your reading experience.
								</div>
							</div>
						</div>
						<!--third faq END-->
						<!--4th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFour">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
										How can I keep track of how many articles I have read?
									</button>
								</h2>
							</div>
							<div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Sorry, you can't track your article limit at the moment. We're still developing this part of the system so do bear with us while we continue to improve.
								</div>
							</div>
						</div>
						<!--4th faq END-->
						<!--5th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFive">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFive" aria-expanded="false" aria-controls="collapseFive">
										If I don’t want to register as a member, can I still read articles for free?
									</button>
								</h2>
							</div>
							<div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordionExample">
								<div class="card-body bg-white">
									As a guest user without an active paid membership, you can access a limited number of articles for free each month. This limit resets every 30 days. This excludes premium content (marked as ‘PREMIUM’), which are exclusive to paid members, and content hosted on a separate subscription-based service, e.g. dimsum e-tuition videos.
								</div>
							</div>
						</div>
						<!--5th faq END-->
						<!--6th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSix">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSix" aria-expanded="false" aria-controls="collapseSix">
										Do I need to log in with a MyUChen account if I just want to read articles for free as a guest user?
									</button>
								</h2>
							</div>
							<div id="collapseSix" class="collapse" aria-labelledby="headingSix" data-parent="#accordionExample">
								<div class="card-body bg-white">
									While it’s not compulsory, we do recommend that you sign up for a MyUChen account. As a member, you can UChent your 1-month free trial to U Chen Daily Digital Access and enjoy personalisation features to improve your reading experience.
								</div>
							</div>
						</div>
						<!--6th faq END-->
						<!--7th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSeven">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSeven" aria-expanded="false" aria-controls="collapseSeven">
										What does the paid U Chen Daily Digital Access membership entail?
									</button>
								</h2>
							</div>
							<div id="collapseSeven" class="collapse" aria-labelledby="headingSeven" data-parent="#accordionExample">
								<div class="card-body bg-white">
									With U Chen Daily Digital Access membership, you will be able to access all articles on TheUChen.com.my and app, including premium content which are exclusive to paid members, excluding content hosted on a separate subscription-based services, e.g. dimsum e-tuition videos. Members can also access all personalisation features.
								</div>
							</div>
						</div>
						<!--7th faq END-->
						<!--8th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingEight">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseEight" aria-expanded="false" aria-controls="collapseEight">
										I'm currently subscribed to ePaper. Do I still need to subscribe to U Chen Daily?
									</button>
								</h2>
							</div>
							<div id="collapseEight" class="collapse" aria-labelledby="headingEight" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Yes. At the moment U Chen Daily Digital Access and ePaper subscription are on two separate platforms.
								</div>
							</div>
						</div>
						<!--8th faq END-->
					</div>
				</div>
				<div class="col-lg-6">
					<h3>About Account</h3>
					<div class="accordion" id="accordionExample">
						<!--9th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingNine">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light" type="button" data-toggle="collapse" data-target="#collapseNine" aria-expanded="true" aria-controls="collapseNine">
										I can’t sign up/register from Internet Explorer?
									</button>
								</h2>
							</div>
							<div id="collapseNine" class="collapse show" aria-labelledby="headingNine" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Internet Explorer is not supported at the moment. Best view from Chrome browsers.
								</div>
							</div>
						</div>
						<!--9th faq END-->
						<!--10th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTen" aria-expanded="false" aria-controls="collapseTen">
										I signed up for a free MyUChen account before Feb 10, 2020 and was prompted to update my password. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseTen" class="collapse" aria-labelledby="headingTen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Please log in with your username/email and change your password with a minimum of eight characters. It must contain at least one upper case letter, one number, and one special character except '+' and '='. Please use your new password for future logins.
								</div>
							</div>
						</div>
						<!--10th faq END-->
						<!--11th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingEleven">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseEleven" aria-expanded="false" aria-controls="collapseEleven">
										Why do I have to change my password?
									</button>
								</h2>
							</div>
							<div id="collapseEleven" class="collapse" aria-labelledby="headingEleven" data-parent="#accordionExample">
								<div class="card-body bg-white">
									We've made some enhancements to the TheUChen.com.my and app to improve your reading experience and for web security. This includes migrating all MyUChen accounts to a new system. Members who signed up before Feb 10, 2020, are required to update their password.
								</div>
							</div>
						</div>
						<!--11th faq END-->
						<!--12th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTwelve">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTwelve" aria-expanded="false" aria-controls="collapseTwelve">
										I forgot my password, what should I do?
									</button>
								</h2>
							</div>
							<div id="collapseTwelve" class="collapse" aria-labelledby="headingTwelve" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Click ‘Forgot Password?’ and you will be emailed a temporary password that you can log in with. Please proceed to change your password as soon as possible.
								</div>
							</div>
						</div>
						<!--12th faq END-->
						<!--13th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingThirteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseThirteen" aria-expanded="false" aria-controls="collapseThirteen">
										I’ve updated my password, but I can’t log in with MyUChen account’s username?
									</button>
								</h2>
							</div>
							<div id="collapseThirteen" class="collapse" aria-labelledby="headingThirteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Please use the new password with your MyUChen email.
								</div>
							</div>
						</div>
						<!--13th faq END-->
						<!--14th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFourteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFourteen" aria-expanded="false" aria-controls="collapseFourteen">
										I registered for a MyUChen account but did not receive any verification email. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseFourteen" class="collapse" aria-labelledby="headingFourteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									lease check both your Inbox and/or Spam folders. Click ‘Resend verification email’ and try again. If you have closed the page or have been logged out, please log in again to click ‘Resend verification email’.
									<br>
									If you are using a corporate email, kindly inform your tech department to whitelist @theUChen.com.my.
								</div>
							</div>
						</div>
						<!--14th faq END-->
						<!--15th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFifteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFifteen" aria-expanded="false" aria-controls="collapseFifteen">
										The email verification link/code provided is invalid. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseFifteen" class="collapse" aria-labelledby="headingFifteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Click ‘Resend verification email’ and try again. If you have closed the page or have been logged out, please log in again to click ‘Resend verification email’.
								</div>
							</div>
						</div>
						<!--15th faq END-->
						<!--16th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSixteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSixteen" aria-expanded="false" aria-controls="collapseSixteen">
										I can’t seem to register. It says email address previously registered. What do I do?
									</button>
								</h2>
							</div>
							<div id="collapseSixteen" class="collapse" aria-labelledby="headingSixteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									If you have forgotten your password, click ‘Forgot Password?’ to reset it. If you are certain that you did not sign up with your email address before, kindly contact our Customer Service.
								</div>
							</div>
						</div>
						<!--16th faq END-->
					</div>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen  Daily | Contact Us</title>
	</head>
	<style>
		.google-maps {
        position: relative;
        padding-bottom: 50%;
        height: 0;
        overflow: hidden;
		}
		.google-maps iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
		}
		i {
		font-size: 50px; 
		color: #1f52a3;
		}
		h5 {
		color: #1f52a3;
		margin-top: 35px;
		}
	</style>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">Contact Us</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0px 35px;">
				<div class="col-12 google-maps">
					<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3972.4919887247825!2d100.2796820147649!3d5.341603796125226!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x304ac048a161f277%3A0x881c46d428b3162c!2sINTI%20International%20College%20Penang!5e0!3m2!1sen!2smy!4v1606047317819!5m2!1sen!2smy" width="600" height="450" frameborder="0" style="border: 2px solid #1f52a3;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
				</div>
			</div>
			<div class="row bg-light" style="margin: 35px 35px 0;">
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="far fa-envelope"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>info@uchendaily.com</h5>
					</div>
				</div>
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="fas fa-phone-alt"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>+604-577 9999</h5>
					</div>
				</div>
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="fas fa-map-marker-alt"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>1-Z, Lebuh Bukit Jambul,<br>Bukit Jambul,<br>11900 Bayan Lepas,Pulau Pinang.</h5>
					</div>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen  Daily | About Us</title>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">About Us</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0 35px;">
				<div class="col">
					<h4>U Chen  Daily</h4>
				</div>
			</div>
			<div class="row bg-light" style="margin: 10px 35px;">
				<div class="col-6">
					<p>Since its launch on June 23, 1995, as Malaysia's first news website, U Chen  Daily has always striven to provide readers with up to date breaking news, compelling content and insightful opinions.</p>
					<p>Evolving with the times, our content includes current news, business, sports, community, tech, lifestyle and world news, as well as expert analysis and dynamic videos.</p>
					<p>The website was recognised in 2014 as one of the best in Asia by the World Association of Newspapers and News Publishers (WAN-IFRA).</p>
					<p>It serves as the foundation of an online community that has a million strong following on both Twitter and Facebook.</p>
					<p>As the digital companion to U Chen  Daily newspaper, U Chen  Daily is part of a portfolio that offers content through print, U Chen  Daily ePaper and a mobile app.</p>
					<p>Readers on-the-go who want breaking news and business updates delivered to them can opt for our SMS services available via Maxis and DiGi.</p>
				</div>
				<div class="col-6">
					<p>U Chen  Daily (daily) and Sunday U Chen  are published in five editions. Two editions cover the northern peninsular states of Penang, Kedah, Perlis, Kelantan and northern Perak, while another two editions cover the rest of the country. As of March 2010, the newspaper has a separate Sarawak edition priced at RM1.20.</p>
					<p>There are two main printing plants that publish four editions of U Chen  Daily on a daily basis. The northern editions are printed at U Chen  Daily Northern Hub in Bayan Lepas, Penang, while the other two editions are printed at U Chen  Daily Media Hub in Bukit Jelutong, Shah Alam, Selangor.</p>
					<p>U Chen  Daily weekday paper is packaged as a 4-in-1 paper, comprising the Main Paper, U Chen Biz, U Chen 2 and U Chen  Metro. Naturally, this newspaper also contains classifieds.</p>
					<p>The Main Paper covers the latest in both local and international news while U Chen Biz offers a comprehensive coverage of business developments, market trends, financial reports and updates in the stock market. U Chen 2 features articles on lifestyle, entertainment, health, parenting, social etiquette, science, environment, fashion, food, comics and many more. The contents published on U Chen  Daily Metro varies by edition, covering news and events in a particular region covered by each edition.</p>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
<footer>
	<div class="container-fluid" style="background: #1f52a3; margin-top: 50px; padding: 30px;">
		<div class="row">
			<div class="col-1"></div>
			<div class="col-10 d-flex justify-content-start" style="color: #e6e8eb;">&#169; Copyright 2020 U Chen Daily. All rights reserved.</div>
			<div class="col-1"></div>
		</div>
	</div>
</footer>
<?php
	$dbc = mysqli_connect('localhost', 'root', '');	//connect database
	mysqli_select_db($dbc, 'news');	//select database
	
	$errorsAddNewsArr = array();
	
	if(isset($_POST['addNewsData'])){
		$newsTitle = trim(str_replace("'", "\'", $_POST['txtNewsTitle']));
		$newsDetails = trim(str_replace("'", "\'", $_POST['txtNewsDetails']));
		$newsCategory = $_POST['selectNewsCategory'];
		
		$targetImage = "/205CDE/Assignment/".basename($_FILES['uploadNewsImg']['name']);
		$newsImage = $_FILES['uploadNewsImg']['name'];
		
		//ensure form fields are filled properly
		if(empty($newsTitle)){
			array_push($errorsAddNewsArr, "News title is required! Please try again!");
		}
		if(empty($newsDetails)){
			array_push($errorsAddNewsArr, "News details is required! Please try again!");
		}
		if($newsCategory == 0){
			array_push($errorsAddNewsArr, "News category is required! Please try again!");
		}
		
		//no errors
		if(count($errorsAddNewsArr) == 0){
			$query = "INSERT INTO news (news_title, news_details, news_category, news_datetime, news_image) 
			VALUES ('$newsTitle', '$newsDetails', '$newsCategory', NOW(), '$newsImage')";
			
			//Move uploaded image into a folder
			if(move_uploaded_file($_FILES['name']['tmp_name'], $targetImage)){
				$msg = "Image uploaded successfully!";
				}else{
				$msg = "Image uploaded unsuccessfully!";
			}
			
			$runQuery = mysqli_query($dbc, $query);
			
			if($runQuery){
				echo '<script> alert("Data saved!"); </script>';
				header('Location: /205CDE/Assignment/manageNews.php');
				}else{
				echo '<script> alert("Data not save yet!"); </script>';
			}
		}else{
			//display error message in alert
			foreach($errorsAddNewsArr as $errorsAddNewsMsg){
				echo '<script type="text/javascript">alert("'.$errorsAddNewsMsg.'");</script>'; 
			}
			
			//redirect to manageNews.php
			echo '<script type="text/javascript">window.location.href = "/205CDE/Assignment/manageNews.php";</script>'; 
		}
	}
	mysqli_close($dbc);
?>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Admin</title>
		<script type="text/javascript">
			setTimeout(function(){ 
				document.querySelector('.close').click();
			}, 2500);
		</script>
		<!--show news info for editing START-->
		<script type="text/javascript">
			$(document).ready(function(){
				$('.btnEdit').on('click', function(){
					$('#updNewsModal').modal('show');
					
					$tr = $(this).closest('tr');
					
					var data = $tr.children("td").map(function(){
						return $(this).text();
					}).get();
					
					console.log(data);
					
					$('#update_id').val(data[0]);
					$('#news_datetime').val(data[1]);
					$('#news_title').val(data[2]);
					$('#news_details').val(data[3]);
					$('#news_category').val(data[4]);
					$('#news_image').val(data[5]);
				});
			});
		</script>
		<!--show news info for editing END-->
		
		<!--show confirmation message for deleting START-->
		<script type="text/javascript">
			$(document).ready(function(){
				$('.btnDel').on('click', function(){
					$('#delNewsModal').modal('show');
					
					$tr = $(this).closest('tr');
					
					var data = $tr.children("td").map(function(){
						return $(this).text();
					}).get();
					
					console.log(data);
					
					$('#delete_id').val(data[0]);
				});
			});
		</script>
		<!--show confirmation message for deleting END-->
		
		<!--show file name after uploading image START-->
		<script type="text/javascript">
            $(document).ready(function() {
                bsCustomFileInput.init();
			});
		</script>
		<!--show file name after uploading image END-->
		<body>
			<!--using external files-->
			<?php
				if(empty($_SESSION['username'])){
					header('Location: /205CDE/Assignment/home.php');
				}
			?>
			<?php require('header.php'); ?>
			
			<div class="container" style="margin: 20px;">
				<div class="row">
					<div class="col-sm"><h3 style="color: #1f52a3;">Manage News</h3></div>
				</div>
			</div>
			<!--add news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="addNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Add News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/insertData.php" method="post" enctype="multipart/form-data">
							<div class="modal-body">
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="inputNewsTitle" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="selectNewsCategory">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Entertainment' => 4
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group mb-3">
									<label for="inputNewsImage" class="col-form-label">News Image:</label>
									<div class="custom-file">
										<input type="file" class="custom-file-input" name="uploadNewsImg" id="customFile">
										<label class="custom-file-label" for="customFile">Choose file</label>
									</div>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="inputNewsDetails" rows="10"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="addNewsData" style="background: #1f52a3;">Add</button>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--add news modal END-->
			
			<!--edit news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="updNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Edit News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/updateData.php" method="post" enctype="multipart/form-data">
							<div class="modal-body">
								<input type="hidden" name="update_id" id="update_id">
								<div class="form-group">
									<label for="txtNewsDatetime">News Created Datetime:</label>
									<input type="text" class="form-control" name="txtNewsDatetime" id="news_datetime" aria-describedby="emailHelp" placeholder="Enter news datetime" disabled>
								</div>
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="news_title" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="news_category">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Entertainment' => 4
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group mb-3">
									<label for="inputNewsImage" class="col-form-label">News Image:</label>
									<div class="custom-file">
										<input type="file" class="custom-file-input" name="uploadNewsImg" id="news_image">
										<label class="custom-file-label" for="news_image"></label>
									</div>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="news_details" rows="10"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="updNewsData" style="background: #1f52a3;">Edit</button>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--edit news modal END-->
			
			<!--delete news modal START-->
			<!-- Modal -->
			<div class="modal fade" id="delNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered" role="document">
					<div class="modal-content">
						<form action="/205CDE/Assignment/deleteData.php" method="post">
							<div class="modal-body">
								<input type="hidden" name="delete_id" id="delete_id">
								<div class="d-flex justify-content-center" style="margin: 25px 0;">
									<i class="fas fa-times-circle text-danger" style="font-size: 100px;"></i>
								</div>
								<div class="d-flex justify-content-center">
									<h4>Are you sure?</h4>
								</div>
								<div class="d-flex justify-content-center">
									<p class="col-1"></p>
									<p class="col-10" style="text-align: center;">Do you really want to delete this record?<br>This process cannot be undone.</p>
									<p class="col-1"></p>
								</div>
								<div class="row justify-content-around" style="margin: 15px 0;">
									<div class="col-6 d-flex justify-content-end">
										<button type="button" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button>
									</div>
									<div class="col-6 d-flex justify-content-start">
										<button type="submit" class="btn btn-danger btn-lg" name="delNewsData">Delete</button>
									</div>
									<input type="hidden" name="delSubmitted" value="true"/>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--delete news modal END-->
			
			<div class="container-fluid bg-light" style="padding: 30px 10px;">
				<div class="row bg-light" style="margin: 0 35px;">
					<div class="col-6">
						<h5>All News</h5>
					</div>
					<div class="col-6 d-flex justify-content-end">
						<button type="button" class="btn btn-primary" style="background: #1f52a3;" data-toggle="modal" data-target="#addNewsModal"><i class="fas fa-plus" style="font-size: 20px;"></i> Add News</button>
					</div>
				</div>
				<!--add news alert START-->
				<div class="row bg-light" style="margin: 15px 35px;" id="addNewsAlert">
					<div class="col-12">
						<div class="alert alert-success alert-dismissible fade show" role="alert" >
							<strong>Success!</strong> The news is added successfully!
							<button type="button" class="close" data-dismiss="alert" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>
						</div>
					</div>
				</div>
				<!--add news alert END-->
				
				<!--news table START-->
				<div class="card-deck" style="margin: 15px 50px;">
					<?php
						$dbc = mysqli_connect('localhost', 'root', '');	//connect database
						mysqli_select_db($dbc, 'news');	//select database
						
						$query = 'SELECT * FROM news ORDER BY news_datetime DESC';
						$runQuery = mysqli_query($dbc, $query);
					?>
					<table class="table table-hover bg-light" id="manageNewsTable">
						<thead class="thead-light">
							<tr>
								<th scope="col">News ID</th>
								<th scope="col">News Created Datetime</th>
								<th scope="col">News Title</th>
								<th scope="col">News Details</th>
								<th scope="col">News Category</th>
								<th scope="col">News Image</th>
								<th scope="col">Edit/Delete</th>
							</tr>
						</thead>
						<?php
							if($runQuery){
								foreach($runQuery as $row){
								?>
								<tbody>
									<tr>
										<td><?php echo $row['news_id']; ?></td>
										<td><small><?php echo $row['news_datetime'];?></small></td>
										<td><?php echo $row['news_title']; ?></td>
										<td><?php echo $row['news_details']; ?></td>
										<td><?php echo $row['news_category']; ?></td>
										<td>
											<a href="<?php 
												if(empty($row['news_image'])){
													echo 'https://via.placeholder.com/200x200';
													}else{
													echo '/205CDE/Assignment/'.$row['news_image'];
												} ?>" target="_blank">
												<img src="<?php 
													if(empty($row['news_image'])){
														echo 'https://via.placeholder.com/200x200';
														}else{
														echo $row['news_image'];
													}?>" alt="Thumbnail News Image" class="img-thumbnail">
											</a>
										</td>
										<td>
											<button type="button" class="btn btn-info btnEdit"><i class="fas fa-edit" style="font-size: 14px;"></i></button>
											<button type="button" class="btn btn-danger btnDel"><i class="fas fa-trash" style="font-size: 14px;"></i></button>
										</td>
									</tr>
								</tbody>
								<?php
								}
								}else{
								echo "ERROR! No record found!";
							}
							mysqli_close($dbc);
						?>
					</table>
				</div>
				<!--news table END-->
			</div>
			<!--using external files-->
			<?php require('footer.html'); ?>
		</body>
	</html>																				
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Admin</title>
		<script>
			
		</script>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">Manage News</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0 35px;">
				<div class="col-6">
					<h5>All News</h5>
				</div>
				<div class="col-6 d-flex justify-content-end">
					<button type="button" class="btn btn-primary" style="background: #1f52a3;" data-toggle="modal" data-target="#addNewsModal"><i class="fas fa-plus" style="font-size: 20px;"></i> Add News</button>
				</div>
			</div>
			
			<!--add news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="addNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Add News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/admin.php" method="post">
							<div class="modal-body">
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="inputNewsTitle" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="selectNewsCategory">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Lifestyle' => 4,
											'Food' => 5,	'Tech' => 6,
											'Education' => 7
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="inputNewsDetails" rows="10"></textarea>
								</div>
								
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="btnAddNews" style="background: #1f52a3;">Add</button>
								<input type="hidden" name="submitted" value="true"/>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--add news modal END-->
			<!--connect & insert news into database START-->
			<?php			
				if (isset($_POST['submitted'])){
					//connect database
					$dbc = mysqli_connect('localhost', 'root', '');
					//select database
					mysqli_select_db($dbc, 'news');
					
					$problem = FALSE;
					
					if(!empty($_POST['txtNewsTitle']) && !empty($_POST['selectNewsCategory']) && !empty($_POST['txtNewsDetails'])){
						$newsTitle = trim($_POST['txtNewsTitle']);
						$newsDetails = trim($_POST['txtNewsDetails']);
						$newsCategory = trim($_POST['selectNewsCategory']);
						}else{
						echo '<p>Error! Please enter title and details select category!</p>';
						$problem = TRUE;
					}
					
					if(!$problem){
						$query = "INSERT INTO news (news_title, news_details, news_category, news_datetime) 
						VALUES ('$newsTitle', '$newsDetails', '$newsCategory', NOW())";
						if(mysqli_query($dbc, $query)){
							echo '<p>Added successfully!</p>';
							}else{
							echo '<p>Error! '.mysqli_error($dbc).'</p>';
							echo '<p>Query: '.$query.'</p>';
						}
					}
					mysqli_close($dbc);
				}
			?>
			<!--connect & insert news into database END-->
			<!--news table START-->
			<div class="card-deck" style="margin: 15px 50px;">
				<table class="table table-hover bg-light">
					<thead class="thead-light">
						<tr>
							<th scope="col">News ID</th>
							<th scope="col">News Datetime</th>
							<th scope="col">News Title</th>
							<th scope="col">News Details</th>
							<th scope="col">News Category</th>
							<th scope="col">Edit/Delete</th>
						</tr>
					</thead>
					<tbody>
						<!--select news from database START-->
						<?php
							$dbc = mysqli_connect('localhost', 'root', '');
							mysqli_select_db($dbc, 'news');
							
							$query = 'SELECT * FROM news ORDER BY news_id ASC';
							
							if($r = mysqli_query($dbc, $query)){
								while($row = mysqli_fetch_array($r)){
									echo "<tr>
									<th scope=\"row\">{$row['news_id']}</th>
									<td>{$row['news_datetime']}</td>
									<td>{$row['news_title']}</td>
									<td>{$row['news_details']}</td>
									<td>{$row['news_category']}</td>
									<td>
									<button type=\"button\" class=\"btn btn-info\"><i class=\"fas fa-edit\" style=\"font-size: 20px;\"></i></button>
									<button type=\"button\" class=\"btn btn-danger\"><i class=\"fas fa-trash\" style=\"font-size: 20px;\"></i></button>
									</td>
									</tr>";
								}
								}else{
								echo '<p>Error! '.mysqli_error($dbc).'</p>';
							}
							
							mysqli_close($dbc);
						?>
						<!--select news from database END-->
					</tbody>
				</table>
			</div>
			<!--news table END-->
		</div>
	</body>
</html>
<?php

// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
mysqli_set_charset($link,'utf8');

// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;

// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));

// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}

// create SQL based on HTTP method
switch ($method) {
  case 'GET':
    $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  case 'PUT':
    $sql = "update `$table` set $set where id=$key"; break;
  case 'POST':
    $sql = "insert into `$table` set $set"; break;
  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;
}

// excecute SQL statement
$result = mysqli_query($link,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error());
}

// print results, insert id or affected row count
if ($method == 'GET') {
  if (!$key) echo '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$key) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($link);
} else {
  echo mysqli_affected_rows($link);
}

// close mysql connection
mysqli_close($link);
add_action('wp_head', 'add_gtm');

function add_gtm() {
	?>
	{{INSERT SCRIPT HERE}}
<?php
}

add_action( 'wp_body_open', 'add_gtm_no_script' );

function add_gtm_no_script() {
	?>
	{{INSERT SCRIPT HERE}}
<?php
}
get_posts(array(
    'post_type' => 'quotes',
    'tax_query' => array(
        // get_the_terms() stuff.
    ),
    'order' => 'ASC',
    'posts_per_page' => 5,
    'orderby' => 'rand')
);
?>
function my_error_handler()
{
  $last_error = error_get_last();
  if ($last_error && $last_error['type']==E_ERROR)
      {
        header("HTTP/1.1 500 Internal Server Error");
        echo '...';//html for 500 page
      }
}
register_shutdown_function('my_error_handler');
error_reporting(E_ALL);
ini_set('display_errors', 'on');

function fatal_error_handler($buffer) {
    header('HTTP/1.1 500 Internal Server Error');
    exit(0);
}

function handle_error ($errno, $errstr, $errfile, $errline){
    header('HTTP/1.1 500 Internal Server Error');
    exit(0);
}

ob_start("fatal_error_handler");
set_error_handler("handle_error");

//would normally cause a fatal error, but instead our output handler will be called allowing us to handle the error.
somefunction();
ob_end_flush();
if (!isset($_COOKIE["//cookie//"])){
	...
}
$sgbd=new mysqli("localhost", $user, $pass, "productos");
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
    echo "Connection successful";
}
// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();
	function qzr_page_target_meta_box( $post) {
		$qzr_targets = get_terms([
			'taxonomy' => 'qzr_target',
			'hide_empty' => false,
		]);

		$current_targets = get_the_terms($post->ID,'qzr_target');

		if(is_array($current_targets)) {
			$current_term_slug = count($current_targets) > 1? 'all' : $current_targets[0]->slug;
		}
		else {
			$current_term_slug = false;
		}
	?>
		<select name="qzr_target" class="qzr_target">
			<?= !$current_term_slug ? '<option selected disabled>Seleziona un target</option>' : '' ?>
			<?php foreach($qzr_targets as $target): ?>
				<option value="<?= $target->slug?>" <?= $target->slug == $current_term_slug? 'selected' : '' ?>>
				<?= $target->name?>
			</option>	
			<?php endforeach?>
		</select>
		<?php
	}

	function qzr_save_target_meta( $post_id ){
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		return $post_id;
		if(isset($_POST['qzr_target'])) {
			if($_POST['qzr_target'] == 'all') {
				$qzr_targets = get_terms([
					'taxonomy' => 'qzr_target',
					'hide_empty' => false,
				]);
				$all_targets = [];

				foreach($qzr_targets as $target) {
					array_push($all_targets,$target->term_id);
				}
				wp_set_post_terms( $post_id, $all_targets, 'qzr_target' );	
			}
			else {
				$term = get_term_by( 'slug',$_POST['qzr_target'], 'qzr_target' );
				if($term->term_id > 0) {
					wp_set_post_terms( $post_id, array( $term->term_id ), 'qzr_target' );
				}
			}
		}
	}
	add_action( 'save_post', 'qzr_save_target_meta', 10, 2 );

	function qzr_post_target_meta() {
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','page','side','high' );
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','post','side','high' );
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','project','side','high' );
	}
	add_action( 'admin_init', 'qzr_post_target_meta' );
foreach($array as $key => $element) {
    if ($key === array_key_first($array))
        echo 'FIRST ELEMENT!';

    if ($key === array_key_last($array))
        echo 'LAST ELEMENT!';
}
<nav x-data="{ open: false }" class="bg-white border-b border-gray-100">
    <!-- Primary Navigation Menu -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
            <div class="flex">
                <!-- Logo -->
                <div class="flex-shrink-0 flex items-center">
                    <a href="{{ route('dashboard') }}">
                        <x-jet-application-mark class="block h-9 w-auto" />
                    </a>
                </div>

                <!-- Navigation Links -->
                <div class=" space-x-8 sm:-my-px sm:ml-10 sm:flex">
                    <x-jet-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                        {{ __('Dashboard') }}
                    </x-jet-nav-link>
                </div>
            </div>

            <!-- Settings Dropdown -->
            <div class=" sm:flex sm:items-center sm:ml-6">
                <x-jet-dropdown align="right" width="48">
                    <x-slot name="trigger">
                         @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())
                            <button class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition duration-150 ease-in-out">
                                <img class="h-8 w-8 rounded-full object-cover" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                            </button>
                         @else
                            <button class="flex items-center text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out">
                                <div>{{ Auth::user()->name }}</div>

                                <div class="ml-1">
                                    <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </div>
                            </button>
                        @endif
                    </x-slot>

                    <x-slot name="content">
                        <!-- Account Management -->
                        <div class="block px-4 py-2 text-xs text-gray-400">
                            {{ __('Manage Account') }}
                        </div>

                        <x-jet-dropdown-link href="{{ route('profile.show') }}">
                            {{ __('Profile') }}
                        </x-jet-dropdown-link>

                        @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                            <x-jet-dropdown-link href="{{ route('api-tokens.index') }}">
                                {{ __('API Tokens') }}
                            </x-jet-dropdown-link>
                        @endif

                        <div class="border-t border-gray-100"></div>

                        <!-- Team Management -->
                        @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())
                            <div class="block px-4 py-2 text-xs text-gray-400">
                                {{ __('Manage Team') }}
                            </div>

                            <!-- Team Settings -->
                            <x-jet-dropdown-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}">
                                {{ __('Team Settings') }}
                            </x-jet-dropdown-link>

                            @can('create', Laravel\Jetstream\Jetstream::newTeamModel())
                                <x-jet-dropdown-link href="{{ route('teams.create') }}">
                                    {{ __('Create New Team') }}
                                </x-jet-dropdown-link>
                            @endcan

                            <div class="border-t border-gray-100"></div>

                            <!-- Team Switcher -->
                            <div class="block px-4 py-2 text-xs text-gray-400">
                                {{ __('Switch Teams') }}
                            </div>

                            @foreach (Auth::user()->allTeams() as $team)
                                <x-jet-switchable-team :team="$team" />
                            @endforeach

                            <div class="border-t border-gray-100"></div>
                        @endif

                        <!-- Authentication -->
                        <form method="POST" action="{{ route('logout') }}">
                            @csrf

                            <x-jet-dropdown-link href="{{ route('logout') }}"
                                                onclick="event.preventDefault();
                                                            this.closest('form').submit();">
                                {{ __('Logout') }}
                            </x-jet-dropdown-link>
                        </form>
                    </x-slot>
                </x-jet-dropdown>
            </div>

            <!-- Hamburger -->
            <div class="-mr-2 flex items-center sm:hidden">
                <button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out">
                    <svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
                        <path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        <path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
        </div>
    </div>

    <!-- Responsive Navigation Menu -->
    <div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
        <div class="pt-2 pb-3 space-y-1">
            <x-jet-responsive-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                {{ __('Dashboard') }}
            </x-jet-responsive-nav-link>
        </div>

        <!-- Responsive Settings Options -->
        <div class="pt-4 pb-1 border-t border-gray-200">
            <div class="flex items-center px-4">
                <div class="flex-shrink-0">
                    <img class="h-10 w-10 rounded-full" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                </div>

                <div class="ml-3">
                    <div class="font-medium text-base text-gray-800">{{ Auth::user()->name }}</div>
                    <div class="font-medium text-sm text-gray-500">{{ Auth::user()->email }}</div>
                </div>
            </div>

            <div class="mt-3 space-y-1">
                <!-- Account Management -->
                <x-jet-responsive-nav-link href="{{ route('profile.show') }}" :active="request()->routeIs('profile.show')">
                    {{ __('Profile') }}
                </x-jet-responsive-nav-link>

                @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                    <x-jet-responsive-nav-link href="{{ route('api-tokens.index') }}" :active="request()->routeIs('api-tokens.index')">
                        {{ __('API Tokens') }}
                    </x-jet-responsive-nav-link>
                @endif

                <!-- Authentication -->
                <form method="POST" action="{{ route('logout') }}">
                    @csrf

                    <x-jet-responsive-nav-link href="{{ route('logout') }}"
                                    onclick="event.preventDefault();
                                                this.closest('form').submit();">
                        {{ __('Logout') }}
                    </x-jet-responsive-nav-link>
                </form>

                <!-- Team Management -->
                @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())
                    <div class="border-t border-gray-200"></div>

                    <div class="block px-4 py-2 text-xs text-gray-400">
                        {{ __('Manage Team') }}
                    </div>

                    <!-- Team Settings -->
                    <x-jet-responsive-nav-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}" :active="request()->routeIs('teams.show')">
                        {{ __('Team Settings') }}
                    </x-jet-responsive-nav-link>

                    <x-jet-responsive-nav-link href="{{ route('teams.create') }}" :active="request()->routeIs('teams.create')">
                        {{ __('Create New Team') }}
                    </x-jet-responsive-nav-link>

                    <div class="border-t border-gray-200"></div>

                    <!-- Team Switcher -->
                    <div class="block px-4 py-2 text-xs text-gray-400">
                        {{ __('Switch Teams') }}
                    </div>

                    @foreach (Auth::user()->allTeams() as $team)
                        <x-jet-switchable-team :team="$team" component="jet-responsive-nav-link" />
                    @endforeach
                @endif
            </div>
        </div>
    </div>
</nav>
"repositories": {
        "webdevmatics/jetstream" : {
            "type": "path",
            "url": "C:\\laragon\\www\\codegenerator\\packages/webdevmatics/jetstream"
        }
    }
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Home</title>
	</head>
	<style>
		@media only screen and (min-width: 893px) {
		.card-img-top{
		width: 100%;
		height: 15vw; 
		object-fit: cover;
		}
		}
		
		.card-body{
		background: #1f52a3;
		}
		
		.card-footer{
		background: #1f52a3;
		}
		
		.h5{
		color: #1f52a3;
		}
		
		.card-text{
		font-size: 12px;
		}
	</style>
	<body class="bg-light">
		<!--using external files-->
		<?php require('header.php'); ?>
		<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
			<ol class="carousel-indicators">
				<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
			</ol>
			<div class="carousel-inner">
				<div class="carousel-item active">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>First slide label</h5>
						<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Second slide label</h5>
						<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Third slide label</h5>
						<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
					</div>
				</div>
			</div>
			<a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
				<span class="carousel-control-prev-icon" aria-hidden="true"></span>
				<span class="sr-only">Previous</span>
			</a>
			<a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
				<span class="carousel-control-next-icon" aria-hidden="true"></span>
				<span class="sr-only">Next</span>
			</a>
		</div>
		<!--4 latest news START-->
		<div class="container-fluid bg-light" style="padding: 40px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-6">
					<h5 style="color: #1f52a3;">Latest News</h5>
				</div>
				
				<div class="col-6 d-flex justify-content-end">
					<a href="" class="btn btn-link font-weight-bold" style="color: #1f52a3;">MORE NEWS <i class="fas fa-angle-double-right" style="font-size: 18px;"></i></a>
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 latest news END-->
		<!--4 nation news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Nation News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Nation" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php	
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 nation news END-->
		<!--4 world news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">World News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="World" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 world news END-->
		<!--4 entertainment news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0; margin-bottom: 40px;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Entertainment News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Entertainment" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 entertainment news END-->
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>				
function add_file_types_to_uploads($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_action('upload_mimes', 'add_file_types_to_uploads');
$query = new ProductSearchQuery();
        $query
            ->setQueryType('prices-drop')
            ->setSortOrder(new SortOrder('product', 'name', 'asc'));

        return $query;
$table = $html->find('table', 0); // ID LOCK IE TABLE 0 (first table) Get the first table ??
foreach($table ->find('tr') as $tr) {     // Foreach row in the table!
    if($td = $tr->find('td', 0)) {
        $Ex_Date = $td->plaintext; // Find the first TD (starts with 0)
        // ... and so on for each variable
  $(document).ready(function() {

        $('#check').on('submit', function(e) {
            e.preventDefault();

            $('#sub').prop('disable', true)
            $('#sub').text('Checking');
            $.ajax({
                url: '/home/checkorderstatus',
                method: 'POST',
                contentType: false,
                processData: false,
                cache: false,
                data: new FormData(this),
                success: function(data) {
                    $('#success').slideDown('slow').html(data);

                }
            });


            $(document).ajaxComplete(function() {
                $('#sub').prop('disabled', false)
                $('#sub').html('<i class="fa fa-search"></i>')
                $('#check').trigger("reset");
            })

            setTimeout(function() {
                $('#success').hide('slow')
            }, 3000)
        })


    })
<?php

add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');

function my_theme_enqueue_styles()
{
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
    wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style'));
    wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/path/to/script.js', '', '', true );
}
       $pic = $this->request->getFile('image');
            if ($pic->isValid()) {
                //let set the rules
                $profile_pic = [
                    'photo' => [
                        'label' => 'Image', 'rules' => 'uploaded[image]|max_size[image,2048]|is_image[image]',
                        'errors' => [
                            'max_size' => 'The uploaded image not accepted',
                            'is_image' => 'Image format not accepted'
                        ]
                    ]
                ];

                //now let validate the picture
                if (!$this->validate($profile_pic)) {
                    //let store the error here
                    $errors = array(
                        'error' => $validation->listErrors('error_msg')
                    );
                    //show the error
                    session()->setFlashdata($errors);
                    return redirect()->back()->withInput();
                } else {
                    //this is to get random
                    $name = $pic->getRandomName();
                    $pic->move('./assets/images/blog/', $name);
                }
$ip =   "127.0.0.1";
exec("ping -n 3 $ip", $output, $status);
print_r($output);
function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            yield $value;
        }
    }
}

// Usage
foreach (recursiveFind($haystack, $needle) as $value) {
    // Use `$value` here
}
function replace_accents($str) {
   $str = htmlentities($str, ENT_COMPAT, "UTF-8");
   $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/','$1',$str);
   return html_entity_decode($str);
}
function extract_emails_from($string) {
         preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
         return $matches[0];
}
<?php

  $var1 = 'nameOfVariable';

  $nameOfVariable = 'This is the value I want!';

  echo $$var1; 

?>
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'];
}
<?php 
  
function startsWith($string, $startString) { 
  $len = strlen($startString); 
  return (substr($string, 0, $len) === $startString); 
} 

// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // false

?> 
SELECT * FROM tableName WHERE timeColumn > UNIX_TIMESTAMP( date_sub(now(),interval 1 week)) and UserName = 'givenUserName'
<?php
/**
 * Titlebar template.
 *
 * @author     ThemeFusion
 * @copyright  (c) Copyright by ThemeFusion
 * @link       https://theme-fusion.com
 * @package    Avada
 * @subpackage Core
 */

// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}
?>
<?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class="fusion-page-title-bar fusion-page-title-bar-<?php echo esc_attr( $content_type ); ?> fusion-page-title-bar-<?php echo esc_attr( $alignment ); ?>" style="background: url('<?php echo $backgroundImg[0]; ?>') no-repeat center center; ">
	<div class="fusion-page-title-row">
		<div class="fusion-page-title-wrapper">
			<div class="fusion-page-title-captions">

				<?php if ( $title ) : ?>
					<?php // Add entry-title for rich snippets. ?>
					<?php $entry_title_class = ( Avada()->settings->get( 'disable_date_rich_snippet_pages' ) && Avada()->settings->get( 'disable_rich_snippet_title' ) ) ? 'entry-title' : ''; ?>
					<h1 class="<?php echo esc_attr( $entry_title_class ); ?>"><?php echo $title; // phpcs:ignore WordPress.Security.EscapeOutput ?></h1>

					<?php if ( $subtitle ) : ?>
						<h3><?php echo $subtitle; // phpcs:ignore WordPress.Security.EscapeOutput ?></h3>
					<?php endif; ?>
				<?php endif; ?>

				<?php if ( 'center' === $alignment ) : // Render secondary content on center layout. ?>
					<?php if ( 'none' !== fusion_get_option( 'page_title_bar_bs' ) ) : ?>
						<div class="fusion-page-title-secondary">
							<?php echo $secondary_content; // phpcs:ignore WordPress.Security.EscapeOutput ?>
						</div>
					<?php endif; ?>
				<?php endif; ?>

			</div>

			<?php if ( 'center' !== $alignment ) : // Render secondary content on left/right layout. ?>
				<?php if ( 'none' !== fusion_get_option( 'page_title_bar_bs' ) ) : ?>
					<div class="fusion-page-title-secondary">
						<?php echo $secondary_content; // phpcs:ignore WordPress.Security.EscapeOutput ?>
					</div>
				<?php endif; ?>
			<?php endif; ?>

		</div>
	</div>
</div>
<!DOCTYPE html>
<html>

<head>
    <title>My MySQL Form</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
</head>

<body>
<?php

require 'helpers/connect.php';
$form = "<form>";

$result = $conn->query("describe codewalldb.people");

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        if ($row["Field"] != "id") {
            $form .= "<div class='form-group'>";
            $form .= "<label for='" . $row["Field"] . "'>" . $row["Field"] . "</label> <input type='text' class='form-control' name='" . $row["Field"] . "' >";
            $form .= "</div>";
        }
    }
    $form .= "<input type='submit' value='Submit'></form>";
}

echo $form;
?>

</body>

</html>
Copy
$servername = "localhost";
$username = "codewall";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
Copy
add_action( 'wp_enqueue_scripts', function() { wp_dequeue_style( 'font-awesome' ); }, 50 );
add_action( 'elementor/frontend/after_enqueue_styles', function () { wp_dequeue_style( 'font-awesome' ); } );
/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options -> Reading
  // Return the number of products you wanna show per page.
  $cols = 9;
  return $cols;
}
<?php 
    
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    
?>
<?php
  $gravatar_link = 'http://www.gravatar.com/avatar/' . md5($comment_author_email) . '?s=32';
   echo '<img src="' . $gravatar_link . '" />';
?>
function replace_accents($str) {
   $str = htmlentities($str, ENT_COMPAT, "UTF-8");
   $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/','$1',$str);
   return html_entity_decode($str);
}
<?php 
  
function startsWith($string, $startString) { 
  $len = strlen($startString); 
  return (substr($string, 0, $len) === $startString); 
} 

// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // false

?> 
function encrypt($key, $plain, $salt = null)
    {
        echo $key;
    $plain = serialize(array( $plain, $salt ));

    $crypt = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    if (false !== stripos(PHP_OS, 'win') and 
        version_compare(PHP_VERSION, '5.3.0')  == -1) 
    {
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($crypt), MCRYPT_RAND);    
    }
    else
    {
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($crypt), MCRYPT_DEV_URANDOM);
    }

    $ks = mcrypt_enc_get_key_size($crypt);

    $key = substr(md5($key), 0, $ks);
    echo strlen($key);
    mcrypt_generic_init($crypt, $key, $iv);
    $encrypted = base64_encode($iv . mcrypt_generic($crypt, $plain));
    mcrypt_generic_deinit($crypt);
    mcrypt_module_close($crypt);

    return $encrypted;
}
<?php
  $gravatar_link = 'http://www.gravatar.com/avatar/' . md5($comment_author_email) . '?s=32';
   echo '<img src="' . $gravatar_link . '" />';
?>
function startsWith($string, $startString) {
  return strncmp($string, $startString, strlen($startString)) === 0;
}
<?php

add_filter( 'gettext', 'woocommerce_rename_coupon_field_on_cart', 10, 3 );
add_filter( 'gettext', 'woocommerce_rename_coupon_field_on_cart', 10, 3 );
add_filter('woocommerce_coupon_error', 'rename_coupon_label', 10, 3);
add_filter('woocommerce_coupon_message', 'rename_coupon_label', 10, 3);
add_filter('woocommerce_cart_totals_coupon_label', 'rename_coupon_label',10, 1);
add_filter( 'woocommerce_checkout_coupon_message', 'woocommerce_rename_coupon_message_on_checkout' );


function woocommerce_rename_coupon_field_on_cart( $translated_text, $text, $text_domain ) {
	// bail if not modifying frontend woocommerce text
	if ( is_admin() || 'woocommerce' !== $text_domain ) {
		return $translated_text;
	}
	if ( 'Coupon:' === $text ) {
		$translated_text = 'Voucher:';
	}

	if ('Coupon has been removed.' === $text){
		$translated_text = 'Voucher has been removed.';
	}

	if ( 'Apply coupon' === $text ) {
		$translated_text = 'Apply voucher';
	}

	if ( 'Coupon code' === $text ) {
		$translated_text = 'Voucher';
	
	} 

	return $translated_text;
}


// rename the "Have a Coupon?" message on the checkout page
function woocommerce_rename_coupon_message_on_checkout() {
	return 'Have a voucher?' . ' ' . __( 'Enter your voucher code', 'woocommerce' ) . '';
}


function rename_coupon_label($err, $err_code=null, $something=null){

	$err = str_ireplace("Coupon","Voucher ",$err);

	return $err;
}

?>
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';

// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
  // extract it to the path we determined above
  $zip->extractTo($path);
  $zip->close();
  echo "WOOT! $file extracted to $path";
} else {
  echo "Doh! I couldn't open $file";
}
DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete();
}, 5);
<?php
/**
 * Template Name: Archive Album
 * Album Post type archive page.
 * *
 * @package Avada
 * @subpackage Templates
 */

// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}
?>
<?php get_header(); ?>
<section id="content" <?php Avada()->layout->add_class( 'content_class' ); ?> <?php Avada()->layout->add_style( 'content_style' ); ?>>
	<?php if ( category_description( 'album' ) ) : ?>
		<div id="post-<?php the_ID(); ?>" <?php post_class( 'fusion-archive-description' ); ?>>
			<div class="post-content">
				<?php echo category_description(); ?>
			</div>
		</div>
	<?php endif; ?>

	<?php get_template_part( 'templates/blog', 'layout' ); ?>
</section>
<?php do_action( 'avada_after_content' ); ?>
<?php
get_footer();

/* Omit closing PHP tag to avoid "Headers already sent" issues. */
/**
 * Add Album post type
 * 
 */
function create_posttype() {
 
    register_post_type( 'album',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'album' ),
                'singular_name' => __( 'album' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'album'),
        )
    );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );

/**
 * Show Album post type with Blog pages
 * 
 */
add_filter( 'pre_get_posts', 'my_get_posts' );

function my_get_posts( $query ) {

	if ( is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', 'album') );

	return $query;
}
UPDATE TABLE_NAME
SET COL_NAME = REPLACE(COL_NAME, 'OLD_URL/', 'NEW_URL/') where 1
add_filter( 'woocommerce_available_payment_gateways', 'conditionally_disable_cod_payment_method', 10, 1);
function conditionally_disable_cod_payment_method( $gateways ){
    // HERE define your Products IDs
    $products_ids = array(2880);

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ){
        // Compatibility with WC 3+
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if (in_array( $cart_item['product_id'], $products_ids ) ){
            unset($gateways['cod']);
            break; // As "COD" is removed we stop the loop
        }
    }
    return $gateways;
}
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');
<?php 
function count_num_finger( $n ) 
{ 
	$r = $n % 8; 
	if ($r == 1) 
		return $r; 
	if ($r == 5) 
		return $r; 
	if ($r == 0 or $r == 2) 
		return 2; 
	if ($r == 3 or $r == 7) 
		return 3; 
	if ($r == 4 or $r == 6) 
		return 4; 
}	 

// Driver Code 
$n = 30; 
echo(count_num_finger($n)); 
 
?> 
<?php 
// PHP program to find nth 
// magic number 

// Function to find nth 
// magic number 
function nthMagicNo($n) 
{ 
	$pow = 1; 
	$answer = 0; 

	// Go through every bit of n 
	while ($n) 
	{ 
	$pow = $pow * 5; 

	// If last bit of n is set 
	if ($n & 1) 
		$answer += $pow; 

	// proceed to next bit 
	$n >>= 1; // or $n = $n/2 
	} 
	return $answer; 
} 

// Driver Code 
$n = 5; 
echo "nth magic number is ", 
	nthMagicNo($n), "\n"; 

// This code is contributed by Ajit. 
?> 
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
star

Fri Oct 22 2021 16:30:17 GMT+0000 (UTC) https://developer.wordpress.org/reference/functions/add_action/

#php #wordpress #functions #documentation #prority
star

Fri Oct 22 2021 13:28:15 GMT+0000 (UTC)

#php
star

Thu Oct 21 2021 21:39:53 GMT+0000 (UTC)

#php
star

Wed Oct 20 2021 23:37:10 GMT+0000 (UTC) crackshack.com

#php
star

Sat Oct 16 2021 06:13:04 GMT+0000 (UTC) https://www.quizcure.com/php/remove-duplicate-elements-from-array-in-php-without-using-function

#php
star

Fri Oct 15 2021 19:07:24 GMT+0000 (UTC)

#php
star

Fri Oct 15 2021 19:05:39 GMT+0000 (UTC)

#php
star

Fri Oct 15 2021 18:16:09 GMT+0000 (UTC) https://stackoverflow.com/questions/30686880/laravel-firstornew-how-to-check-if-its-first-or-new

#php
star

Fri Oct 15 2021 14:29:30 GMT+0000 (UTC) https://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date/2910642

#php
star

Tue Oct 05 2021 13:59:30 GMT+0000 (UTC)

#php
star

Sun Oct 03 2021 01:16:58 GMT+0000 (UTC) https://www.postgresql.org/docs/

#php #sql #postgresql
star

Thu Sep 30 2021 21:00:53 GMT+0000 (UTC) https://stackoverflow.com/questions/53532424/how-to-enable-animate-css-in-wordpress

#php
star

Thu Sep 30 2021 17:10:31 GMT+0000 (UTC)

#php
star

Mon Sep 27 2021 01:38:18 GMT+0000 (UTC) https://babiato.co/threads/wp-content-pilot-pro-best-wordpress-autoblog-affiliate-marketing-plugin.30824/

#php
star

Fri Sep 24 2021 17:36:04 GMT+0000 (UTC)

#php #laravel
star

Fri Sep 24 2021 15:22:07 GMT+0000 (UTC) https://www.humblix.com/Wxmew2p/in-php-how-to-check-if-a-multidimensional-array-is-empty

#php
star

Tue Sep 21 2021 15:18:57 GMT+0000 (UTC) https://stackoverflow.com/questions/8754980/convert-array-of-single-element-arrays-to-one-a-dimensional-array

#php
star

Fri Sep 17 2021 10:47:34 GMT+0000 (UTC) https://postmarkapp.com/email-api

#php
star

Thu Sep 16 2021 08:36:20 GMT+0000 (UTC)

#php #sort #array
star

Tue Sep 14 2021 20:54:34 GMT+0000 (UTC) https://stackoverflow.com/questions/13469803/php-merging-two-arrays-into-one-array-also-remove-duplicates

#php
star

Wed Sep 08 2021 23:52:36 GMT+0000 (UTC) https://www.itsolutionstuff.com/post/laravel-5-inner-join-with-multiple-conditions-example-using-query-builderexample.html

#php
star

Wed Sep 01 2021 13:20:42 GMT+0000 (UTC) https://docs.wp-rocket.me/article/1280-customize-access-to-options-for-user-roles#custom-code

#php
star

Wed Sep 01 2021 04:03:36 GMT+0000 (UTC) https://laravel.com/docs/8.x/eloquent

#php #الاضافة
star

Wed Aug 25 2021 16:19:17 GMT+0000 (UTC) https://stackoverflow.com/questions/36241924/laravel-model-error-handling-when-creating

#php
star

Wed Aug 25 2021 11:54:18 GMT+0000 (UTC)

#php
star

Wed Aug 25 2021 11:33:31 GMT+0000 (UTC)

#php
star

Thu Aug 19 2021 11:00:37 GMT+0000 (UTC)

#php
star

Tue Aug 17 2021 17:28:48 GMT+0000 (UTC) https://laravel.com/docs/7.x/migrations

#php
star

Sun Aug 15 2021 02:24:34 GMT+0000 (UTC) https://www.quizcure.com/php/stdclass-object-php-foreach-loop

#php
star

Sat Aug 14 2021 22:26:45 GMT+0000 (UTC)

#php
star

Wed Aug 04 2021 17:05:38 GMT+0000 (UTC) https://wpglorify.com/show-total-savings/

#php
star

Tue Aug 03 2021 15:54:10 GMT+0000 (UTC) https://stackoverflow.com/questions/14179758/how-can-i-build-a-condition-based-query-in-laravel

#php
star

Tue Aug 03 2021 04:36:57 GMT+0000 (UTC) https://stackoverflow.com/questions/51487769/how-to-insert-big-data-on-the-laravel

#php
star

Mon Aug 02 2021 15:49:52 GMT+0000 (UTC) https://wordpress.org/support/topic/how-to-increase-product-variation-limit-in-woo-commerce/

#php
star

Mon Aug 02 2021 08:20:32 GMT+0000 (UTC) https://seodoityourself.co.il/איך-להוסיף-תמונת-מוצר-להזמנות-של-ווקומ/

#php
star

Fri Jul 30 2021 00:28:21 GMT+0000 (UTC) https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

#php #laravel
star

Thu Jul 22 2021 22:01:24 GMT+0000 (UTC)

#php
star

Thu Jul 22 2021 22:00:00 GMT+0000 (UTC)

#php
star

Thu Jul 22 2021 21:59:18 GMT+0000 (UTC)

#php
star

Thu Jul 22 2021 21:58:35 GMT+0000 (UTC)

#php
star

Thu Jul 22 2021 21:58:03 GMT+0000 (UTC)

#php