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=[].

php fatal erro mysqli_connect() [duplicate]

<?php
    $servername = "localhost";
    $username = "root";
    $password = "123456";
    $dbname = "buke";
    
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    $sql ="INSERT INTO xuesheng (xingming,nianling,xingbie) 
    VALUES ('小明','18','男')";
    
    if (mysqli_query($conn, $sql)) {
        echo "新记录插入成功";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
    
    mysqli_close($conn);
?>

when i run it in visule studio 2019 ,I met :

Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in D:codenodejshtdocsaddStudent.php:8
Stack trace:
#0 {main}
  thrown in D:codenodejshtdocsaddStudent.php on line 8

I have installed
php debug
xdebug
php intelephense
php intellisense

and edit the php.ini:

extension="D:phpstudy_proExtensionsphpphp7.3.4ntsextphp_mysqli.dll"
extension_dir="D:phpstudy_proExtensionsphpphp7.3.4ntsext"

Move 50.000 folders with rename

I have the challenge of sorting about 50,000 folders with images in them.

Currently, it is like this. There is a folder “Uploads”. There are 50000 subfolders in it.

Now I want them to be sorted by year/month.
So
uploads/2022/03
uploads/2022/02
uploads/2022/01
etc

Creating the folders for month/year with mkdir and rename for moving the folders is known to me.

My question is rather if rename is the best solution here.

And maybe does someone also have an idea how long such a process takes?

As far as I understand, rename changes the path of the folder. Is the folder on the hard disk of the server “really moved” or is that “only” meta information and rename is done in a few milliseconds?

Remove duplicate in array and display quantity of each duplicate – Smarty

I have an array full of Strings. I am trying to remove the duplicates in the array, and display how much value there were. I don’t know if i’m clear.

Here is my code :

{loop type="product" name="mot-cle"}
    {assign var="fooVar" value="{$POSTSCRIPTUM}"}
    {assign var="parts" value=","|explode:$fooVar}
    
    {foreach from=$parts key=k item=i}
    <ul>
        <li>{$i}</li>
    </ul>
    {/foreach}
{/loop}

This code display this :

test
test2.
test3
test3
test3.
test
test3
test.
test2
test3.
test2
test
test3.
test3

I wish to display this :

test (4)
test2 (3)
test3 (7)

PS : I am new with smarty.
Any help ?

How to make architecture of querying SQL with arbitrary filters [closed]

Let’s say I have a table for showing data in the frontend, and the user can select all kinds of filters based on the columns. For text columns they can have certain text filters such as ‘starts with’, ‘contains’, ‘equals’, ‘is not equal to’, etc.

For columns with integers it would be stuff like ‘equals’, ‘greater than’, ‘less than’, ‘is not empty’, ‘is empty’.

For percentage columns the same etc etc.

How would one structure this, in broad terms, in the backend to recognize all these filters and place them in a query at the right place. So which filters would be a WHERE, which filters HAVING? Which filters go inside a join, which filters go outside a join or subquery?

And if certain columns show an average, how would you structure this so that certain filters get applied before or after an AVG function? If I want to see only AVG rows with a value above 20, OR I want to see AVG rows that are calculated from values above 20, both should be possible. Same with COUNT or SUM.

I’m struggling to come up with a coherent system that doesn’t become incredibly confusing and complex. How do other companies do this? Is there maybe a framework that has all this built in? I’m just using Symfony and MySQL.

Show S3 SSE-C Encrypted Image using Presigned URL in the browser

Without any encryption, even for a file that resides in a bucket with no public access, I can create a presigned URL by modifying response-content-type header for an image with an expiry time and it would show the image in the browser. This is very helpful when I need to display the image in the browser using the src attribute of img HTML tag.

However, When I encrypt an image using SSE-C in S3, is there any way to show the image in the browser using presigned URL? I’ve some images which are encrypted using SSE-C in S3.
However, in some cases they might required to be shown in the browser.

The documentation states this
enter image description here aws docs link

Is there any way? Thank you.

Error page with Laravel policy and authorization with User Model

This is my UserPolicy:

<?php
namespace AppPolicies;
use AppModelsUser;
use IlluminateAuthAccessHandlesAuthorization;
class UserPolicy
{
    use HandlesAuthorization;
    public function view(User $user, User $model)
    {
        return $user->id === $model->id;
    }
}

This is the AuthServiceProvider:

<?php
namespace AppProviders;
use AppModelsUser;
use AppPoliciesUserPolicy;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'AppModelsModel' => 'AppPoliciesModelPolicy',
        User::class => UserPolicy::class
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

And finally the UserController

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;

class UserController extends Controller
{
    public function show(User $user)
    {
        $this->authorize('view', $user);
        return view('user.show', [
            'user' => $user,
        ]);
    }
}

I am trying to use $this->authorize('view', $user); to authorize but I am getting the “Something went wrong in Ignition!” error page.

I have already spent an entire day trying to figure out what I have done wrong. Can anyone please point out what’s wrong?