php Session Problems

I have a problem with my Website. It’s not passing session variables between pages. I made a simple 2 files to pass session variables between them but it’s not working.
page1.php code as follows

    <?php
        session_start();
        $_SESSION['id']='3';
        $_SESSION['name']='sameer';
        header('location:page2.php');
        exit();
    ?>

page2.php code as follows

    <?php
        session_start();
        echo $_SESSION['id'].'<br>';
        echo $_SESSION['name'];
        echo 'finish';
    ?>

in my localhost it’s working and showing the two variables and say finish.

in my hosting server it says only finish without passing the variables.

I tried with my hosting technical support team but they did not solve the problem.

is there anything to do to let the server pass the session variables between these two pages.

Thanks

Video dimensions in php [duplicate]

Is there a way to get the width and height of a video in php? I have uploaded images and I can get their dimensions using GD or IMagick but I haven’t found a way to get the dimensions of a video. I don’t want to use getID3.
Thank you.

php documentation
searched on google

Loaders & jquery not working in the livewire pagination

my code is working correctly in the first page, but when I navigate to the second page the loading icons and the jQuery effects not working correctly when I submitting a form.
It’s insert the data without showing the loading icon.

my view

 <x-livewire.form.buttons.save type="submit" title="{{ __('buttons.save') }}" wire:target="form_data.{{ $user->id }}.file" wire:loading.attr="disabled">
                                        <div wire:target="save({{ $user->id }})" wire:loading.remove>
                                            {{ __('buttons.save') }}
                                        </div>

                                        <div wire:target="save({{ $user->id }})" wire:loading>
                                            <i class="fa-solid fa-spinner fa-spin"></i>
                                        </div>
                                    </x-livewire.form.buttons.save>

php

public $page;
public $name = '';
public $badge_number = '';


public $form_data = [];
public $permission_type = [];

protected $queryString = [
    'page',
    'name',
    'badge_number',
];

public function updatingName()
{
    $this->resetPage();
}

public function updatingBadgeNumber(){

    $this->resetPage();
}

public function render()
{
    $name = $this->name;
    $badge_number = $this->badge_number;

    if($name === '' && $badge_number === '')
    {
        $users = User::orderBy('name')
        ->paginate(15);
    }
    else
    {
        $users = User::where('name', 'like', '%' . $name . '%')
        ->where('badge_number', 'like', $badge_number . '%')
        ->orderBy('name')
        ->paginate(15);
    }

    return view('livewire.attendances.daily', [
        'users' => $users,
        'page' => $this->getPage()
    ]);
}

Cannot clear APCu Cache from Console, it’s shared in the Webserver memory and not accessible from the CLI

I’m trying to clear doctrine cache after updating entities, so that there won’t be errors like this after adding new property:

Uncaught Error: Typed property ProjectEntitiesEntity::$property must not be accessed before initialization in ...

php cli-config.php orm:clear-cache:metadata and php cli-config.php orm:clear-cache:result works fine but when I’m trying to execute php cli-config.php orm:clear-cache:query I get Error:

In QueryCommand.php line 43:
                                                                                                              
  Cannot clear APCu Cache from Console, it's shared in the Webserver memory and not accessible from the CLI.

If I disable APCu for CLI in php.ini like this:

apc.enable_cli=0

then orm:clear-cache:query results in:

In MemcachedAdapter.php line 300:
                                                     
  MemcachedAdapter client error: connection failure

as Doctrine defaults to MemcachedAdapter if APCu is unavailable.

When creating EntityManager with isDevMode set to true, it works fine (no errors occur) but I’m not convinced it’s a valid solution.

new EntityManager(
    DriverManager::getConnection($params),
    ORMSetup::createAttributeMetadataConfiguration(
        paths: [__DIR__ . '/../Entities'],
        isDevMode: true, // should be false as it's production
        proxyDir: __DIR__ . '/../../../tmp',
    ),
);

Versions:

  1. PHP: 8.2
  2. Doctrine ORM: 3.1
  3. Doctrine DBAL: 4.0

I’m not using Symfony, just plain Doctrine.

How to approach this issue so that I could correctly clear the production cache?

