php binary could not be either found or executed. Make sure PHP is installed, and add path

here is the settings.json file on vscodium

{"php.executables": {"v8.3.17": "/usr/bin/php"}}

when I try to run it:

[Error: spawn php ENOENT
at ChildProcess._handle.onexit (node:internal/child_process:285:19)
at onErrorNT (node:internal/child_process:483:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)] {
errno: -2,
code: 'ENOENT',
syscall: 'spawn php',
path: 'php',
spawnargs: [
'-dxdebug.mode=off',
'/home/kudo/Documents/php learning/index.php'
]
}

I am on fedora. php is installed. version: 8.3.17

How can avoid PHP json_encode to escape URL when I use it for JSON LD? [duplicate]

I use an array to store my Json Ld content

$arJsonLd = array(
            "@context" => "https://schema.org",
            "@type" => "NewsArticle"
        );

I did search here how to convert a PHP array to Json Ld output and multiple answer pointed me to

json_encode($arJsonLd, JSON_PRETTY_PRINT);

the problem is that URLs get escaped

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "NewsArticle"
 }
 </script>

how can I avoid this? On Json Ld documentation url aren’t escaped

Laravel route returning “No response data for this request” when accessing an image file

I’m working on a Laravel application where I need to serve images stored in the filesystem and display them on a web page. I have defined the following route in web.php:

Route::post('/image/{campaign}/{folder}/{filename}', function ($campaign, $folder, $filename) {
    $path = "private/campaigns-images/campaign-$campaign/$folder/$filename";

    if (!Storage::exists($path)) {
        abort(404);
    }

    $file = Storage::get($path);
    $mimeType = Storage::mimeType($path);
    
    return Response::make($file, 200)->header("Content-Type", $mimeType);
})->name('image.show');

HTML and JavaScript
In my frontend, I’m trying to load and set the image as a background for a Fabric.js canvas using JavaScript:

<div class="mySlides">
    <div class="numbertext">1 / 3</div>
    <img id="background-image" 
        src="{{ route('image.show', ['campaign' => 1, 'folder' => 'images_17', 'filename' => 'DJI_20241105104710_0123_V.JPG']) }}"
        alt="Campaign Image"
        style="width: 100%; max-width: 1200px; height: auto;">
</div>

<canvas id="canvas"></canvas>
const canvas = new fabric.Canvas('canvas');

function setBackgroundImage() {
    const imgElement = document.getElementById('background-image'); 

    if (imgElement) {
        imgElement.onload = function () {
            fabric.Image.fromURL(imgElement.src, function (img) {
                canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
                    scaleX: canvas.width / img.width,
                    scaleY: canvas.height / img.height
                });
            });
        };

        // If the image is already loaded (from cache), trigger onload manually
        if (imgElement.complete) {
            imgElement.onload();
        }
    }
}
window.onload = function () {
    setBackgroundImage();
};

Issue

When I try to access an image via (GET request):
http://127.0.0.1:8000/admin/image/1/images_17/DJI_20241105104710_0123_V.JPG
I get the response “No response data for this request” but if I click on the same link the resource is available

What I’ve Tried
Checked that the file exists using Storage::exists($path), and it does.
Changed the route method from POST to GET, but still no response.
Checked storage/logs/laravel.log but no related errors appear.
Tried return response(‘Test Response’); inside the route, but nothing is displayed..

Turn the description input field of Elementor’s Call-To-Action Widget into a WYSIWYG-field

as the title says, I’m trying to hook into Elementor’s exisiting CTA-widget and turn the existing input field into a WYSIWYG-field by looking at the widget’s structure etc. within elementor pro directory. But somehow nothing happens. If I change it in the plugins source file it works, but sure I want to override it through my functions.php.

I’ve done this for the slides Widget before and that worked well. What am I missing here?

/*
 * Set Elementor > CTA widget description as wysiwyg Text Editor
 */
add_action( 'elementor/element/call-to-action/section_content/before_section_end', function( $widget, $args ) {
    $cta_control = ElementorPlugin::instance()->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'call-to-action' );

    if ( is_wp_error( $cta_control ) ) {
        return;
    }

    $cta_control['fields']['description']['type'] = ElementorControls_Manager::WYSIWYG;

    $widget->update_control( 'call-to-action', $cta_control );
},10 ,2 );

Any help appreciated. Thank you.

Got warning while uploading video file in PHP but not image or audio file [duplicate]

i got warnings when i upload a video file in PHP

