How to use php-cli with Linux C++

I am making a software using C++, which needs to process a lot of data. C++ makes me feel uncomfortable, and I want to use PHP to deal with these data classes. I have searched a lot of information, but there is very little information about how C++ indirectly uses php-cli, which I know may involve the application of some underlying PHP apis. But I couldn’t find any information about it.

I want to be able to package PHP with my files in any environment that supports C++, and then I can use it in C++. Crucially, something like this:

cout << php("echo 'xxxx';" );

or

cout << php("preg_match('/^(-)? (d+)/',string)");

I know this can involve a lot of knowledge, I’m new to Linux, and I’m just hoping to get some direction.

Getting “Sorry, please enter the key” on PHP cUrl request

I am following the API Redeem Microsoft call from this website: https://getcid.info/developers]

Here is my PHP code for the cURL request:

$url = 'https://getcid.info/api-key-digital';
 
$curl = curl_init();

$fields = [
    'key' => '1231232-1232123-1232123-1231232-5762636-1232123-1232123-1232123-1232123'
];

$fields_string = http_build_query($fields);
 
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
 
$data = curl_exec($curl);

echo '<pre>';
     var_dump( $data );
echo '</pre>';
 
curl_close($curl);

But I am getting an error message;

{“status”:”error”,”res”:”Sorry, please enter the key”}

I don’t understand why this error message is showing as I have passed the key!

Not able to interact with php file in xampp

I downloaded xampp and am running a PHP file in my localhost, however, I cannot receive user input from the program, any idea what I am doing wrong? I used both fscanf and readline, but both just stop the program from running.

How to refactor deprecated create_function inside array_reduce in php 7.2

I am trying to refactor a use of create_function in an old legacy site that uses propel 1.6 but needs to run on php 7.2.

The original function is

 protected static function dumpArray($value)
{
// array
$keys = array_keys($value);
if (
  (1 == count($keys) && '0' == $keys[0])
  ||
  (count($keys) > 1 && array_reduce($keys, create_function('$v,$w', 'return (integer) $v + $w;'), 0) == count($keys) * (count($keys) - 1) / 2))
{
  $output = array();
  foreach ($value as $val) {
    $output[] = self::dump($val);
  }

  return sprintf('[%s]', implode(', ', $output));
}



// mapping
$output = array();
foreach ($value as $key => $val) {
  $output[] = sprintf('%s: %s', self::dump($key), self::dump($val));
}

return sprintf('{ %s }', implode(', ', $output));

}

I’ve refactored

 (count($keys) > 1 && array_reduce($keys, create_function('$v,$w', 'return (integer) $v + $w;'), 0) == count($keys) * (count($keys) - 1) / 2))

