Return 200 status code with Location header

PHP documentation for the header() function tells us:

There are two special-case header calls… The second special case is the “Location:” header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

However, I want to return a 200 status code with a Location header. How can I do this, if at all? I have tried a few variations on the following with no luck:

header('Location: https://example.com/foo', true, 200);
http_response_code(200);
header('HTTP/1.1 200 OK', true, 200);
header('Content-Type: application/json');
echo '{"test":"testing"}';

According to my understanding of the PHP source, the first line should do it because of the explicitly specified status code:

if ((SG(sapi_headers).http_response_code < 300 ||
    SG(sapi_headers).http_response_code > 399) &&
    SG(sapi_headers).http_response_code != 201) {
    /* Return a Found Redirect if one is not already specified */
    if (http_response_code) { /* user specified redirect code */
        sapi_update_response_code(http_response_code);
    } else if (SG(request_info).proto_num > 1000 &&
       SG(request_info).request_method &&
       strcmp(SG(request_info).request_method, "HEAD") &&
       strcmp(SG(request_info).request_method, "GET")) {
        sapi_update_response_code(303);
    } else {
        sapi_update_response_code(302);
    }
}

How to enable CSRF protection in Laravel 12 API

I’m developing a Laravel (v12) API-based backend. I want to implemented CSRF protection but I can’t figure out how It’s gonna be doing in Laravel version 12.x.

I read Laravel 12 CSRF protection document but it couldn’t help me.

So how can I use CSRF protection on Laravel 12 APIs?

I tried following way and it I got nothing (CSRF token is not required from server):

<?php

use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->validateCsrfTokens();
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

enter image description here

Composer: how to use local symlinks for packages in development but Git versions in production

I have a project with a composer.json where some libraries are pulled from our GitLab:

"require": {
    "my/library": "1.0.0",
    "my/library-second": "1.2.1"
}

On production, this works fine — Composer fetches the packages from Git.

However, during development, I need to make changes to these libraries locally without creating a release. I want to use path repositories with symlink to my local folder.

The problems I face:

  • If I add local path repositories directly to the main composer.json, it breaks the production build.

  • Using replace or dev-master leads to conflicts with the fixed versions (1.0.0 / 1.2.1).

  • Ideally, I want a way to have a separate local composer.json or override only on the dev machine, so that:

  1. locally the packages are installed as symlinks,

  2. on production the stable Git versions are used,

  3. the main composer.json remains unchanged.

Question:

What is the proper way to structure Composer for this use case?

  • Is there a standard practice or common pattern to separate local and production Composer configuration, while keeping symlinks for local packages during development?

  • How do PHP projects usually handle local development with symlinks on packages without touching production composer.json?

Use a reference to $a to make $a a reference to $b

I have an array $arr = ['a', ['b',['c','d','e']]];.
So $arr[1][1][0] is 'c'.

I have these indexes listed in n array: $idx = [1,1,0];
(this may sound tricky, but comes from the fact that I got them from parsing a kind of scripting pseudo-language).

I have a recursive function which returns a reference to the expected element:
function &getDeepRef(&$array, $indexes){...}

Usage:
$ref = & getDeepRef($arr, $idx);

At that point, everything works as expected:
echo $ref;===> outputs 'c'
$ref = 12;
print_r($arr); ==> $arr is now ['a', ['b',[12,'d','e']]]

Here comes my question:
I need $arr[1][1][0] to become a reference to another variable $otherVar.
Can I do this using the $ref reference?

If yes, I couldn’t find the right syntax for this
($ref = &$OtherVar; unsets $ref as a reference to $arr[1][1][0], and makes it a reference to $otherVar, but in no way helps make $arr[1][1][0] a reference to $otherVar).

If no, how would you make the array element which indexes are listed in an array, become a reference to a given variable?