This is my HTML code:

<form method=”post” action=”post.php” class=”box” enctype=”multipart/form-data”>

<textarea rows=”5″ cols=”35″ name=”message” placeholder=”content”>

<input type=”file” name=”mediaFile”>
button type=”submit”>Post
</form>

These are the warnings:

`Warning: POST Content-Length of 81138635 bytes exceeds the limit of 41943040 bytes in Unknown on line 0

Warning: Undefined array key “message” in C:xampphtdocspost.php on line 15

Warning: Undefined array key “mediaFile” in C:xampphtdocspost.php on line 24

Warning: Trying to access array offset on value of type null in C:xampphtdocspost.php on line 24`

why i did not get these warnings when i successfully upload a image or audio file in the server?

Laravel Files upload

I’m encountering the following error when attempting to upload an image in my Laravel project:

Error:
IlluminateHttpExceptionsPostTooLargeException

I understand that this issue is related to file size limitations. Based on my research, I modified the following settings in my php.ini file:

post max size
upload max file size
memory limit
After making these changes, I restarted Apache, but the error persists.

What I Have Tried:
Updated php.ini settings (as shown above).
Restarted Apache and MySQL to apply changes.
Checked Laravel configuration to ensure proper file storage settings.
Verified that the correct php.ini file is being modified using

PHP getting data from a XML/XBRL file

I am trying to fetch the data from the following file http://regnskaber.virk.dk/48966882/ZG9rdW1lbnRsYWdlcjovLzAzLzdjLzk0LzFhL2I4LzY5ZGMtNGRhZi04NGE0LTRmNTEyN2UxY2U2MA.xml into php

So i can loop every field thru and fetch the needed data.

I have taken a look at How to parse this XML(XBRL) using Php

but i am still unable to go thru the data :/ can someone please help here.

Hvae tried following How to parse this XML(XBRL) using Php

but with no luck

Applying template formatting using PHPWord [duplicate]

I’ve written a Laravel application that generates content for documents and inserts it into existing Word templates using PHPWord. My desired approach is pretty simple:

  1. I generate the content that I need with Markdown formatting
  2. I write that content to named slots in Word (E.g. ${slot}) using PHPWord’s Template Processing

The issue that I’m experiencing is finding reliable ways to write formatted content such as bulleted lists or applying styles that are pre-existing in the Word document. For example, a markdown section of content might be formatted like this:

# Some heading
A paragraph of text
- Bullet 1
- Bullet 2
Some more text
## A sub-heading
- Bullet 1
- Bullet 2
Some text

I don’t have an easy way of knowing what the format will be before the text is generated, but I need to now insert this into Word. I’ve seen people doing this by adding HTML to sections like here, but I don’t know how to do it using named slots, as my content needs to fit into specific places in the document.

I’ve tried using the HTML route, but to no avail (formatting not applied, issues with special characters and the Word documents not opening). I’ve tried plain text, but that obviously leaves out all my required formatting. My latest approach has been to write the actual HTML tags and then use Copilot in Word to format them, but that is tedious and not automated.

Can someone help me with either:

  1. A better way of telling PHPWord to apply the in-document styles (e.g Heading 1, Heading 2 etc.) to markdown text generated and inserted into an existing template.
  2. Or, a way of programmatically telling Copilot in Word to auto-rewrite all of the content inserted with HTML tags.

Parsing XML snippets contained in a log file

I have a data file from an external source which contains multiple XML snippets (up to 350). Each one starts with a bit of text and then some XML output like this :

2025-02-21 16:45:55,760 - Transaction RUN04-merchtranid1 - Success: <?xml version="1.0" encoding="UTF-8"?>
<payment_response>
  <transaction_type>sale</transaction_type>
  <status>approved</status>
  <recurring_type>initial</recurring_type>
  <unique_id>ccc01a6fb43b45cf38298fee067d1688</unique_id>
  <transaction_id>RUN04-merchtranid1</transaction_id>
  <mode>test</mode>
  <timestamp>2025-02-21T14:45:55Z</timestamp>
  <descriptor>UAT Gen Current UK</descriptor>
  <amount>0</amount>
  <currency>EUR</currency>
  <sent_to_acquirer>true</sent_to_acquirer>
  <scheme_transaction_identifier>485029514074150</scheme_transaction_identifier>
</payment_response>