to

 (count($keys) > 1 && array_reduce($keys, function($v,$w){return (integer) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2))

It appears to work BUT i now get warnings because $v+$w doesn’t always return an integer.

Im unsure if I have refactored correctly and if I have how I should deal with the warning.

Thanks.

Symfony 5: controller requires that you provide a value for an argument

I have recently bought a new computer. Both old and new have xampp over Windows 10. After I have copied all my apache, mysql and php configuration files to the new one and once checked everything can run. I find an error on one of my symfony sites homepage using exactly the same files I was using previously.

Controller “AppControllerFrontendController::index()” requires that
you provide a value for the “$locale” argument. Either the argument is
nullable and no null value has been provided, no default value has
been provided or because there is a non optional argument after this
one.

In order to check for the possible error I have created a new FrontendController class with the minimal code I needed in order to reproduce my error.

Here is the code that does not generate the error:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;

class FrontendController extends AbstractController 
{

    /** 
     * @Route("/", name="index")
     */

    public function index(
      Request $request,
      string $locale = 'es'
    ) {
      dd($locale);
    }
  }

Here is the code that DOES generate the error. The only difference is that I add WhiteOctober/BreadcrumbsBundle that works like a charm in my installation on the previous computer.

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use WhiteOctoberBreadcrumbsBundleModelBreadcrumbs;

class FrontendController extends AbstractController 
{

    /** 
     * @Route("/", name="index")
     */

    public function index(
      Request $request,
      string $locale = 'es',
      Breadcrumbs $breadcrumbs
    ) {
      dd($locale);
    }
  }

Again, when I remove $locale from the parameters list, things also work:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use WhiteOctoberBreadcrumbsBundleModelBreadcrumbs;

class FrontendController extends AbstractController 
{

    /** 
     * @Route("/", name="index")
     */

    public function index(
      Request $request,
      Breadcrumbs $breadcrumbs
    ) {
      dd("Without locale");
    }
  }

How to read JSON file with PHP from instagram __a=1 page

I’m trying to call a URL and read its content using php.
when I place the url directly in the browser It works, but when I use php it returns me null.
here’s my code:

$url = "https://www.instagram.com/instagram/?__a=1"
$json = file_get_contents($url);
$res= json_decode($json);
var_dump($res);

Does anyone have an idea why I can’t read the file with PHP?
Thank you,

PHP Warning: PHP Startup: Can’t load module ‘C:xamppphpextphp_mongodb.dll’ as it’s linked with 14.29, but the core is linked with 14.16

Please help me

I am having an issue while the Laravel MongoDB connection.
when running this command :”composer require jenssegers/mongodb”.
I got this warning message:

LENOVO@DESKTOP-7MHNLPS MINGW64 /c/xampp8/htdocs/mongotest
$ composer require jenssegers/mongodb
PHP Warning: PHP Startup: Can’t load module ‘C:xamppphpextphp_mongodb.dll’ as it’s linked with 14.29, but the core is linked with 14.16 in Unknown on line 0
Warning: PHP Startup: Can’t load module ‘C:xamppphpextphp_mongodb.dll’ as it’s linked with 14.29, but the core is linked with 14.16 in Unknown on line 0
Info from https://repo.packagist.org: #StandWithUkraine
Using version ^3.9 for jenssegers/mongodb
./composer.json has been updated
Running composer update jenssegers/mongodb
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
– Root composer.json requires jenssegers/mongodb ^3.9 -> satisfiable by jenssegers/mongodb[v3.9.0].
– jenssegers/mongodb v3.9.0 requires illuminate/support ^9.0 -> found illuminate/support[v9.0.0-beta.1, …, 9.x-dev] but these were not loaded, likely because it conflicts with another require.
You can also try re-running composer require with an explicit version constraint, e.g. “composer require jenssegers/mongodb:
” to figure out if any version is installable, or “composer require jenssegers/mongodb:^2.1” if you know which you need.
Installation failed, reverting ./composer.json and ./composer.lock to their original content.
*

I am using XAMPP on windows 10 and my PHP version is 8.1.6 and MongoDB version is 5.0.8.
I have tried three different php_mongodb.dll.

  1. php_mongodb-1.13.0-8.1-ts-vs16-x64
  2. php_mongodb-1.12.1-8.1-ts-vs16-x64
  3. php_mongodb-1.12.0-8.1-ts-vs16-x64

and also added extension=php_mongodb.dll in the php.ini file.

I don’t understand this warning and I have no clue how to resolve it.

PHP Warning: PHP Startup: Can’t load module ‘C:xamppphpextphp_mongodb.dll’ as it’s linked with 14.29, but the core is linked with 14.16 in Unknown on line 0

Please help me and Thanks in Advance.

How to compare current date within while loop value?

I have some dates for my tickets for the event like the following screenshot and I am using ACF repeater for this.

enter image description here

And I have a function where I am trying to compare the ticket registration start date with the current date.

function santy_shortcode_race_categories_event_post(){
    date_default_timezone_set('Asia/Kolkata');
    $result = '<div class="table-responsive">
                <table class="table table-bordered" style="text-align:center; background-color:#fff;">
                <thead>
                    <tr class="table-head">
                        <th>Package</th>
                        <th>Age Category</th>
                        <th>Ticket Price</th>
                        <th>Reg. Link</th>
                    </tr>
                </thead>
                <tbody>';
    $id = get_the_ID();
    $current_date = date("Y-m-d H:i:s");
    if( get_field('Race-Categories', $id) ) {
        while( the_repeater_field('Race-Categories', $id) ) {
        $event_start_date .= date("Y-m-d H:i:s", strtotime("+5 hours +30 minutes", strtotime(get_sub_field("ticket_registration_start"))));
        $event_end_date .= date("Y-m-d H:i:s", strtotime("+5 hours +30 minutes", strtotime(get_sub_field("ticket_registration_end_date"))));
        $result .='<tr>';
        $result .='<td>'.get_sub_field("package").'</td>';
        $result .='<td>'.get_sub_field("age_category").'</td>';
        $result .='<td>'.get_sub_field("ticket_price").'</td>';
        if($current_date > $event_start_date){
            $result .= '<td>Registration Open</td>';
        }else{
            $result .= '<td>Registration Close</td>';
        }
        $result .='</tr>';
    }
    }else{
        $result .='No Any Race categories allocated for this event. Try other events.';
    }
    $result .= '</tbody>
                </table>
                </div>';
    return $result;
}

But this is returning wrong output, going share below the screenshot of my output..

enter image description here

It is showing in every row registration open but logically it should be show registration closed and show only registration open for 2 km Family-Run.

how to redirect sub pages to www to non-www from htaccess

I am trying to redirect my subpage to a non-www but I get duplicate URLs of the same page.

What I want to implement

https://www.example.com/category/webs => https://example.com/category/webs
http://example.com/category/webs => https://example.com/category/webs
http://www.example.com/category/webs => https://example.com/category/webs

.htaccess

Options -Indexes
RewriteEngine On

RewriteRule ^category/([a-zA-Z0-9-/]+) category-list.php?id=$1 [NC,L]

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</IfModule>

With this current code, my root domain redirects perfectly. but not subpages! I read many articles but not helping

Update WP query with a dropdown

I’m looking for a way for users to update the content of a WP query by choosing a year in a dropdown. I’d like to display the current year by default but let the users consult the archive of past years.

Is there a way to make it?

Thanks for your help !

Here’s the link to the page :
http://preprod.atelier-labotte.fr/municipalite/

Here’s my code :

    <?php
$yearToLookFor = $_GET['year']; 

$args = array(
    'post_type'             => 'comptes-rendus',
    'post_status'           => array( 'publish' ),
    'posts_per_page'        => '-1',
    'date_query' => array('year' => $yearToLookFor ),
    'order'                 => 'DESC', 
);
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {  
?>
    <section class="wp-block-group light-color-section" id="compte-rendus">
        <div class="wp-block-group__inner-container">
            <div class="d-flex justify-content-between align-items-center">
                <h2>Comptes rendus du conseil municipal</h2>
<select class="dropdown-year" name="archive-dropdown" onchange="">
  <?php wp_get_archives( array( 'type' => 'yearly', 'format' => 'option', 'show_post_count' => 1,   'post_type' => 'comptes-rendus') ); ?>
</select>
            </div>
            <div class="d-grid columns-3">
            <?php                
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
    ?>
                <div class="document-card">
                    <h4><?php the_title(); ?></h4>
                    <p class="tiny"><?php the_date('d/m/Y'); ?></p>
                    <?php
                    $file = get_field('download_document');
                    if( $file ):
                        $url = wp_get_attachment_url( $file ); ?>
                        <a href="<?php echo esc_html($url); ?>" class="btn" >Télécharger</a>
                    <?php endif; ?>
                </div>
    <?php
    }
    ?>  
            </div>
        </div>
    </section>
    <?php
}
wp_reset_postdata();
?>

