PHP GnuPG Extension Not Working with Nginx, Fails to add PGP Key

I’m trying to use the PHP GnuPG extension to perform PGP encryption in my PHP script. The script works as expected when running with the built-in test server (php -S), but it fails to import a PGP public key when served through Nginx. I’m encountering the “Error importing public key” issue.

Here’s an overview of the situation:

PHP Version: 8.1.24
Nginx Version: nginx/1.18.0 (Ubuntu)

putenv("GNUPGHOME=/tmp");

$pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)
[KEY HERE]
-----END PGP PUBLIC KEY BLOCK-----";

$enc = (null);
$res = gnupg_init();
var_dump($res);
$rtv = gnupg_import($res, $pubkey);
$rtv = gnupg_addencryptkey($res, "C25F29936D9046D73A77DCF8244F423AED8F1481");
var_dump($rtv);
$enc = gnupg_encrypt($res, "just a test to see if anything works");
var_dump($enc);
echo "Encrypted Data: " . $enc . "<br/>";

I tested the script with nginx and the php test server.
While using the php server I get a output like this:

resource(2) of type (ctx) 

array(9) { ["imported"]=> int(0) ["unchanged"]=> int(1) ["newuserids"]=> int(0) 
["newsubkeys"]=> int(0) 
["secretimported"]=> int(0) 
["secretunchanged"]=> int(0) 
["newsignatures"]=> int(0) 
["skippedkeys"]=> int(0) 
["fingerprint"]=> string(40) "C25F29936D9046D73A77DCF8244F423AED8F1481" 
} 

bool(true) 

Encrypted Data: -----BEGIN PGP MESSAGE----- [MESSAGE]-----END PGP MESSAGE-----

But with nginx the output is only:

resource(2) of type (ctx) 
array(9) { 
["imported"]=> int(0) 
["unchanged"]=> int(1) 
["newuserids"]=> int(0) 
["newsubkeys"]=> int(0) 
["secretimported"]=> int(0) 
["secretunchanged"]=> int(0) 
["newsignatures"]=> int(0) 
["skippedkeys"]=> int(0) 
["fingerprint"]=> string(40) "C25F29936D9046D73A77DCF8244F423AED8F1481" } 

bool(false) 

Encrypted Data:

I added the line extension = gnupg.so to these files:

/etc/php/8.1/cli/php.ini
/etc/php/8.1/fpm/php.ini

I also added a file to the conf.d folder called gnupg.ini

I’ve noticed that when I run phpinfo() on the test server, there’s a PATH environment variable that includes GnuPG, but this variable is not present when running the same script through Nginx.

Any suggestions or insights would be greatly appreciated. Thank you!

Firebase/JWT php plugin to create ECDH-ES+A256KW token

i use this site to create JWT token and now i want to create that in php code with firebase plugin but i have to change algoritm & encrypt like the photo below + with a specific public key:

enter image description here

the simple code for creating JWT in this plugin is like this:

$secretKey = 'key';
$payload = [
  'iss' => 'http://test.com', // refer site
  'iat' => time(), //  token generate
  'nbf' => time()+30, /// token usable after 
  'exp' => time()+36000, /// token expire
  $data = ['email' => $email] 
];
$jsonWebToken = JWT::encode($payload,$secretKey,'HS256'); 

so how i must change the code to generate that key?!

CMS Module agnostic with dependency injection (symfony, dependency-injection, container)

I’m trying to develop a library in PHP. This library will be used in modules for CMS (WordPress, Drupal, PrestaShop for example).

Each CMS has different specificities and very special ways of doing things: on PrestaShop, for example, we have access to the symfony dependency injection system.

On WordPress, this system doesn’t exist at all and the norm is to create a Singleton and make a big mess.

I’m looking for a simple architecture that I could use in my library because it’s becoming complex and a dependency injection/container system would be very useful.

I’ve focused on PrestaShop because I can use Symfony DI directly in my library, but I’ve come across a problem: I need to make database calls (something specific to each module) so I need a service that is defined in the PrestaShop container except that I can’t find a “clean” way of retrieving this service in my module container..

In the library, the container is defined like that :

private function createContainer()
{
    $container = new ContainerBuilder();

    $configurationLoader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Ressources/config'));
    $configurationLoader->load('services.yml');

    $container->compile();

    return $container;
}

I found I could technically do this to fix my problem, but it no longer works when I want to use PhpDumper and cache my library container:

private function createContainer(WidgetRepositoryInterface $widgetRepository)
{
    $container = new ContainerBuilder();

    $container->set('repository.widget_repository', $widgetRepository);
    $container->setAlias(WidgetRepositoryInterface::class, 'repository.widget_repository');

    $configurationLoader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Ressources/config'));
    $configurationLoader->load('services.yml');

    $container->compile();

    return $container;
}

I think I’m in a bit of a loop where I don’t really know how to merge the containers :

  • I’ve tried extension systems.
  • I looked at the compiler pass on my library.
  • I tried importing the “service.yml” file for my library from the PrestaShop module files.

Thanks in advance,

JQuery toggle() not working in included php file

This code works fine (it hides or reveals the HTML elements with classes ‘PA’, ‘PF’ etc.):

<input type="button" id="moreLess" value="woops">
<script>
$(document).ready(function () {
  $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");

  $("#moreLess").on('click', function () {
    $(".PF, .PA, .TF, .TA").toggle();
    $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");
  });
});
</script>

But the exact same code, when included in a php class file (which basically just prints a lot of HTML) does not work.
The code is properly escaped and the resulting HTML is identical to the code which is written by the original method.
So 2 identical JQuery scripts, but the one that is written inside the php class does not work.
To be exact, the ‘.toggle()’ does not work – the reset of the input value from “woops” to “<–>” is executed.

I’ve searched around, but can’t find any clue as to why this doesn’t work.

What is particularly confusing is the fact that the html generated by the 2 methods appears to be identical in every respect.

To clarify, I allowed both versions to create the HTML and :

  <input type="button" id="moreLess" value="woops">
  
  <script>
    $(document).ready(function () {
      $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");

      $("#moreLess").on('click', function () {
        $(".PF, .PA, .TF, .TA").toggle();
        $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");
      });
    });
      </script>
      
                <input type="button" id="moreLess" value="woops">
                
                <script>
                  $(document).ready(function () {
                    $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");
              
                    $("#moreLess").on('click', function () {
                      $(".PF, .PA, .TF, .TA").toggle();
                      $("#moreLess").val($(".TA").is(':visible') ? "-><-" : "<-->");
                    });
                  });
                </script>  

Facing Uncaught TypeError: Cannot access offset of type string on string after moving from php 7.4 to php 8.2 [closed]

I have this part of a code :