2025-02-21 16:45:56,704 - Transaction RUN04-merchtranid2 - Success: <?xml version="1.0" encoding="UTF-8"?>
<payment_response>
  <transaction_type>sale</transaction_type>
  <status>approved</status>
  <recurring_type>initial</recurring_type>
  <unique_id>1f293c3166045f645b9ea4aeee755840</unique_id>
  <transaction_id>RUN04-merchtranid2</transaction_id>
  <mode>test</mode>
  <timestamp>2025-02-21T14:45:56Z</timestamp>
  <descriptor>UAT Gen Current UK</descriptor>
  <amount>0</amount>
  <currency>GBP</currency>
  <sent_to_acquirer>true</sent_to_acquirer>
  <scheme_transaction_identifier>MDHMKJSTW</scheme_transaction_identifier>
  <scheme_settlement_date>0129</scheme_settlement_date>
</payment_response>

I need to roll through it with PHP and pick out the <unique_id> and matching <transaction_id> for each transaction. I can do this if it was a properly formatted XML document but this obviously isn’t.

Would really appreciate any ideas ?

Error with Nginx (ERR_TOO_MANY_REDIRECTS) in VPS Hostinger default config WordPress

I’m having a problem with my WordPress hosting on a Hostinger VPS with CloudPanel and NGINX. I’ve tried reinstalling it, it worked for 10 minutes (which is strange) and then it stopped working.

Basically, I try to access the site and I get the following response:
“ERR_TOO_MANY_REDIRECTS”
However, when I access wp-login, I can fill in the username and password, but it just reloads the page.

NGINX Error Log – Nothing
PHP-FPM Error Log – Nothing
WP_LOG – Nothing

This is the default configuration file:

server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 off;
  ssl_certificate_key /etc/nginx/ssl-certificates/www.casamarx.com.br.key;
  ssl_certificate /etc/nginx/ssl-certificates/www.casamarx.com.br.crt;
  server_name casamarx.com.br;
  return 301 https://www.casamarx.com.br$request_uri;
}

server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 off;
  ssl_certificate_key /etc/nginx/ssl-certificates/www.casamarx.com.br.key;
  ssl_certificate /etc/nginx/ssl-certificates/www.casamarx.com.br.crt;
  server_name www.casamarx.com.br www1.casamarx.com.br;
  root /home/casamarx/htdocs/www.casamarx.com.br;

  access_log /home/casamarx/logs/nginx/access.log main;
  error_log /home/casamarx/logs/nginx/error.log;

  if ($scheme != "https") {
    rewrite ^ https://$host$request_uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  location ~/.git {
    deny all;
  }

  location = /xmlrpc.php {
    deny all;
  }

  location ~/(wp-admin/|wp-login.php) {
    #auth_basic "Restricted Area";
    #auth_basic_user_file /home/site-user/.htpasswd;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      7200;
    proxy_send_timeout         7200;
    proxy_read_timeout         7200;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location ~* ^.+.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    # WordPress Multisite Subdirectory
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 break;
    rewrite ^/[_0-9a-zA-Z-]+(/.*.php)$ $1 break;
    add_header Access-Control-Allow-Origin "*";
    add_header alt-svc 'h3=":443"; ma=86400';
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}

server {
  listen 8080;
  listen [::]:8080;
  server_name www.casamarx.com.br www1.casamarx.com.br;
  root /home/casamarx/htdocs/www.casamarx.com.br;

  include /etc/nginx/global_settings;

  try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ .php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:15001;
    fastcgi_param PHP_VALUE "
    error_log=/home/casamarx/logs/php/error.log;
    memory_limit=512M;
    max_execution_time=60;
    max_input_time=60;
    max_input_vars=10000;
    post_max_size=64M;
    upload_max_filesize=64M;
    date.timezone=UTC;
    display_errors=off;";
  }

  # WordPress Multisite Subdirectory
  if (!-e $request_filename) {
    rewrite /wp-admin$ https://$host$uri permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*.php)$ $1 last;
  }

  if (-f $request_filename) {
    break;
  }
}

Portuguese:

Estou passando por um problema com minha hospedagem WordPress em uma VPS do Hostinger com CloudPanel e NGINX. Já tentei reinstalar, funcionou por um tempo de 10 minutos (o que é estranho) e logo em seguida passou a não funcionar.

Basicamente tento entrar no site e meu retorno é:
“ERR_TOO_MANY_REDIRECTS”
Porém, quando entro no wp-login, consigo preencher usuário e senha, mas ele somente recarrega a página.