chnage download_url in woocommerce

i want to change the download_url in woocommerce

my-account : http://localhost/i/account

downloads : http://localhost/i/account/downloads

  • before : http://localhost/i/?download_file=
  • after : http://localhost/i/account/downloads/download_file=

path : /plugins/woocommerce/includes/wc-user-functions.php | lines 632 to 640

line 639 = change home_url( ‘/’ ) to home_url( ‘/account/downloads/’ )

i have a hook for changes but i do not know how to call that part through the hook :

function filter_woocommerce_customer_available_downloads( $downloads, $customer_id ) { 
    
    return $downloads; 
} add_filter( 'woocommerce_customer_available_downloads', 'filter_woocommerce_customer_available_downloads', 10, 2 );

and i had another change, remove the question mark : change /?download_file= to /download_file=

Follow unfollow working only first row php while loop

I’m working on a follow and unfollow system project but there seems to be a problem with my code

The follow unfollow button only work for the first row.
How can i get it to work for different rows
I have tried different ways but none seem to be working
Here is my Php while loop code and J’s code below

 $check_following_or_not = mysqli_query($db,"select * from follow_and_unfollow_activity where page_owners_emails = '{$_SESSION["username"]}'");  
        while($de=mysqli_fetch_array($check_following_or_not)) {      
         $page_owner=$de['followers_emails'; 
       if(mysqli_num_rows($check_following_or_not) > 0)

      {?>
    <span hidden data-src="loading.gif"></span>

                    <span  style="background:purple;color:white;opacity:0.6"  class="button actions__btn text-uppercase font-900 " id="following" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','following');"><b>Following    <?php echo $page_owner;?> </b> <i class="fa fa-check"></i></span>
     <? if(!isset($_SESSION['username']))
{echo'<a href="/ver/dist">';}?>
    <button style="display:none;background-color:" class="actions__btn actions__btn--active follow" id="follow" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','follow');">
<font color="">Follow    <?php echo $page_owner;?>     </font></button>
            
    <? if(!isset($_SESSION['username'])){echo'</a>';}?>
      <?php} 

else{<? if(!isset($_SESSION['username'])){echo'<a href="/ver/dist">';}?>
                    
    <span hidden data-src="loading.gif"></span>
     <button class="actions__btn actions__btn--active follow " id="follow" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','follow');" <? if(!isset($_SESSION['username'])){

     echo'';}?>>Follow <?php echo $page_owner;?> </button>
     <? if(!isset($_SESSION['username']))
{echo'</a>';}?>
     <span   style="display:none;background:purple;color:white;opacity:0.6" class="button actions__btn text-uppercase font-900" id="following" onClick="follow_or_unfollow('<?php echo $page_owner; ?>','<?php echo $_SESSION["username"]; ?>','following');"><b>Following     <?php echo $page_owner;?> </b> <i class="fa fa-check"></i></span>

     <?
      }?>
     <?}?>

Here is my My Js code

$(document).ready(function(){     $('.following').hover(function()
{                 $(this).text("Unfollow");},function()
{                  $(this).text("Following");
  });
 });
             
        
    function follow_or_unfollow(page_owner,follower,action)
    {
        var dataString = "page_owner=" + page_owner + "&follower=" + follower;
        $.ajax({  
            type: "POST",  
            url: "follow_or_unfollow.php",  
            data: dataString,
            cache: false,
            beforeSend: function() 
            {
                if ( action == "following" )
                {
                    $("#following").hide();
                    $("#loading").html('<img src="images/loading.gif" align="absmiddle" alt="Loading...">');
                }
                else if ( action == "follow" )
                {
                    $("#follow").hide();
                    $("#loading").html('<img src="images/loading.gif" align="absmiddle" alt="Loading...">');
                }
                else { }
            },  
            success: function(response)
            {
                if ( action == "following" )
                {
                    $("#loading").html('');
                    $("#follow").show();
                    
                }
                else if ( action == "follow" )
                {
                    $("#loading").html('');
                    $("#following").show();
                }
                else { }
            }
        }); 
    }