Show or Hide Text added after pricing depending on User Group or login status

I am using a B2B plugin that allows me to create different pricing for different user groups. The standard pricing is shown for all users until they sign up and account and are added to a group with better pricing (for wholesale customers etc).

I have added some code to say Retail Pricing after the standard pricing. The problem is I don’t want this suffix to show once a user is logged in OR to certain user groups as the pricing is no longer retail for these customers, its wholesale.

The code I used is:

function woo_text_after_price( $price ) {
    $price .= ' Retail Price';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'woo_text_after_price' );
add_filter( 'woocommerce_cart_item_price', 'woo_text_after_price' );

The B2B plugin I am using is called WooCommerce B2B and was purchased from Code Canyon developed by code4lifeitalia.

Thank you in advance.

I have not tried any resolution yet as I don’t know what to try. I know I would need some kind of filter or rule but I don’t know how to create one.

php_mongodb.dll for windows 1.15

I’m trying to find the dll driver for mongodb. I want to run my project in laragon and I need de mongodb.dll version 1.15 or higher, howevwer I can’t find this dll version.

I found the others .dll in this url, but no the version 1.15

help?

Control character error, possibly incorrectly encoded in php [closed]

<?php
$jsonString = '[["7155206488121","Size","700C","",""],["","","26""]]';

$data = json_decode($jsonString);

if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON decoding failed with error: " . json_last_error_msg();
} else {
    var_dump($data);
}
?> 

how to fix this problem.

I see output like this

<?php
$data = array(
    array("7155206488121","Size","700C","",""),
    array("","","26"")
);
print_r($data);
?>

A special character issue is occurring while decoding JSON.

I have tried three which are below.

try 1 :

<?php
$jsonString = preg_replace('/[[:cntrl:]]/', '', $jsonString);
$data = json_decode($jsonString, true);
?>

try 2 :

<?php
$jsonString = iconv('UTF-8', 'UTF-8//IGNORE', $jsonString);
$data = json_decode($jsonString, true);
?>

try 3 :

<?php
if (!mb_check_encoding($jsonString, 'UTF-8')) {
    $jsonString = mb_convert_encoding($jsonString, 'UTF-8');
}
$data = json_decode($jsonString, true);
?>

I have tried three it doesn’t work.

If you don’t understand my question, read the message again calmly.

Why does Visual Studio Code continue to indent after a }?

i got a strange issue,
i frequently have to used the auto indent on VS but when i’m in php, it seems to act strange when i’m coding classes, (thats really annoying cause im at 8 indent now at the start of a class[enter image description here])
enter image description here

i’m explaining :

normal indent :

class 1{
   setting
   setting
   function(){
      setting
   }
}
class 2{
   setting
...
}

what i am having:

class 1{
   setting
   }
   class 2
      setting
      }
      class 3{
         setting
        }

confusion in unix socket to use for query in postgresql through php

i try to build website in ubuntu vps using nginx, php7.4, and PostgreSQL.
my goal is using unix socket to communicate through ajax-phpfpm-postgresql to execute query sql in PHP program.

i have change my serverblock to use php7.4-fpm