NGINX Error Log – Não tem nada
PHP-FPM Error Log – Não tem nada
WP_LOG – Não tem nada

I tried to modify the permissions, I tried to disable plugins (at the first occurrence), but nothing. I don’t understand too much about nginx. But, I know when the VPS had the srv….hostinger.cloud (original domain) from Hostinger, don’t currency anything like this error.

Symfony Form: Validate children before parent

I have code that looks more or less like this:

It’s not my actual code, but just to show the concept of what I’m trying to do:

I have a form where each individual field is required and then some checks are run on the values of multiple fields in combination.

class testForm extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault(
            'constraints', 
            [new Callback(
                ['callback' => function (
                        $payload, 
                        ExecutionContextInterface $context
                    ) 
                    {
                        $data = $context->getObject()->getData();

                        if (strcasecmp($data['field1'], $data['field2']))
                        {
                            $context
                                ->buildViolation('fields must be equal')
                                ->atPath('[field1]')
                                ->addViolation();
                        }
                    }
                ]
            )]
        );
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('field1', TextType::class, ['constraints' => [new NotBlank]])
            ->add('field2', TextType::class, ['constraints' => [new NotBlank]]);
    }
}

The problem I’m having with this code is that it will throw a notice when you submit with empty fields (null is not allowed as parameters for string functions like strcasecmp() since PHP 8.0).

AFAICT this is because the parent validation runs before the child validation, so it only checks if the fields have values after the upper level validation has run.

What I am looking for is a way to reverse this, i.e. run the child validation before the parent validation is called. Looking at the Symfony documentation, there’s a Valid constraint that seems to do exactly that, but it only seems to work with entities (my form doesn’t use an entity, but a simple DTO).

So I remain wondering about a way to either make Valid work without entities, or some other way to remedy the constraints of doing this.

Trying to understand PHP Garbage Collection [duplicate]

Forgive my ignorance but I’ve not played around with PHP’s garbage collection before. Specifically, I’m running a CakePHP 5.x Command Script and running into memory exhausted issues.

As a test to see how I can clear some memory, I’m trying to run gc_collect_cycles(); on this part of the code:

$connection = ConnectionManager::get('default');
    $this->logMessage('Memory usage before query: ' . memory_get_usage(true) / 1024 / 1024 . 'MB');
    $studentList = $connection->execute("SELECT DISTINCT
                stu.STU_ID AS person_id
        FROM SMS.S1STU_DET AS stu
        LEFT JOIN Pulse.$studentsTableName AS students
            ON students.person_id = stu.STU_ID
        LEFT JOIN Pulse.$coursesTableName AS courses
            ON courses.person_id = stu.STU_ID
        LEFT JOIN Pulse.$unitsTableName AS units
            ON units.person_id = stu.STU_ID
        LEFT JOIN Pulse.$rawCasesTableName AS cases
            ON cases.person_id = stu.STU_ID
        WHERE   1 = 1
            AND (
                students.person_id IS NOT NULL
                OR
                courses.person_id IS NOT NULL
                OR
                units.person_id IS NOT NULL
                OR
                cases.person_id IS NOT NULL
            )
    ")->fetchAll('assoc');

    $this->logMessage('Memory usage after query: ' . memory_get_usage(true) / 1024 / 1024 . 'MB');

    unset($studentList);
    gc_collect_cycles();

    $this->logMessage('Memory usage after garbage collection: ' . memory_get_usage(true) / 1024 / 1024 . 'MB');
    exit();

And this is the output I get:

2025-02-23 11:32:54 - Memory usage before query: 8MB
2025-02-23 11:32:57 - Memory usage after query: 48MB
2025-02-23 11:32:57 - Memory usage after garbage collection: 44MB

As you can see gc_collect_cycles() didn’t find anything to clean up (it drops to 44MB regardless if I run gc_collect_cycles() or not. So I’m obviously not understanding and/or using this correctly. Is there anyway I can free up memory to get close to the starting 8MB again?

Modify main WordPress query to limit results to a list of possible Post IDs

I am working on a WprdPress/WooCommerce plugin feature where specific Customers are shown only a subset of Products.
The user has a meta data field with an array of post ids corresponding to the allowed Products.

I am trying to hook into the main query:

add_action( 'pre_get_posts', 'customprefix_pre_get_posts' );

function customprefix_pre_get_posts( $query )
{
  $user = wp_get_current_user();

  if ( $query->is_main_query() && is_product_category() )
  {
    /** @var array $allowed Post IDs */
    $allowed = customprefix_get_allowed_products_per_user( $user );

    $query->set( 'post__in', $allowed );
  }
}

I have tried many different combinations of how to add the post__in clause to the query including $query->query_vars['post__in'] = $allowed and others. I have tried adding $query->parse_query_vars() as well with no success.

While diving further into the get_posts() function in WP_Query it appears that my change to the Query is returned correctly (by reference) from the pre_get_posts hook. The next line: $q = $this->fill_query_vars( $q ); somehow looses my custom post__in field.

Most of the documentation for WP_Query and post__in revolve around creating a new query, not modifying the main query.

How to make a background bash script pause while an npm build runs?

I’m setting up a new method of deploying my personal react website, which is using vite for bundling. My idea is:

  1. I push un-bundled changes from local to remote repo
  2. a web hook informs my server (which has a listening php script)
  3. the php script triggers a bash script that: 1) runs an npm install, 2) runs an npm run build and 3) runs an rsync to copy the build contents to the web’s live folder