[Edit]
I found a solution based on eval();, but I’d rather use another way for security reasons:

    $arr = ['a', ['b', 'ii'=> ['c','d','e']],'f'];
    out($arr);
    
    $idxLeft  = [2];
    $idxRight = [1,'ii',0];
    
    $ref = &getDeepRef($arr,$idxRight);//$ref now is a reference to $arr[1]['ii'][0]
    $ref = 'ccc';//demo: $arr[1]['ii'][0] is now 'ccc'
    out($arr);
    
    //Now the target: $arr[2] = &$arr[1]['ii'][0];
    //Following does NOT work:
    $leftRef  = &getDeepRef($arr,$idxLeft);
    $rightRef = &getDeepRef($arr,$idxRight);
    $leftRef = &$rightRef; //this did NOT make $arr[2] a reference to $arr[1]['ii'][0]
        //instead it broke the reference from $leftRef on $arr[2] and made a new reference from $leftRef onto $arr[1]['ii'][0].
    
    //Following DOES work, but I'd prefer avoiding eval();  [notice: the mapping with json_encode is just here for string indexes compatibility, like 'ii']
    $eval = '$arr['. implode('][',array_map('json_encode',$idxLeft)) . '] = &$arr['. implode('][',array_map('json_encode',$idxRight)) . '];';
    out($eval);
    eval($eval);
    out($arr);
    
    $a = &getDeepRef($arr,$idxLeft);
    $a=45;
    out($arr);


    function &getDeepRef(&$var,$indexes){//third param just for exception message
        if(null===($id=array_shift($indexes))){ return $var; }
        if(!is_array($var) || !array_key_exists($id, $var)){ throw new Exception("Bad key: [$id]"); }
        return getDeepRef($var[$id],$indexes);
    }
    
    function out($v){
        static $i=0;
        echo '<br>'.++$i.' - '; print_r($v);
    }

How to run tests of the same phpunit testcase class in parallel with ParaTest?

I have a contrived test case showcasing how multiple test cases can slow the entire execution time down, as even though each is quick on its own, they add up if waited for before executing the next.

use PHPUnitFrameworkTestCase;

class ShouldTestInParallel extends TestCase
{
    /**
     * @dataProvider delayProvider
     */
    public function testItRunsTestsInParallel(int $delay)
    {
        sleep($delay);
        $this->assertTrue(true);
    }

    public function delayProvider()
    {
        return array_map(function ($value) {
            return [$value];
        }, array_fill(0, 10, 1));
    }

}

In order speed up test execution time, I installed paratest:

composer require brianium/paratest --dev

Now I expected the test to finish after 1 seconds.

I execute the test via phpstorm (and have enabled the paratest config), yet the entire test run still takes ~10s as each test is executed one after the other.

/bin/php -d memory_limit=5G /myproject/vendor/bin/paratest_for_phpstorm /myproject/library/vendor/phpunit/phpunit/phpunit --bootstrap /myproject/tests/bootstrap.php --debug --verbose --configuration /myproject/tests/phpunit.xml --filter Test\Vm\ShouldTestInParallel --test-suffix ShouldTestInParallel.php /myproject/tests/Vm --teamcity
Testing started at 1:57 PM ...
PHPUnit 9.6.25 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.0.30
Configuration: /myproject/tests/phpunit.xml

Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #0 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #1 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #2 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #3 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #4 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #5 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #6 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #7 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #8 (1)' ended
Test 'TestVmShouldTestInParallel::testItRunsTestsInParallel with data set #9 (1)' ended


Time: 00:10.026, Memory: 28.00 MB

OK (10 tests, 10 assertions)
Process finished with exit code 129 (interrupted by signal 1:SIGHUP)

How to Make Elementor Loop Grid Taxonomy Filters Work Dynamically After Custom User Role Filtering?

I have a custom post type called files. This post type is connected to a field group that includes:

  • 3 taxonomies

  • 1 checkbox list containing the available user roles on my site

I’m displaying the posts using an Elementor Loop Grid.

What I want to achieve:

  • First, filter the posts based on a comparison between the allowed roles (from the checkbox list) and the current user’s roles.

  • Then, apply Elementor’s native taxonomy filters dynamically on top of that.