location ~ .php$ {
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

sudo nano /etc/php/7.4/fpm/pool.d/www.conf and change variable to bellow

listen = /run/php/php7.4-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

and sudo nano /etc/postgresql/13/main/postgresql.conf and turn

listen address='*'
 unix_socket_directories = '/var/run/postgresql'
#if I change unix socket directories to /run/php/, I cant access postgresql through terminal#

and change pg_hba.conf. the local method into thrust (because I still confused what should id do)

local   all             all                                     trust

and change pg_connect variable in php program to use unix

$host = 'var/run/postgresql';
$dbname = 'confidential';
$user = 'confidential';
$password = 'confidential';

it’s still not working even i try to check all of the error log in nginx, PHP, and postgresql,and the ajax respond is still error output,
my question

  1. which one unix socket I have to use in this server in each file above? php7.4-fpm.sock or the PostgreSQL
  2. do anybody have complete tutorial that have the same goal with mine?

source of tutorial(maybe i miss some tutorial link)
https://www.tecmint.com/connect-nginx-to-php-fpm/
https://medium.com/@danilsyah/install-web-server-nginx-php8-0-fpm-postgresql-v12-in-ubuntu-server-22-04-d0113495115d
https://gustavostraube.wordpress.com/2009/10/02/connecting-php-to-postgresql-via-unix-sockets/
https://www.php.net/manual/en/function.pg-connect.php
https://www.digitalocean.com/community/tutorials/php-fpm-nginx

Using Carbon to generate multiple dates with an interval in a range, but only ones in the future

I need to generate multiple dates between two dates, based on an interval (eg. weekly, every 2 weeks, monthly, …), but I only need the ones in the future.

For that I’m using the Carbon 2.72.3 library and I came up with the following code:

$interval = CarbonInterval::week();
$startDate = Carbon::create(2024, 3, 17);
$endDate = Carbon::create(2024, 4, 1);
$amount = 4;

$period = CarbonPeriod::interval($interval)
    ->setStartDate($startDate)
    ->addFilter(fn(Carbon $carbon) => $carbon->isFuture(), 'isFuture')
    ->addFilter(fn(Carbon $carbon) => !$endDate || $carbon->isBefore($endDate))
    ->setRecurrences($amount);

dd($period->toArray());

Unfortunately, this just works sometimes (meaning: Not with all dates / intervals) and I can’t tell exactly under what conditions it works and when it doesn’t work.

With the dates above, Carbon throws an CarbonExceptionsUnreachableException with the message Could not find next valid date.. If I reduce the amount to 1, it works, but only returns 2024-03-24 as a date (which is then expected, but doesn’t solve my issue).

With other data, such as this, it works as expected: It returns 4 dates according to the interval in relation to the start date, but only the ones in the future.

$interval = CarbonInterval::month();
$startDate = Carbon::create(2022, 6, 2);
$endDate = null;
$amount = 4;

If I set the $endDate = Carbon::create(2024, 4, 1);, it also stops working. I suspect that it sometimes happens when it cannot generate the $amount of dates. But this doesn’t seem to be the case always, as the following setup should be able to generate at least 4 dates, though the same exception is thrown:

$interval = CarbonInterval::year();
$startDate = Carbon::create(2022, 6, 2);
$endDate = Carbon::create(2028, 4, 1);
$amount = 4;

Expected dates:

  • 2024-06-02
  • 2025-06-02
  • 2026-06-02
  • 2027-06-02

Though in this case it only works if I set the end date to 2029-04-01, which doesn’t make sense to me as the last date is already in 2027.

Code vulnerable to unauthorized arbitrary post creation due to a missing capability check on the check_for_saas_push() function

Trying to improve the code below, which is missing a capability check on the function below, to stop the vulnerability where people can create arbitary post creation, and content, but not sure how to change and amend the below code to make it safe.

Any ideas would be really appreciated.

Existing code below:

public static function check_for_saas_push() {

    if ( ! isset( $_REQUEST['json_product_push'] ) || ( isset( $_REQUEST['json_product_push'] ) && 'true' !== $_REQUEST['json_product_push'] ) )
        return;

        error_reporting( E_ERROR );

        if ( ! empty( $_POST['product'] ) ) {
            $product = stripslashes( $_POST['product'] );
            $product = json_decode( $product );

            $download_url = Sputnik::API_BASE . '/download/' . $product->post_name . '.zip';
            $thumb_url    = $product->thumbnail_url;

            //Check if local product exists - if so, update it, if not, don't.
            $local = get_posts( array(
                'pagename' => $product->post_name,
                'post_type' => 'wpsc-product',
                'post_status' => 'publish',
                'numberposts' => 1 )
            );

            $user_check = get_user_by( 'email', $product->author_email );

            if ( $user_check ) {
                $product->post_author = $user_check->ID;

                if ( ! in_array( 'vendor-administrator', $user_check->roles ) )
                    $user_check->add_role( 'vendor-administrator' );
            }
            else {
                $product->post_author = wp_insert_user( array( 'role' => 'vendor-administrator', 'user_email' => $product->author_email, 'user_pass' => wp_generate_password(), 'user_login' => $product->author_email ) );
            }

            $product = (array) $product;
            unset( $product['guid'] );
            unset( $product['post_date_gmt'] );
            unset( $product['post_date'] );

            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');

            if ( ! empty( $local ) ) {
                $product['ID'] = $local[0]->ID;
                $new_id = wp_update_post( $product );
            } else {
                unset( $product['ID'] );
                // Doesn't exist, create it.  Then, after created, add download URL and thumbnail.
                $new_id = wp_insert_post( $product );
            }

            update_post_meta( $new_id, '_download_url', $download_url );

            foreach ( $product['meta'] as $key => $val ) {
                if ( '_wpsc_product_metadata' == $key )
                    continue;

                if ( '_wpsc_currency' == $key )
                    continue;

                update_post_meta( $new_id, $key, $val[0] );
            }



            $thumb = media_sideload_image( $thumb_url, $new_id, 'Product Thumbnail' );

            if ( ! is_wp_error( $thumb ) ) {
                $thumbnail_id = get_posts( array( 'post_type' => 'attachment', 'post_parent' => $new_id ) );

                if ( ! empty( $thumbnail_id ) ) {

                    $thumbnail = set_post_thumbnail( $new_id, $thumbnail_id[0]->ID );
                    echo json_encode( array( 'set_thumbnail' => $thumbnail, 'post_id' => $new_id ) );
                    die;
                }
                die;
            }
            die;
        }

    exit;
}

Researching online, and looking into ways of changing things.

Would incorporating the below code help with (this new to php and learning):

if ( ! current_user_can( 'manage_options' ) ) {
wp_die(); }

Laravel controller does not get correct parameter from route definition, and enters in the wrong controller function

I have this route defined:

Route::match(['get', 'post'], '/{class}/{function}/', [OldBackendController::class, 'apiV1']);

If I do this request:

POST /api/v2_1/wishlist/archive

Laravel enters int the OldBackendController, and the value of $class variable (in the controller), is this:

api/v2_1/wishlist

Why? It shouldn’t enter in the controller, cause the request does not contains 2 variables, but 4.

The strange thing is if in the controller I print $request->segments() value, I get all 4 segment:

Array
(
    [0] => api
    [1] => v2_1
    [2] => wishlist
    [3] => archive
)

Why wamp server doesn’t work on localhost?

enter image description here

enter image description here

I successfully installed wamp-manager in my device, but when I run it in browser localhost doesn’t work. I have tried to change the port from 8081 to 80, 8080, or another port, but it doesn’t work anyway. Please, help me! I’m literally dying inside if I can’t work with my website. I have tried Wamp Server.

Any tips on integrating status check features for social grant programs like SASSA, SRD, and R350, especially for SRD Grant Status updates?

Does anyone have experience integrating a status check feature for social grant applications, specifically for programs like SASSA, SRD, and R350? I’m looking for insights on how to implement a reliable status check system that can provide real-time updates to applicants regarding their grant statuses. Any suggestions or recommended tools/APIs for integrating SRD Grant Status or similar functionalities would be greatly appreciated. Thank you!

Seeking advice on covertly incorporating status check functionalities for social grant programs such as SASSA, SRD, and R350, with a particular focus on SRD Grant Status updates.

Php, CURL, Operation timed out after 60010 milliseconds with 0 bytes received

I’m using this function to make cURL calls:

$crl = curl_init();
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($crl, CURLOPT_HTTPHEADER, ['Expect:']);
curl_setopt($crl, CURLOPT_POSTFIELDS, $postParameters);
curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, $timeOut);
curl_setopt($crl, CURLOPT_TIMEOUT, $timeOut);
$answer = curl_exec($crl);
$answer = [
    'result' => $answer,
    'error' => curl_error($crl),
    'errno' => curl_errno($crl)
];
curl_close($crl);

this works very fine so far. If the size of the $postParameters is about 0.5 MB, it gets the answer in 2-3 seconds.
But when it’s about 1 MB, it never returns. I get timeout, no matter how high I set (60, 120…). It holds for 2 minutes and timeout. And it looks it doesn’t even get the server, I mean if I do loggings in the server it looks it just wont get executed.
I tried to set max_input_vars to 1000000, post_max_size to 1024M (on server side), nothing works.