when I run the bash script manually via PuTTY, it works fine. I can watch while vite’s build output scrolls in the terminal, and eventually the rsync is triggered. But when the bash script is run via the php script, it does not seem to wait for the build (and perhaps even the install) to complete. It just copies whatever is in the build folder over to the live site (which is always the result of the last build, because the current build has not completed yet).

Is there a way to make the bash script wait for the install and the build to complete? I’ve tried adding a pause 120 after the install and build statements, and I’ve tried chaining the commands, for example something like

npm install && npm run build && rsync ......

neither accomplishes the goal when the script is run via php, but both work perfectly when I run manually..

The relevant line from the php script that calls the bash script is:

$commandOutput = shell_exec("/bin/bash ./sync.sh --repo=" . $hook["repo"] . " --branch=" . $hook["branch"] . " --subdomain=" . $subdomain);

$hook["repo"] is the name of the repo, $hook["branch"] is the current branch, and $subdomain is the subdomain being worked on (I have multiple set up).

The bash script starts out by picking up the repo, branch, and subdomain and then makes the various git and npm commands. The relevant lines are:

if [[ ${repo} && ${branch} && ${subdomain} ]]; then
  git -C /path/"${repo}"/ checkout "${branch}"
  git -C /path/"${repo}"/ fetch
  git -C /path/"${repo}"/ pull origin "${branch}"
  npm --prefix /path/"${repo}"/ install
  npm --prefix /path/"${repo}"/ run build;
  rsync -auv /path/"${repo}"/htdocs/* /path/"${subdomain}"/htdocs;
else
  echo "repo, branch and subdomain were not provided, I will not do anything.";
fi

Redis streams memory leak?

It is really long to explain why I use streams for simple task (and I can’t change it)
but at the moment I save multiple datas into different keys which are associated with streams.
After data is got from the stream with XRANGE I need to completely destroy the data,key.
Yes, just one access to the stream and everything has to be destroyed.
I tried everything. I tried expire 0 on the key, del, xtrim maxlen of 0 (and then del) and nothing works and my memory keeps getting bigger until exhaustion.
Even if 1 key (stream) is used, XRANGEd then deleted same memory leak applies.
What i see is

Memory

used_memory:27305504
used_memory_human:26.04M
used_memory_rss:17321984
used_memory_rss_human:16.52M
used_memory_peak:27349928
used_memory_peak_human:26.08M
used_memory_peak_perc:99.84%
used_memory_overhead:681540
used_memory_startup:660608
used_memory_dataset:26623964
used_memory_dataset_perc:99.92%
allocator_allocated:29209872
allocator_active:38076416
allocator_resident:38535168
total_system_memory:2050424832
total_system_memory_human:1.91G
used_memory_lua:37888
used_memory_lua_human:37.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:33554432
maxmemory_human:32.00M
maxmemory_policy:volatile-lru
allocator_frag_ratio:1.30
allocator_frag_bytes:8866544
allocator_rss_ratio:1.01
allocator_rss_bytes:458752
rss_overhead_ratio:0.45
rss_overhead_bytes:-21213184
mem_fragmentation_ratio:0.64
mem_fragmentation_bytes:-9944392
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:20496
mem_aof_buffer:0
mem_allocator:jemalloc-5.2.1
active_defrag_running:0
lazyfree_pending_objects:0

Using PHP redis to do Redis->del($key) etc.

I can’t use ordinary key to store the data (when del there is no leak).
Redis version 6.0.16