What I have so far:

I wrote a small custom script (see below).

  • The user role filtering part works correctly: when I load the page, the posts displayed are restricted according to the current user’s roles.

  • However, the taxonomy filters do not work dynamically: when I click on a taxonomy filter, no posts appear. If I refresh the page, the filter is applied correctly, but I want it to work without needing a page reload.

Here’s my code:

<?php add_action("elementor/query/fichiers_query", function ($query) {
  if (!is_user_logged_in()) {
    $query->set("post__in", [0]);

    return;
  }

  $user = wp_get_current_user();

  $roles = (array) $user->roles;

  if (empty($roles)) {
    $query->set("post__in", [0]);

    return;
  }

  $meta_queries = ["relation" => "OR"];

  foreach ($roles as $role) {
    $meta_queries[] = [
      "key" => "roles",

      "value" => '"' . $role . '"',

      "compare" => "LIKE",
    ];
  }

  $query->set("meta_query", $meta_queries);
});
?>

Question:

How can I make Elementor’s taxonomy filters work dynamically after applying the initial user role filtering logic?

I hope you can help me on this,
thank you in advance!

How to select custom theme in Magento integration tests?

I am writing an integration test for a Magento action. In the frontend I have selected a custom theme with custom layout files and I get the correct output.

But in the integration test the default theme Magento/luma is used, where the specific blocks, which should be shown in the frontend, are not available.

How can I select the correct theme in my integration tests? A solution that must not be repeated for each test is preferred.

PHP Mail Function Says it Sends … but it doesnt [duplicate]

New to PHP, so please bare with me.

I created a function to send an activation email. To test it, I setup a test page that would run the function. The page is telling me that the mail was sent (i.e. it prints “Mail Sent.”) … but I never receive any email.

I’ve tried several different “to emails” (just in case the mail server for one was being picky). I also checked my SPAM folders for each account, but the emails aren’t showing. Can anyone see any issue with the code below?

<?
include_once('configinfo.php');
?>
<html>
<head>
<meta charset="utf-8">
<title>Email Test</title>
</head>

<body>
<?php
// site_email  and  activation_link are defined in configinfo.php. 
// activation-email-template.html is a file in the same location as this test page

function send_activation_email($email, $code) {
    // Email Subject
    $subject = 'Account Activation Required Test';
    // Email Headers 
    $headers = 'From: ' . site_email . 'rn' . 'Reply-To: ' . site_email . 'rn' . 'Return-Path: ' . site_email . 'rn' . 'X-Mailer: PHP/' . phpversion() . 'rn' . 'MIME-Version: 1.0' . 'rn' . 'Content-Type: text/html; charset=UTF-8' . 'rn';
    // Activation link
    $activate_link = activation_link .'?email=' . $email . '&code=' . $code;
    // Read the template contents and replace the "%link" placeholder with the above variable
    $email_template = str_replace('%link%', $activate_link, file_get_contents('activation-email-template.html'));
    // Send email to user
    if(mail($email, $subject, $email_template, $headers)) {
        $mailed = 1;
    } else {
        $mailed = 0;
    }
    return $mailed;
}
$code = '123456789';
$email = '[email protected]'; // I replace with my email address

$mailed = send_activation_email($email, $code)
?>

<h1>TESTING EMAIL</h1>
<?php
if($mailed == 1) {
    echo "Mail Sent."; // Page tells me this...
} else {
    echo "Mail FAILED";
}
?>
    
</body>
</html>

WordPress + Elementor critical error due to PHP limits on OVH shared hosting (tried .htaccess, wp-config, cron – no effect) [closed]

I am hosting a WordPress site (with Elementor) on OVH shared hosting. After installing my Elementor-compatible theme, the editor does not load and I only see:

There has been a critical error on this website.
Please check your site admin email inbox for instructions.