//Get Data from Clients
if(is_array($ClientsData)){
   foreach($ClientsData as $value){

      //Get inside Specific client results
      if(is_array($value)){
         foreach($value as $values){
            $GetValues = $values['NameID'];
            if(isset($values[$GetValues])){
               $GetValuesCount = count($values[$GetValues]);
            }
            
            //Get Statistics
            for($z = 0; $z < $GetValuesCount; $z++){`

….

I’m showing you part of the code because the whole code is something like 3000 lines…

I get an error in line $GetValues = $values[‘NameID’];
Didnt had this issue in php 7.5. I know its an issue about an array and string thing but although I’ve tried to find it (from other similar questions) cant deal with it, due to my small experience in PHP.. Any idea how to solve it ?

If I try and print_r($ClientsData) I get this results:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [NameID] => 41
                    [Name] => SAMANTHA SMITH
                    [DateOfBirth] => 19/12/1975
                    [Address] => 0
                    [Country] => Italy
                    [Skills] => Engineer
                )

        )

)

Calculate the percentage between two dates without PHP or Javascript functions [closed]

For a client, I had to find a way to get the percentage between today, x and an objective date, y. That will be useful for creating a reduced price, but the problem is I can’t do that with PHP or Javascript functions, only with one simple formula.

I have found this :

((x-y)/365)-(1*floor((x-y)/365))

x = The ordinal number of today (the 19th of October if the 291st day of the year)
y = The ordinal number of your objective day

Result : Decimal percentage of the ordinal number of days out of 365 with an objective day.

Now, I need feedback about it and see if there is a better way to get the same result or maybe if a mathematician sees this post he could teach me how to replace the “floor” function.

Laravel previous and next recordings of the episode

is there any way to create previous and next recording of each episode on laravel?
this is what i have

My controller:

 public function getEpisode(Request $request, $movie, $slug, $id)
    {
        $movie = Movie::fromCache()->find($movie)->load('episodes');

        if (is_null($movie)) abort(404);

        /** @var Episode */
        $episode = $movie->episodes->when($id, function ($collection, $id) {
            return $collection->where('id', $id);
        })->firstWhere('slug', $slug);

        if (is_null($episode)) abort(404);

        $episode->generateSeoTags();

        $movie->increment('view_total', 1);
        $movie->increment('view_day', 1);
        $movie->increment('view_week', 1);
        $movie->increment('view_month', 1);

        $movie_related_cache_key = 'movie_related.' . $movie->id;
        $movie_related = Cache::get($movie_related_cache_key);
        if(is_null($movie_related)) {
            $movie_related = $movie->categories[0]->movies()->inRandomOrder()->limit(12)->get();
            Cache::put($movie_related_cache_key, $movie_related, setting('site_cache_ttl', 5 * 60));
        }

        return view('themes::themebptv.episode', [
            'currentMovie' => $movie,
            'movie_related' => $movie_related,
            'episode' => $episode,
            'title' => $episode->getTitle()
        ]);
    }

I have tried creating the previous and next buttons but it doesn’t work at all. I hope someone can help me

using SQL in echo php

I try to use SELECT in echo because I make while loop and I want to SELECT id in table account so I will use this data inside form

here is some of my php code:

    $sql = "SELECT * FROM account";
    $getquery = mysqli_query($conn, $sql);

    while ($runrows = mysqli_fetch_array($getquery)) {
        echo '
      <!-- td -->
      <li class="account">
       <div class="products">
        ' . $runrows["id"] . '
       </div>
       <span class="status">
        <span></span>
        ' . $runrows["username"] . '</span>
       <div class="button-wrapper">
       ' . $runrows["rank"] . '
       </div>
       <div class="button-wrapper" style="margin-right: 10px;">
       <a href="#edit' . $runrows["id"] . '"><button style="margin-right: 10px; background-color: #4299e1; border: none; border-radius: 5px; font-size: 25px; font-family: supermarket; border: black solid 1px;">edit</button></a>
       <a href="#delete"><button style="margin-right: 10px; background-color: #f56565; border: none; border-radius: 5px; font-size: 25px; font-family: supermarket; border: black solid 1px;">delete</button></a>
      </div>
      </li>
      <div id="edit' . $runrows["id"] . '" class="overlay" style="font-family: supermarket">
    <div class="popup">
        <h2 style="font-family: supermarket"><i class="fa-solid fa-user-pen"></i> edit data of user ID : ' . $runrows["id"] .'</h2>
        <a class="close" href="/backend/user/"><i class="fa-solid fa-xmark"></i></a>
        <div class="content" style="overflow: hidden; font-size: 20px;">
            <form action="collector.php" method="post">
            <?php
            $sql = "SELECT * FROM account WHERE id = ' . $runrows["id"] . '";
            $queryId = mysqli_query($conn,$sql);
            $idRows = mysqli_fetch_array($queryId)
            ?>
                <div class="txt_field">
                    <input type="text" required name="phone" max-length="10" style="color: var(--content-color); font-family: supermarket;" value="' . $idRows["id"] .'">
                    <span></span>
                    <label style="font-family: supermarket;">' . $runrows["id"] . '</label>
                </div>
            </form>
        </div>
    </div>
</div>';

as you can see I try to use SELECT in echo but at input feild it don’t show me nothing (all of php syntax are correct but I don’t sure if it correct or not in echo that have sql inside)

here is some of my database

id username password
1 test1 testno1
2 test2 testno2

If anyone have better way or can fix my code please let me know. Thanks

When I try to submit a PHP form from my web (on render.com) I get this error:

When I try to submit a PHP form from my web I get this error:

Warning : require(/var/www/html/vendor/composer/…/symfony/polyfill-ctype/bootstrap.php): failed to open stream: No such file or directory in /var/www/html/vendor/composer/autoload_real.php on line 41

Fatal error : require(): Failed opening required ‘/var/www/html/vendor/composer/…/symfony/polyfill-ctype/bootstrap.php’ (include_path=‘.:/usr/local/lib/php’) in /var/www/html/vendor/composer/autoload_real.php on line 41

The form works fine when testing on my local environment using XAMPP. I should receive an email to my gmail address.

I should receive the form content to my gmail. I tried many things. The files are in place.

Different price coefficient by category – WooCommerce

I have a site (WordPress and WooCommerce) that uses a product scraping script. In it, it is set that all products and categories have the same margin coefficient as follows:

$koef = 1;// If you need add 25% – set $koef = 1.25, if 55% – $koef = 1.55, if 120% – $koef = 2.2

I want some categories to have a margin of 10%, some 5%, some 30%, etc.

How could I separate it?

I set the percentage in WooCommerce, but after each product update, the prices are 0,00 €

Choosing the Best Approach for an Internal Back Office Software: CodeIgniter or jQuery for API Calls in a Decoupled App? [closed]

I’m working on the development of an internal back office software, and I’m exploring the best approach for building the front end and handling API calls. Here’s the setup:

Frontend Views: I plan to create the frontend views using HTML and jQuery in CodeIgniter (CI).

Backend: The backend logic and APIs are powered by Laravel, which resides on a different server.

The purpose of this software is to serve a small user base, typically ranging from 10 to 40 people, and there is little to no chance of high traffic.

The approach I’m considering is as follows:

CodeIgniter will load a view, rendering the initial UI for users.

The view will use jQuery to make an API call to CodeIgniter.
CodeIgniter, in turn, will make an HTTP request to the Laravel backend to retrieve data or perform operations.

CodeIgniter will receive the response from Laravel and relay it to the view, which will update the UI accordingly.

My question is whether this approach is a good one for this context, or if it’s better to directly make API calls to the Laravel server using jQuery from the front end.

I’m interested in the pros and cons of both approaches, particularly regarding ease of development, security, maintainability, and performance. Given the low traffic and the nature of this back office software, which approach is more suitable, and why?

I appreciate any insights and recommendations based on your experience and expertise. Thank you!

Display Line chart with data retrieved from MySQL Database

I am using a template built on Bootstrap 4 & 5. There is a line chart already featured, with hardcoded values being displayed.

Hardcoded values:

<div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="card overflowhidden number-chart">
                        <div class="body">
                            <div class="number">
                                <h6>SALES</h6>
                                <span>$500</span>
                            </div>
                            <small class="text-muted">19% compared to last week</small>
                        </div>
                        <div class="sparkline" data-type="line" data-spot-Radius="0" data-offset="90" data-width="100%" data-height="50px"
                        data-line-Width="1" data-line-Color="#604a7b" data-fill-Color="#a092b0">**1,4,2,3,6,2**</div>
                    </div>
                </div>

And it looks like this visually:

enter image description here

Now, I have a MySQL database and I want to retrieve the data to display it on the line chart.

I removed the hardcoded values and added the MySQL query. Please tell me what I’m doing wrong because the retrieved data is not being displayed. My DB connection is ok.

<div class="row clearfix">
            <div class="col-lg-3 col-md-6 col-sm-6">
                    <div class="card overflowhidden number-chart">
                        <div class="body">
                            <div class="number">
                                <h6>Water Level</h6>
                                <span><p></p><p></p></span>
                            </div>
                            <small class="text-muted">Last 2 Hours</small>
                        </div>
                        <div class="sparkline" data-type="line" data-spot-Radius="0" data-offset="90" data-width="100%" data-height="50px"
                        data-line-Width="1" data-line-Color="#604a7b"  data-fill-Color="#a092b0">
                        **<?php
                        $sql2 = "SELECT water_level as water_level FROM `tbl_water_level` WHERE `date` > SUBDATE( NOW(), INTERVAL 2 HOUR)";
                            $result2 = mysqli_query($conn, $sql2);
                            $data = '';
                            while($data=mysqli_fetch_array($result2)){
                                echo '.$row["water_level"].'; 
                            }
                            
                        ?>**
                        </div>
                    </div>
                </div>
        </div>

Distribution of Fixed Coupons Among Order Items

I’m curious about how WooCommerce distributes coupons within order items. I’ve generated a fixed cart coupon for $100 Coupon Details.

However, when I apply this coupon to an order, I’ve noticed that the coupon amount is divided among the order’s line items. I’m unclear about the logic WooCommerce uses to distribute the coupon amount. Is there a specific formula or method involved in this distribution process? Order Details

I attempted a solution where I evenly divided the coupon amount among each order item and then deducted this allocated coupon value from the subtotal of each item. However, this approach did not yield the desired results.

Here’s the formula I used:

  • Coupon applied to each item = Total coupon amount / Number of order items
  • Adjusted item total = Original item subtotal – Coupon applied to each item

Best way to implement view counter of article/news in laravel? [closed]

I have tables for articles/news in my project. Please tell me. If I add a view_count column and increment it every time an article/news is sent by the server. Would this be good practice or is there a better solution?

Or will this slow down response or will it not work if I have many hits on this route at the same time? Or is it better to use some third party counter like google analytics? I would appreciate any suggestion, thanks.