Including sidebar partial view with php MVC

I have to create a to-do application with PHP using MVC.
It’s obligated to use partials such as header.php, footer.php, …

However, I want to echo the sidebar as an inline element with my main content(.php).
But when I do this it get’s positioned as a column (obviously).

So I tried to render the sidebar.php into the content.php but it didn’t appear and in the browsers console, even funnier, the command that should import the sidebar.php got commented out..

I’m on the edge of just write sidebar content in a container from the content.php and drop the sidebar partial unless some of you can give me a clear way to do this. And with ‘this’, I mean a way to include the sidebar.php into my content so they are partials but inline.

If you want to see some code.. :

this is the index.php in the public folder

require '../resources/views/header.php';
//require '../resources/views/sidebar.php';
require '../App/bootstrap.php';
require '../resources/views/footer.php';

The main content is rendered with a controller through bootstrap.php

This is the controller that renders my main content (which is called application.php)

<?php 

namespace AppHttpControllers;

use AppProvidersView;

class MainController {
    public function mainApp() {
       return View::display('application.php');
    }
};

but I’ve written this inside the application.php file:

<?php 
include 'sidebar.php';
?>

Laravel Trying to get property id of non-object

I am trying to update variables at About Us table, but i am getting this error. What is wrong?

AboutUsController:

   /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsAboutUs $aboutUs
     * @return IlluminateHttpResponse
     */
    public function edit($aboutUs_id)
    {
        $aboutUs = AboutUs::find($aboutUs_id);
        return view('auth.aboutus.form',compact('aboutUs'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsAboutUs $aboutUs
     * @return IlluminateHttpResponse
     */
    public function update(AboutUsRequest $request, AboutUs $aboutUs)
    {
        $params = $request->all();

        $aboutUs->update($request->all($params));

        return redirect()->route('aboutUs.index')->with('success','Post updated successfully');
    }

Here is my AboutUsRequest, where i am getting this error:

    public function rules()
    {
        $rules = [
            'title1' => 'required|min:5',
            'body1' => 'required|min:5',
        ];

        if ($this->route()->named('aboutUs.update')) {
            $rules['title1'] .= ',' . $this->route()->parameter('aboutUs')->id;
        }

        return $rules;
    }
}

Laravel 9 and ReactJS App gets a 401 unauthorized with api.php router

I am made an App with Laravel 9 back-end and ReactJS front-end and get a 401 unauthorized error even I am successfully logged-in in to my App.

Code is in api.php router and looks like below:

Route::post('/userdata', [AppHttpControllersProfileController::class, 'userData'])->middleware('auth')->name('userdata');

And here is a ProfileController:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportStr;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateFoundationValidationValidatesRequests;

class ProfileController extends Controller
{
   private $apiToken;

   public function __construct()
   {
        $this->apiToken = uniqid(base64_encode(Str::random(40)));
        $this->middleware('auth');
    }

    /**
    * Get the user's profile.
    *
    * @param  Request  $request
    * @return Response
    */
    public function userData(Request $request)
    {
         $user = Auth::user();
         var_dump($user);
    
         return "";
     }
 }

Purpose of this controller is to get logged-in users details for ReactJS GUI.

And also here is a code in AuthController.php which make user logged-in:

    public function login(Request $request){
    //User check
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_active' => 1])){
        
        $user = Auth::user();
        
        if($user->email_verified_at !== NULL){
        
            if (DB::table('domains')
                ->select('domain', 'valid_before')
                ->where('domain', $user->domain)
                ->whereDate('valid_before_at', '<=', Carbon::now())
                ->count()){
                    return response()->json([
                       'success' => false,
                       'data' => 'Username and password do not match or domain subscription is not valid or expired!'
                    ], 200);
                
            } else { 
                 // Login and "remember" the given user...
                Auth::login($user, true); 
                //Setting login response 
                $success['token'] = $this->apiToken;
                $success['name'] =  $user->name;
                return response()->json([
                   'success' => true,
                   'data' => $success
                ], 200); 
            }

        } else {
            return response()->json([
                'success' => false,
                'data' => 'Please Verify Email!'
            ], 200);
        }
        
    } else {
        //$success['success'] = false;
        return response()->json([
            'success' => false,
            'data' => 'Username and password do not match or domain subscription is not valid or expired!'
        ], 200);
          
    }
}

Also if anyone wants to see whole source codes of am App there re publically here in my GIT repos:

https://bitbucket.i4ware.fi/projects/LOG/repos/login-form/browse?at=refs%2Fheads%2Fmatti_0006

https://bitbucket.i4ware.fi/projects/SAAS/repos/saas-app/browse?at=refs%2Fheads%2Fmatti_0008

Toggle switch display on selected

i would like to display creating product in admin section sub categories in tree only when selected else closed in woocommerce product categoreis.How can i achieve this.presently it appears like this. tried css but didn’t work

<li id="tire_sizes-52"><label class="radiall"><input value="52" type="checkbox" name="tax_input[tire_sizes][]" id="in-tire_sizes-52"> 145</label><ul class="children">

<li id="tire_sizes-62"><label class="radiall"><input value="62" type="checkbox" name="tax_input[tire_sizes][]" id="in-tire_sizes-62"> 65</label>    <ul class="children">

<li id="tire_sizes-87"><label class="radiall"><input value="87" type="checkbox" name="tax_input[tire_sizes][]" id="in-tire_sizes-87"> 15</label></li>
    </ul>
</li>
</ul>
</li>

i want it closed and open only if is selected

Redirect multipe links using htaccess

I have shifted my website from one place to another. I have high traffic in the first place, so I need to redirect it on specific pages mapping to the second place. There are almost one thousand articles, so I need one thousand redirections. How to do that through htaccess?

I am using the described below HTACCESS CODE for this purpose but it is not working:

Redirect https://websiteOLD.com/article1 https://websiteNEW.com/article1

Redirect https://websiteOLD.com/article2 https://websiteNEW.com/article2

Redirect https://websiteOLD.com/article3 https://websiteNEW.com/article3

Redirect https://websiteOLD.com/article4 https://websiteNEW.com/article4

Redirect https://websiteOLD.com/article5 https://websiteNEW.com/article5

Redirect https://websiteOLD.com/article6 https://websiteNEW.com/article6

Whats wrong with the above described code lines? I have almost one thousand of such lines mapping each WordPress article from old domain to the new domain.

How can I select from stored procedures in CodeIgniter 4

I need help solving selecting from a procedure table from MySQL in Codelgniter and loading the data into Datatable. I am new to Codelgniter, for the past few days, I have been trying to solve this.

In my Controller I tried the following:

function get_vendors_sales_detail() {

     
        $customer = $this->input->get('customer') ? $this->input->get('custoproduct_codemer') : NULL;
        $start_date = $this->input->get('start_date') ? $this->input->get('start_date') : NULL;
        $end_date = $this->input->get('end_date') ? $this->input->get('end_date') : NULL;
        $user = $this->input->get('user') ? $this->input->get('user') : NULL;

        $this->load->library('datatables');
        $this->datatables
        ->select("sn, date, customer_name, product_name, product_code, total_items, unit_price  ")
        ->from('vendor03_product_sales');
        if ($this->session->userdata('store_id')) {
            $this->datatables->where('store_id', $this->session->userdata('store_id'));
        }
        $this->datatables->unset_column('id');
        if($customer) { $this->datatables->where('customer_name', $customer); }
        if($user) { $this->datatables->where('created_by', $user); }
        if($start_date) { $this->datatables->where('date >=', $start_date); }
        if($end_date) { $this->datatables->where('date <=', $end_date); }

        echo $this->datatables->generate();
        $this->page_construct('reports/vendors_sales_details', $this->data, $meta);
        

    }

But in my view, I am getting an error. I have tried making a search online but could not find what I need. I need help from Codelgniter experts.

Sign In With Google with custom buttons

I am using google library for social login with custom buttons but it is not opening the login popup.

Below is my code

<div class = "google-design-rest">
    <a href = "javascript:void();" ><i
            class = "fab fa-google"></i> {{ __('shop::app.customer.login-form.continue-with-google-button-text') }} </a>
    <!--end Google Check-->
    <div id = "g_id_onload" data-client_id = "{{ env('GOOGLE_CLIENT_ID') }}" data-context = "signup"
         data-ux_mode = "popup" data-callback = "handleCredentialResponse" data-auto_prompt = "false">
    </div>
    <div class = "g_id_signin" data-type = "standard" data-theme = "filled_blue" data-size = "large"
         data-text = "continue_with" data-shape = "rectangular" data-logo_alignment = "center"
         data-width = "500">
    </div>
</div>

If I use the default buttons then it’s working. There is no way provided by this version of the library to use it with custom buttons. There is no console error as well.
If anyone can provide me a way to make it work will be helpful.

Page-by-page migrate from the old site (Yii / PHP 5.4) to a new (Laravel)

The Insurance company website on Yii, PHP 5.5 with 95% old and 5% new design, bad customer journey map, a lot of junk and glitches. It makes no sense to update it, we will spend more time on fixes and optimization than a new development.

We want to migrate the site to the new framework Laravel, updating the entire design to fit the new style. Development will take years – more than 500 pages and a long approval cycle for each.

Questions:
Is it possible to gradually move from one framework to another, replacing the site page by page until we update everything? How can it technically be done so that you can switch from one framework to another depending on the page. Does it make sense?
Could you tell us about your cases or suggest other solutions?
Thanks in advance!

How to enable invisible ReCAPTCHA on checkbox onclick

I am struggling with an recaptcha issue on my local. I am trying to build a register form. All examples about recaptcha are about buttons. What I want is to pop-up recaptcha modal to user when he/she clicks on checkbox which says ‘ I have read and accept terms and conditions.’ When he/she solves recaptcha then checkbox would be checked. Here what I am trying

<html>
  <head>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
     <script>
       function onSubmit(token) {
         document.getElementById("checkbox-form").submit();
       }
     </script>
  </head>
  <body>
    <form id='checkbox-form' action="?" method="POST">
     <input type="checkbox" class="g-recaptcha" data-sitekey="MY_KEY_IS_HERE" data-callback='onSubmit' id="termsConditions" class="termsOkay">
     <label for="termsConditions" generated="true">I have read and accepted <a target="_blank" href="/sales-terms-and-conditions/">Terms and Conditions</a> </label>
      <br/>
    </form>
  </body>
</html>

I know code is a mess because I tried so many different thing and this is what I got. I am really confused. All I want is if user checks the checkbox let captcha popup. When solved, checkbox is checked. How can I do it? I tried to use handleChange but could not make it either.

How to Add Dynamic Meta tags Using php

I Fetch Data From Laravel API and I want to show dynamic meta title and description but when i set dynamic data in inspect element it show’s dynamic values but not updated in page source and also when share on social media like whatsapp, facebook etc it not showing dynamic title and description.

Here is My Code..

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="theme-color" content="#084594" />
<meta property="og:title" id='metaTitle' content="Static Title">
<meta property="og:description" id='metaDescription' content="Static Description">

Now I am Change it Using Jquery

<script>
$(document).ready(function() {
  const API = "<?= API ?>";
  $('#metaTitle').attr('content','Dynamic Title')
  $('#metaDescription').attr('content','Dynamic Description')
  function getCategory() {
   
    $.ajax({
      type: "get",
      url: `${API}/all_category`,
      success: function(response) {
        console.log("responseCat", response.category);
        $.each(response.category, function(key, item) {
          let cat = item.name.split(' ')[0];
          $("#filter").append(
            `<li data-filter=".${cat}"><a href="#">${item.name}</a></li>`
          );
        });
        isotopFilter();
      },
    });
  }

  function getPortfolio() {
    $.ajax({
      type: "get",
      url: `${API}/all_portfolios`,
      success: function(response) {
        console.log("responseCat", response.portfolio);
        $.each(response.portfolio, function(key, item) {
          let cat = item.category.split(' ')[0];
          let url_title = item.title.toLowerCase().replace(/[ ().]/g, '-');
          url_title = url_title.replace('--', '-');
          $(".masonry_wrapper").append(
            `<div class="col-md-4 col-sm-6 flex-active item ${cat}"><div class="tutorial_card"> <div class="service-content"> <a href="portfolio/${url_title}" > <h3>${item.title}</h3></a > </div><div class="read"> <a href="portfolio/${url_title}" class="btn btn-default" >View Portfolio</a > </div></div></div`
          );
        });
        isotopFilter();
      },
    });
  }

  
  getCategory();
  getPortfolio();
});

But It is showing Static Title And Description in ctrl + u Page Source code But In Inspect Elements It change With Dynamic Title And Description.
And Also When Share Page It Shows Static Title And Description

Message: Class ‘PublicKeyLoaders’ not found (phpseclib)

I am trying to connect SSH to EC2 server with privatekey using php (phpseclib). I’ve downloaded phpseclib from GitHub and added into libraries folder.

My code:

/* $dir --- contains my library folder path */
include($dir.'phpseclib3/Net/SSH2.php');
include($dir.'phpseclib3/Crypt/PublicKeyLoader.php');
$key = new PublicKeyLoader();
$key->loadPrivateKey(file_get_contents($ppkpath));

$ssh = new SSH2('ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com');
if (!$ssh->login('ec2-user', $key)) {
    exit('Login Failed');
}

while executing this I got the following error

Class ‘PublicKeyLoader’ not found

How to redirect to thank you page after woocommerce checkout order processed

im trying to change order status to “completed” and skip payment page (go to thank you page) after order is processed.

so far i manage to change order status to completed but instead of redirecting me to thank you page, i will be redirected to payment page with the following error :

enter image description here

this is the code i use :

add_filter( 'woocommerce_checkout_order_processed' , 'skip_join_payment' );
function skip_join_payment( $order_id ) {
     if ( ! $order_id ) {
        return;
    }
    if( $_COOKIE['isjoinForFree'] == "yes" ){
        $order = wc_get_order( $order_id );
        $order->update_status( 'completed' );

        ** i tried to redirect here but getting error on checkout page **
        // if ( $order->has_status( 'completed' ) ) {
                // header("Location: /jtnx/");
                // die();
        // } 


    }
}

in addition i tried adding another hooks with redirect :

add_action( 'woocommerce_payment_complete', 'skiped_join_payment_redirect', 1 ); 
function skiped_join_payment_redirect ( $order_id ){
    $order = wc_get_order( $order_id );
    if( $_COOKIE['isjoinForFree'] == "yes" ){
    $order = wc_get_order( $order_id );
    if ( $order->has_status( 'completed' ) ) {
            header("Location: /jtnx/");
            die();
        } 
    }
}

How do I display a PHP script as html page after calling it using AJAX?

I am trying to call a php file, which will display a html page, using AJAX from my js. This is my php file:

<!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>Snippet details</title>
</head>
<body>
    <?php
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    
        require "../server_detail.php";
    
        $con=mysqli_connect($server,$username,$pass);
        $connection=mysqli_select_db($con,$database);
    
        if(!$connection)
            echo "Connection to database failed! Please try again";
        else{
            $sql="SELECT `Snapshot` FROM `snippet` WHERE `Date`='".$_POST["date"].
                "' AND `newspaper`='".$_POST["newspaper"]."' AND `Subject_desc`='".$_POST["news_desc"]."'";

            $result = $con->query($sql);
            $temp=explode('.',$result->fetch_array()[0]);

            echo "<div style=
             'text-align:center; vertical-align: middle;
             background-color: #FFFFFF; margin: 0 auto !important; 
             min-height: 100%; padding: 0; width: 978px !important; overflow:auto;'>";

            echo "<h3>{$_POST['newspaper']}</h3>";
            if($temp[count($temp)-1]=="pdf" || $temp[count($temp)-1]=="PDF")
                echo "<iframe src='{$result->fetch_array()[0]}' height='200px'>";
            else
                echo "<img src='{$result->fetch_array()[0]}' height='200px'>";
            echo "<p>{$_POST["news_desc"]}</p>";
            echo "</div>";
        }
        $con->close();
    ?>
</body>
</html>

I am trying to call this script from my js (when a li is pressed):

document.querySelector('body').addEventListener('click', function(event) {
      if (event.target.tagName.toLowerCase() === 'li') {
        var str=event.target.innerText.split('-');
        $.ajax({
            url: '/all_backend_stuff/view_page.php',
            type: 'POST',
            data:{
                "date":document.getElementById("date").value,
                "newspaper":str[0],
                "news_desc":str[1]
            },
            success:function(response){
                window.open('/all_backend_stuff/view_page.php'); //shows that all my array keys are undefined 
            },
            complete:function(){}
        });
      }
});

My POST variables are showing as undefined. Why is that?

error foreach upload image in php/Laravel

I’m tryng to upload image from a form in laravel but i get this in postman on dd($request->image)

Laravel version is 8.12

i have problem to get images on request , i’ve used/imported Request $request in my function and globally in my controller

IlluminateHttpUploadedFile {#1900
  -test: false
  -originalName: "IMG_20211015_104550_306.jpg"
  -mimeType: "image/jpeg"
  -error: 0
  #hashName: null
  path: "C:xampptmp"
  filename: "php9F5A.tmp"
  basename: "php9F5A.tmp"
  pathname: "C:xampptmpphp9F5A.tmp"
  extension: "tmp"
  realPath: "C:xampptmpphp9F5A.tmp"
  aTime: 2022-03-11 09:47:40
  mTime: 2022-03-11 09:47:40
  cTime: 2022-03-11 09:47:40
  inode: 6192449487666182
  size: 153950
  perms: 0100666
  owner: 0
  group: 0
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
  linkTarget: "C:xampptmpphp9F5A.tmp"
}

in my controller:

            
            if (isset($request->immagini)) {
                $realPath=[];
                foreach ($request->file('immagini') as $key => $value) {
                    dd($value);
                    // $realPath = $value->store('images/mail', 'public');
                    $realPath =Storage::disk('public')->put('images/mail', $value);
                }
                
            }
            else {
                $realPath=null;
               
            }

            $data = [
                $request->type,
                $realPath,
                $nome,
                $mailMittente,
                $telefono,
                $anno,
                $info,
                $km,
                $cilindrata,
                $alimentazione,
                $targa,
                $marca,
                $cognome,
                $modello
            ];
            dd($request->immagini);

i can’t access to dd($value) and i get realPath=[].