When I checked the server requirements from the template, I noticed some PHP settings are lower than recommended:

  • PHP version: 8.4.7 (works, but Elementor officially supports up to 8.2)

  • memory_limit: 512M ✅ (OK)

  • post_max_size: 130M ❌ (should be 256M)

  • upload_max_filesize: 128M ❌ (should be 256M)

  • max_execution_time: 165 ❌ (should be 300)

  • max_input_vars: 16000 ✅ (OK)


What I tried

  1. Edited .htaccess in /www/ root:

    php_value memory_limit 512M
    php_value post_max_size 256M
    php_value upload_max_filesize 256M
    php_value max_execution_time 300
    php_value max_input_vars 16000
    
    

    → No effect.

  2. Edited wp-config.php:

    @ini_set( 'memory_limit', '512M' );
    @ini_set( 'post_max_size', '256M' );
    @ini_set( 'upload_max_filesize', '256M' );
    @ini_set( 'max_execution_time', '300' );
    @ini_set( 'max_input_vars', '16000' );
    
    

    → No effect.

  3. Tried using cron in OVH Manager to force wp-cron.php.
    → Still same error when opening Elementor.

  4. I also tried switching PHP version inside OVH (.ovhconfig), but Elementor still crashes with the critical error.


Question

  • On OVH shared hosting, is it possible at all to increase post_max_size, upload_max_filesize, and max_execution_time to meet Elementor’s requirements?

  • Or do I need to upgrade to a different OVH plan (e.g. Pro / Performance) to get these PHP settings?

Any experience with Elementor + OVH hosting would be appreciated.

Is it allowed to create inheritors from Aggregates in DDD?

There is a PHP project with DDD approach, i.e. class entities have AggregateRoot.

The main classes of entities inherit from AggregateRoot and are implemented in the logic of the object.

Is it allowed within the DDD agreement to create inheritors from classes that implement the logic of the object, if these inheritors will have slightly different logic in the class?

For example

abstract class User extends AggregateRoot
class Customer extends User
class Employee extends User

or

class Order extends AggregateRoot
class RegularOrder extends Order
class SubscriptionOrder extends Order

Are inheritors allowed? In which cases?

.htaccess not working on LiteSpeed server worked fine on apache [closed]

I am retry to rewrite index.php to home and details.php?id=$ to product/$

Options -MultiViews
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]




RewriteRule ^product/([0-9a-zA-Z-_]+) details?id=$1 


RewriteRule ^special/([0-9a-zA-Z-_]+) details2?id=$1 




Can someone please assists am not sure what i did wrong thanks

MYSQL stored procedure called in PHP loop – only first iteration works [duplicate]

PHP version: 7.4.3
MySQL version: 8.0.42

I have a simple stored procedure which selects a single column from a table, which is called inside a loop from my PHP. The first iteration works fine. The second iteration fails. I have logged the SQL statements which my PHP builds, and when I run the statement for the second iteration in MySQL Workbench, it works as expected.

This is the stored procedure in question:

DELIMITER $$
USE `Valor`$$
CREATE DEFINER=`sean`@`%` PROCEDURE `Critter_GetType`(IN crtr VARCHAR(35))
BEGIN
    SELECT  `type` FROM Valor.CreatureStats WHERE creature = crtr LIMIT 1 ;
END$$

DELIMITER ;
;

This is my PHP code calling it:

$sql = "CALL Valor.Critter_GetType('$cc');"; 
error_log("sql = $sql");
$typeresult = NULL;
$typeresult = $conn->query($sql);
error_log("num rows = $typeresult->num_rows");
while($typerow = $typeresult->fetch_assoc()){
    $type = $typerow['type'];    
}

I set $typeresult = NULL because that was a suggestion I found for a similar problem, but it doesn’t help. The logged SQL works as expected when I call it from outside of the PHP script. The error stops the script, so when I say that the second iteration fails, I’m not implying that there is a third iteration which runs OK.

The first sign that something is wrong is the message

Trying to get property ‘num_rows’ of non-object” in the line “error_log(“num rows = $typeresult->num_rows”)”.

This message occurs, whether or not I have the $typeresult = NULL; line. Then, of course, the “while” loop is where the script-killing error occurs.

This is the first time I’ve used a stored procedure with PHP. I don’t know if that’s relevant, but I have dozens of other SQL calls from inside loops in my PHP which do not have this problem.

How do I add another array entry to an array? [duplicate]

Here’s the code that works.

$options = [
        'title' => $this->name,
        'options' => [
          [
            'id' => 'home_delivery',
            'icon' => $this->settings['icon'],
            'name' => 'Delivery Fee',
            'description' => 'weight:'.$weight,
            'fields' => $note,
            'cost' => $price1,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],
          [
            'id' => 'option_2',
            'icon' => $this->settings['icon'],
            'name' => $cparray[0],
            'description' => 'This is the description for option 2',
            'fields' => '',
            'cost' => $price2,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],
        ],
      ];

The number of different options (different id’s) varies, so I just want to add another id with its variables afterwards, like maybe add this if there’s a 3rd option:


          [
            'id' => 'option_3',
            'icon' => $this->settings['icon'],
            'name' => $cparray[1],
            'description' => 'This is the description for option 3',
            'fields' => '',
            'cost' => $price3,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],

I’m thinking something like this afterwards, but it’s not quite right:

      $options['options'] += ['id' => 'option_3','icon' => $this->settings['icon'],'name' => $cparray[4],'description' => 'This is the description for option 3','fields' => '','cost' => $price2,'tax_class_id' => $this->settings['tax_class_id'],];

I’m finding several options of adding to an array. I’m obviously not doing something right because I don’t fully understand the array construction being made originally. I think it’s creating an array 2 levels deep and I need to add an element to the inner one.

How to speed up Mailchimp campaign/recipient/activity import in PHP (currently ~4 hours) [closed]

I’m writing a PHP script that fetches all campaigns, recipients, and their activities from the Mailchimp API into my application.

Mailchimp’s API limits me to 1,000 records per request, so my script paginates and inserts everything into MySQL in chunks. Even with chunking and INSERT IGNORE bulk inserts, the full run still takes about 4 hours for large lists.

Example snippet of what I’m doing:

$offset = 0;
$count = 1000;
do {
    $email_activities = $MailChimp->get("reports/$campaign_id/email-activity", [
        'offset' => $offset,
        'count'  => $count,
    ]);

    // bulk insert recipients + activities
    // ...
    
    $offset += $count;
} while (count($email_activities['emails']) === $count);

This works but is extremely slow for campaigns with hundreds of thousands of recipients/activities.

Question:
What are effective ways to improve the performance of importing this data?

  • Are there Mailchimp features (like webhooks) I should use instead of repeatedly polling the API?

  • Are there PHP/MySQL optimizations (e.g., LOAD DATA INFILE, parallel jobs, queue/worker model) that can handle millions of rows faster?

Any best practices or architectural suggestions for large Mailchimp data imports would be appreciated.

php CI 3 custom library => passing parameter to someclass

I am really new to Codeigniter, and just learning from scratch. I use CI3.

in native PHP I have a function like this
( to calculate the number of days between two dates) :

function dateDiff($date1, $date2){
$d1 = date_create($date1); $d2 = date_create($date2);
$diff = date_diff($d1,$d2);
$result =  $diff->format("%a");
return $result;
}

I have read the manual of CI3 & tried but no success.

this is my trial code

defined('BASEPATH') OR exit('No direct script access allowed');



class DateDiff { 
public $date1 = ''; public $date2 = '';
public function __construct($params)
{
    $d1 = date_create($this->date1); $d2 = date_create($this->date2);
    $diff = date_diff($d1,$d2);
    $result =  $diff->format("%a");
    return $result;
} }

then I call it in other controller, like this :

$NumberOfDays = $this->load->library('datediff', ['2025-01-01','2025-02-02']); echo $NumberOfDays;

Got error.

how to create such a function in CI3 custom library so I can call it in every controller