Doctrine CLI setup on an existing project

I am completely new to doctrine ORM and my objective is to get the schema from an open source project on a git repository below:
https://github.com/monarc-project/zm-core

I am trying to set up the doctrine CLI for this application to probe the database and generate schema but after installing the dependencies and running doctrine I get the following error:

$php vendor/bin/doctrine

You are missing a "cli-config.php" or "config/cli-config.php" file in your
project, which is required to get the Doctrine Console working. You can use the
following sample as a template:

<?php
use DoctrineORMToolsConsoleConsoleRunner; 

// replace with file to your own project bootstrap
require_once 'bootstrap.php';

// replace with mechanism to retrieve EntityManager in your app
$entityManager = GetEntityManager();

return ConsoleRunner::createHelperSet($entityManager);

From error message it seems there are two paths I can take:

  1. I should not be using doctrine and instead use bin/console. However for console to work I need to upgrade to php 8.1 which doesn’t meet this projects requirements. Thus is not an alternative.

  2. If I still try to use doctrine I cannot see cli-config.php which I am presuming should have been there before. I tried to create one but then don’t know which bootstrap.php should be used by cli-config.php. There are following bootstrap files present in vendor directory.

./vendor/symfony/polyfill-intl-normalizer/bootstrap.php
./vendor/symfony/polyfill-intl-idn/bootstrap.php
./vendor/symfony/polyfill-php81/bootstrap.php
./vendor/symfony/polyfill-ctype/bootstrap.php
./vendor/symfony/polyfill-php73/bootstrap.php
./vendor/symfony/polyfill-php80/bootstrap.php
./vendor/symfony/polyfill-mbstring/bootstrap.php
./vendor/symfony/polyfill-intl-grapheme/bootstrap.php
./vendor/symfony/polyfill-php72/bootstrap.php
./vendor/cakephp/utility/bootstrap.php

After struggling for 2 days I think it is better to get some pointers in case I am completely going on a wrong track.

Thanks a lot for any inputs.

Symfony 5 – How to inject an important Service class easily to a lot of my controllers?

I have a lot of controllers that will need to use the Symfony TranslatorInterface for my alerts, flash messages etc.

What is the best practice to inject a service in a lot of controllers without code repetition?

My first thought was to create BaseController that will extend AbstractController, inject service there in the constructor and extend my current controller by the new BaseController.

Controllers/BaseController.php

class BaseController extends AbstractController
{
    private TranslatorInterface $translator;

    public function __construct(TranslatorInterface $translator)
    {

        $this->translator = $translator;
    }

    public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
    {
        return $this->translator->trans($id, $parameters, $domain, $locale);
    }
}

And from here in the controller that i will need a lot of translations i could:

Controllers/FooController.php

class RegisterController extends BaseController //instead of AbstractController
{

    public function foo(): Response
    {
        
        $this->trans('test.message');

    }
    
    ...

}

Is this a good practice or should i traditionally inject TranslatorInterface inside parameters of my functions? Or maybe every translated controller should have constructor with it?

PHP Script works in curl but GuzzleHttp

I have already checked this post but not working for me: API request works with cURL but not with Guzzle?

PHP Script to access token works perfectly for me

Initialization

$_consumerKey = "consumer key";
$method = "POST";   
$endpoint = 'https://api.twitter.com/oauth/request_token';
$callbackUrl = "https://localhost/script/test.php";

$authorizationParams = array(
    'oauth_callback' => $callbackUrl,
    'oauth_consumer_key' => $_consumerKey,
    'oauth_nonce' => md5( microtime() . mt_rand() ),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_timestamp' => time(),
    'oauth_version' => '1.0'
);

Prepare Signature

function getSignature( $method, $endpoint, $authorizationParams, $urlParams = array() ) {
    $authorizationParams = array_merge( $authorizationParams, $urlParams );
    uksort( $authorizationParams, 'strcmp' );
    foreach ( $authorizationParams as $key => $value ) {
        $authorizationParams[$key] = rawurlencode( $key ) . '=' . rawurlencode( $value );
    }
    $signatureBase = array(
        rawurlencode( $method ),
        rawurlencode( $endpoint ),
        rawurlencode( implode( '&', $authorizationParams ) ),
    );
    $signatureBaseString = implode( '&', $signatureBase );
    $signatureKey = array(
        rawurlencode("consumer token"),
        ""
    );
    $signatureKeyString = implode('&', $signatureKey);
    return base64_encode(hash_hmac('sha1', $signatureBaseString, $signatureKeyString, true));
}

convert array to string

function getAuthorizationString( $authorizationParams ) {
    $authorizationString = 'Authorization: OAuth';
    $count = 0;
    foreach ( $authorizationParams as $key => $value ) { // loop over authorization params array
        $authorizationString .= !$count ? ' ' : ', ';
        $authorizationString .= rawurlencode( $key ) . '="' . rawurlencode( $value ) . '"';
        $count++;
    }
    return $authorizationString;
}
$authorizationParams['oauth_signature'] = getSignature( $method, $endpoint, $authorizationParams );
$apiParams = array(
    'method' => $method,
    'endpoint' => $endpoint,
    'authorization' => getAuthorizationString( $authorizationParams )
);

Curl Request

$curlOptions = array(
    CURLOPT_URL => $apiParams['endpoint'],
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
        $apiParams['authorization'],
        'Expect:'
    )
);
$curlOptions[CURLOPT_POST] = TRUE;
$ch = curl_init();
curl_setopt_array( $ch, $curlOptions );
$apiResponse = curl_exec( $ch );
print_r($apiResponse);

Now when I try to replace curl with Guzzle Http, I get following error. Notice the error details, It said callback url is not same as registered in app. But I am using same callback url and same was used in CURL

Fatal error: Uncaught GuzzleHttpExceptionClientException: Client
error: POST https://api.twitter.com/oauth/request_token resulted in
a 403 Forbidden response: Callback URL not approved
for this client application. A (truncated…) in
C:xampphtdocsscriptvendorguzzlehttpguzzlesrcExceptionRequestException.php:113
Stack trace: #0
C:xampphtdocsscriptvendorguzzlehttpguzzlesrcMiddleware.php(69):
GuzzleHttpExceptionRequestException::create(Object(GuzzleHttpPsr7Request),
Object(GuzzleHttpPsr7Response), NULL, Array, NULL) #1
C:xampphtdocsscriptvendorguzzlehttppromisessrcPromise.php(204):
GuzzleHttpMiddleware::GuzzleHttp{closure}(Object(GuzzleHttpPsr7Response))
#2 C:xampphtdocsscriptvendorguzzlehttppromisessrcPromise.php(153):
GuzzleHttpPromisePromise::callHandler(1,
Object(GuzzleHttpPsr7Response), NULL) #3
C:xampphtdocsscriptvendorguzzlehttppromisessrcTaskQueue.php(48):
GuzzleHttpPromisePromise::GuzzleHttp in
C:xampphtdocsscriptvendorguzzlehttpguzzlesrcExceptionRequestException.php
on line 113

Curl Code

$client = new GuzzleHttpClient();
$response = $client->request('POST', $apiParams['endpoint'], [
    'headers' => [
        'Content-Type' => 'application/json',
        "Authorization" => "OAuth " . $apiParams['authorization']
    ]
]);
$result = json_decode($response->getBody()->getContents(), true);

flutter Upload Images/Files to laravel api

I have an application in which I need to add products that contain more than one image and I already tried the code and it worked well on Postman, but when I use it on flutter it gives me an error **

foreach() argument must be of type array|object, null given

** and I cannot solve the problem
I need to upload more than one image to laravel api
my laravel code

 public function add(Request $request){
    $attars = $request->validate([
            'name' => 'required|string',
            'desc' => 'required|string',
            'status'  => 'required|integer',
            'ad'  => 'required|integer|max:1',
            'top' => 'required|integer|max:1',
            'phoneNumber' => 'required|string',
            'socialMdeia' => 'required|string',
            'webLink' => 'required|string',
            'show' => 'required|integer|max:1',

        ]);
        $imagesName = [];
        if($request->has('images')){
        foreach($request->file('images') as $image){
             $imageName = $image->getClientOriginalName().'-image-'.time().rand(1,1000).'.'.$image->extension();
             $image->move(public_path('product_images'),$imageName);
             $imagesName[] = $imageName;
         }
        }
         $imagesData = json_encode($imagesName);

        $post = productes::create([
        'image' => $imagesData,
        'name' => $attars['name'],
        'desc' => $attars['desc'],
        'status' => $attars['status'],
        'ad' => $attars['ad'],
        'top' => $attars['top'],
        'phoneNumber' => $attars['phoneNumber'],
        'socialMdeia' => $attars['socialMdeia'],
        'webLink' => $attars['webLink'],
        'show' => $attars['show'],
    ]);
 
    return response([
        'message' => 'productes Created',
        'post' => $post
    ], 200);
}

flutter api services

Future<ApiResponse> addProductes(
  var image,
  String name,
  String desc,
  String status,
  String ad,
  String top,
  String phoneNumber,
  String socialMdeia,
  String webLink,
  String show) async {
ApiResponse apiResponse = ApiResponse();
final response =
    await http.post(Uri.parse('${addProductesLink}'), headers: {
  'Accept': 'application/json'
}, body: {
  'images[]': image,
  'name': name,
  'desc': desc,
  'status': status,
  'ad': ad,
  'top': top,
  'phoneNumber': phoneNumber,
  'socialMdeia': socialMdeia,
  'webLink': webLink,
  'show': show
});
switch (response.statusCode) {
  case 200:
    apiResponse.data = productesModel.fromJson(jsonDecode(response.body));
    break;
  case 422:
    final errors = jsonDecode(response.body)['errors'];
    apiResponse.error = errors[errors.keys.elementAt(0)][0];
    break;
  case 403:
    apiResponse.error = jsonDecode(response.body)['message'];
    break;
  default:
    apiResponse.error = jsonDecode(response.body)['message'];
}
return apiResponse;

flutter controller upload images

 uploadImage(context) async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
  allowMultiple: true,
);
List<File> file = result!.paths.map((path) => File(path!)).toList();
images.addAll(file);
if (images != null) {
  for (File file in images) {
    imageList.add(file.path);
  }
  print(imageList);
} else {}

flutter controller send data

 Future addProductesData(image, name, desc, status, ad, top, phoneNumber,
  socialMdeia, webLinks, show) async {
FormData formData = FormData({});
for (String path in imageList) {
  formData.files.add(MapEntry(
      "images[]",
      MultipartFile(File(path),
          filename:
              '${DateTime.now().microsecondsSinceEpoch}.${path.split('.').last}')));
}
ApiResponse response = await addProductesServices().addProductes(image,
    name, desc, status, ad, top, phoneNumber, socialMdeia, webLinks, show);
if (response.error != null) {
  print(response.error);
}

postman

SQLSTATE[42P01]: Undefined table when try to create new user

i’m new in laravel php and i try to create a new user with api post request and when i send this request i have a porblem when i do it
I use psgql and laravel 9. i use that
link to do this and custom somthing

This is my code:
i has User model like

class User extends Authenticatable
{
    use HasApiTokens,HasFactory, Notifiable;

    public $timestamps = false;
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


}

and here is my AuthController to create new user

class AuthController extends Controller
{
    /**
     *  Create User
     * @param Request $request
     * @return User|IlluminateHttpJsonResponse
     */
    public function createUser(Request $request){
        try{
            $validateUser = Validator::make($request->all(),[
                'first_name'=>'required',
                'last_name'=>'required',
                'email'=>'required|email|unique:users,email',
                'password'=>'required'
            ]);

            if($validateUser->fails()){
                return response()->json([
                    'status'=>false,
                    'message'=>'validation error',
                    'errors'=>$validateUser->errors()
                ],401);
            }
            $user = User::create([
                'first_name'=>$request->first_name,
                'last_name'=>$request->last_name,
                'email'=>$request->email,
                'password'=> Hash::make($request->password)
            ]);
            return response()->json([
                'status'=>true,
                'message'=>'User created successfully',
                'token'=>$user->createToken("API TOKEN")->plainTextToken
            ],200);
        }
        catch (Throwable $th){
            return response()->json([
                'status'=>false,
                'message'=>$th->getMessage()
            ],500);
        }

    }
}

and i got problem when i send post request json
like

{
    "status": false,
    "message": "SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "users" does not existnLINE 1: select count(*) as aggregate from "users" where "email" = $1n                                          ^ (SQL: select count(*) as aggregate from "users" where "email" = [email protected])"
}

please help me

woocommerce get chosen shipping method – error Call to a member function get() on null

In my child theme’s functions.php I have this function

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_cash_on_delivery' );

function payment_gateway_cash_on_delivery( $available_gateways ) {

  $selected_shipping_id = WC()->session->get( 'chosen_shipping_methods' )[0];
  
  if ( in_array($selected_shipping_id, ['flexible_shipping_5_5', 'flexible_shipping_7_6' ]) && isset( $available_gateways['bacs'] )) {
    unset( $available_gateways['bacs'] );
  }

  return $available_gateways;

}

WP sends me these warnig about an error at the first row of the function

Podrobnosti chyby
=================
Na řádku č. 61 v souboru /hosting/www/weftsandwarps.com/Zlaterouno/wp-content/themes/storefront-child/functions.php došlo k chybě typu E_ERROR. Chybová zpráva: Uncaught Error: Call to a member function get() on null in /hosting/www/weftsandwarps.com/Zlaterouno/wp-content/themes/storefront-child/functions.php:61
Stack trace:
#0 /hosting/www/weftsandwarps.com/Zlaterouno/wp-includes/class-wp-hook.php(307): payment_gateway_cash_on_delivery()
#1 /hosting/www/weftsandwarps.com/Zlaterouno/wp-includes/plugin.php(189): WP_Hook->apply_filters()
#2 /hosting/www/weftsandwarps.com/Zlaterouno/wp-content/plugins/woocommerce/includes/class-wc-payment-gateways.php(160): apply_filters()
#3 /hosting/www/weftsandwarps.com/Zlaterouno/wp-content/plugins/woocommerce/packages/woocommerce-admin/src/Features/OnboardingTasks.php(91): WC_Payment_Gateways->get_available_payment_gateways()
#4 /hosting/www/weftsandwarps.com/Zlaterouno/wp-content/plugins/woocommerce/packages/woocommerce-admin/src/Features/OnboardingTasks.php(148): AutomatticWooCommerceAdminFeaturesOnboardingTasks::get_settings()
#5 /hosting/www/weftsandwarps.com/Zlaterouno/wp-includes/class-wp-hook.php(307): AutomatticWooComm

My guess is the function is called when no method has been chosen?

net::ERR_CONNECTION_REFUSED, TypeError: Failed to fetch at HTMLDocument.requestItems (script.js:56:5)

I’m trying to use fetch API to get information about my database but I keep getting “net::ERR_CONNECTION_REFUSED
TypeError: Failed to fetch
at HTMLDocument.requestItems (script.js:56:5)” error

Here’s my db.php code to connect to database

    $conn=new mysqli("localhost:3306", "root", "", "online_canteen_system");
    if($conn->connect_errno){
        echo json_encode(['error'=>$conn->connect_error]);
        exit();
    }

and here’s my items.php code

 <?php 
require 'db.php';
header('Access-Control-Allow-Origin: *');  

if($_SERVER['REQUEST_METHOD']==="GET"){
    $stmt = "select name from items where status=1;";
    if($result= $_conn->query($stmt)){
        $arr= array();
        while($name= $result->fetch_assoc()['name']){
            array_push($arr,$name); 
        }
        echo json_encode(['items'=>$arr]);
    }
    else{
        echo json_encode(['error'=>'an error occured']);
    }
    exit();
}

here is the js code for the fetch api

document.addEventListener('DOMContentLoaded', requestItems);
function requestItems() {
    fetch("http://localhost:8080/backend/items.php")
        .then((res) => res.json())
        .then((data) => {
                console.log(data);
            }
        )
        .catch(err => console.log(err));
}

screenshot of error

Make button toggle on by default

I have a project detail menu that I want to be open by default, iam new to coding but the only way to change this is by coding I think. I think I found some relevant code that needs to be changed:

php:

                    <a href="#" id="toggle-project-info" class="btn-lg project-toggle w-100 d-lg-flex justify-content-end">
                    <span class="more-info-text"> <?php _e('Meer projecten'); ?></span>
                    <i class="ml-3 fal fa-angle-up fa-2x text-white"></i>
                </a>

js:

        if (projectDetailToggle.on('click', function (e) {
            e.preventDefault();
            body.toggleClass('project-detail-open');
        })
    );

more js:

  var projectDetailToggle = $('#toggle-project-info');

more php:

    <script>
    (() => {
        const button = document.querySelector('#toggle-project-info');
        if (!button) {
            return;
        }
        
        window.addEventListener('load', () => button.click());
    })();
</script>

I hope this is enough information, when the menu is open by default there still needs to be a option to close it.

If there is missing information please ask!

How to use specific element of one to many relationship in whereHas (Laravel)

I want to get data list , which has many relational rows in another table.
I need to check specific row of relational rows for getting data list from first, for example with it can be the first one and second … (some conditions), but in whereHas you know that we are checking all elements.

$shipments->whereHas('shipment_stops', function ($q) use ($startDate) {
               $q->where('departure_date', '>=', $startDate) ;
            });

This will check all shipment_stops, but I want to check only the last stop with the specific type (for example).

I know that maybe I can create better structure in DB, but anyway, I have this structure.

Thanks

Laravel and Angular CORS

I’ve been through all articles related to this and neither solution is helping me.
I have an API running on a remote server built on Laravel 9. My Kernel.php file has the $middleware array like this:

protected $middleware = [
    AppHttpMiddlewareTrustProxies::class,
    AppHttpMiddlewareCheckForMaintenanceMode::class,
    IlluminateFoundationHttpMiddlewareValidatePostSize::class,
    AppHttpMiddlewareTrimStrings::class,
    IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    AppHttpMiddlewareCORS::class,
];

The CORS.php class has the following code:

public function handle($request, Closure $next)
{
    $request->header('Access-Control-Allow-Origin' , '*');
    $request->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE, PATCH');
    $request->header('Access-Control-Allow-Headers', 'origin, x-requested-with');

    return $next($request);
}

But everytime I try to access it from an Angular application from my localhost I get CORS error. In my angular I have an interceptor for every request which adds the headers to the requests:

  request = request.clone({ headers: request.headers.set('Access-Control-Allow-Origin', '*') });
  request = request.clone({headers: request.headers.set('Access-Control-Allow-Methods', 'GET, OPTIONS')});
  request = request.clone({headers: request.headers.set('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token')});
  request = request.clone({headers: request.headers.set('Access-Control-Allow-Credentials', 'true')});

On the Chrome inspector I can see that the headers are being passed as shown in the picture:
Chrome

I tried also adding the following to my .htaccess/apache config:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Also I’ve tried few variants in the CORS.php handler, tried declaring it as a route middleware, etc, etc. But just won’t work.
I’m pretty sure it’s something very silly that I’m missing, could anyone help?

Image not displaying in LibreOffice Writer

I am trying to load an image programmatically on to a LibreOffice Writer .odt document using PHP & XML.

Instead of the image displaying, it is the code that displays. The code is:

$xml = <<<IMG
<draw:frame draw:name="$filenamefromodf" text:anchor-type=“aschar” svg:width="{$width}cm" svg:height="{$height}cm" draw:z-index=“3”>
<draw:image xlink:href=“testpic1.jpg” xlink:type=“simple” xlink:show=“embed” xlink:actuate=“onLoad” draw:mime-type=“image/jpg”/>
</draw:frame>
IMG;

So, what displays is this:

<draw:frame draw:name="167FP1" text:anchor-type="aschar" svg:width="21.168cm" svg:height="15.876cm" draw:z-index="3"> <draw:image xlink:href="testpic1.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad" draw:mime-type="image/jpg"/> </draw:frame>

Instead of ‘xlink:href=“testpic1.jpg”’

I have also tried

‘xlink:href=“extracteddestination/Pictures/100000000000002B0000002E30BAD18A830F9794.jpg”’.

But to no avail.

I have also tried replacing the heredoc with outer double quotes and inner escaped double quotes, including trying to echo the image.

I have tried relocating the odt template to the same directory on the server as the calling php script in case there is a path problem.

I have successfully loaded text onto the same .odt template document replacing {placeholders} with values from a MYSQL database. It is only the image that I am having problems with

Version: 7.3.6.2 (x64) / LibreOffice Community
Build ID: c28ca90fd6e1a19e189fc16c05f8f8924961e12e
CPU threads: 2; OS: Windows 10.0 Build 19044; UI render: Skia/Raster; VCL: win
Locale: en-GB (en_GB); UI: en-GB
Calc: CL

Resultant .odt document illustrating the problem

How can I apply a saved configuration

I’m working on an admin page and so far I’ve only worked on PHP and a bit of HTML. But now, I have run into a problem, what I would like to know is how I could apply this configuration automatically through HTML as shown in the following script:

<?php 

if(isset($_SESSION['userID']))
{
    $sql_result=$db->ExecuteQuery("SELECT `admin_set` FROM `users` WHERE `id`={$_SESSION['userID']}");
    if($sql_result!=false)
    {
        //exit("Ok");
        $j_settings=$sql_result->fetch_assoc()['admin_set'];
        $_SESSION['admin_set']=$j_settings;
        include_once("./classes/admin_settings.class.php");
        $settings=new AdminSettings((string)$j_settings);
        //echo '<script language="javascript" type="text/javascript" src="path/to/your/file.js"> sidebarColor('.') </script>';
    }
  }

function GetThemeKey(int $index) : string
{
    switch($index)
    {
      case 0:
        return "primary";
      case 1:
        return "dark";
      case 2:
        return "info";
      case 3:
        return "success";
      case 4:
        return "warning";
      case 5:
        return "danger";
      default:
        return "primary";
    }
}
?>
<div class="card-body pt-sm-3 pt-0">
<!-- Sidebar Backgrounds -->
<div>
  <h6 class="mb-0">Sidebar Colors</h6>

</div>
<a href="javascript:void(0)" class="switch-trigger background-color">
  <div class="badge-colors my-2 text-start">
  <span class="badge filter bg-gradient-primary<?=($settings->HighlightColor==0? ' active':'')?>" data-color="primary" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-dark<?=($settings->HighlightColor==1? ' active':'')?>" data-color="dark" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-info<?=($settings->HighlightColor==2? ' active':'')?>" data-color="info" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-success<?=($settings->HighlightColor==3? ' active':'')?>" data-color="success" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-warning<?=($settings->HighlightColor==4? ' active':'')?>" data-color="warning" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-danger<?=($settings->HighlightColor==5? ' active':'')?>" data-color="danger" onclick="sidebarColor(this)"></span>
 </div>
</a>
<!-- Sidenav Type -->
<div class="mt-3">
  <h6 class="mb-0">Sidenav Type</h6>
  <p class="text-sm">Choose between 2 different sidenav types.</p>
</div>
<div class="d-flex">
  <button class="btn bg-gradient-dark px-3 mb-2 active" data-class="bg-gradient-dark" onclick="sidebarType(this)">Dark</button>
  <button class="btn bg-gradient-dark px-3 mb-2 ms-2" data-class="bg-transparent" onclick="sidebarType(this)">Transparent</button>
  <button class="btn bg-gradient-dark px-3 mb-2 ms-2" data-class="bg-white" onclick="sidebarType(this)">White</button>
</div>
<p class="text-sm d-xl-none d-block mt-2">You can change the sidenav type just on desktop view.</p>
<!-- Navbar Fixed -->
<div class="mt-3 d-flex">
  <h6 class="mb-0">Navbar Fixed</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="navbarFixed" onclick="navbarFixed(this)">
  </div>
</div>
<hr class="horizontal dark my-3">
<div class="mt-2 d-flex">
  <h6 class="mb-0">Sidenav Mini</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="navbarMinimize" onclick="navbarMinimize(this)">
  </div>
</div>
<hr class="horizontal dark my-3">
<div class="mt-2 d-flex">
  <h6 class="mb-0">Light / Dark</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="dark-version" onclick="darkMode(this)">
  </div>
</div>

Currently, what this script does is load a sidebar on the right that is displayed when a button is pressed. Specifically, my problem is that I want it to automatically apply the saved color when this element is loaded as well as make it change color when I click on one of the options and call the sidebarColor(this) function in a JavaScript file:

Pink color image

Blue color image

But if I refresh the page this color goes back to color 0 (pink). In the tests that I am doing, I have a PHP class called Admin Settings where I am setting the color 4 (orange) by default, as you can see in the previous code, I have modified the HTML so that the color is selected in the buttons based on this new default value and when I refresh the page, this button is correctly selected. But this color is not automatically applied on the page:

Problem image

So my question is: Where and how would I have to apply the sidebarColor() function so that it is called automatically when the element loads?

sidebarColor function:

function sidebarColor(a) {
  var parent = a.parentElement.children;
  var color = a.getAttribute("data-color");

  for (var i = 0; i < parent.length; i++) {
    parent[i].classList.remove('active');
  }

  if (!a.classList.contains('active')) {
    a.classList.add('active');
  } else {
    a.classList.remove('active');
  }

  var sidebar = document.querySelector('.sidenav');
  sidebar.setAttribute("data-color", color);

  if (document.querySelector('#sidenavCard')) {
    var sidenavCard = document.querySelector('#sidenavCard');
    let sidenavCardClasses = ['card', 'card-background', 'shadow-none', 'card-background-mask-' + color];
    sidenavCard.className = '';
    sidenavCard.classList.add(...sidenavCardClasses);

    var sidenavCardIcon = document.querySelector('#sidenavCardIcon');
    let sidenavCardIconClasses = ['ni', 'ni-diamond', 'text-gradient', 'text-lg', 'top-0', 'text-' + color];
    sidenavCardIcon.className = '';
    sidenavCardIcon.classList.add(...sidenavCardIconClasses);
  }
}

How to change php.ini parameters on ovh webcloud hosting

I would like send emails from my php webpage. I was doing that successfully on my temporary apache hosting on my PC.I need to change php.ini parameters such as sendmail_from, but there is no clear explanation how do I do that on OVH.

I was able to access php.ini file using SSH but I’m unable to save it (no permission).

I was trying to put .platform.app.yaml in the root folder as well as in the www folder using FTP explorer but it is not working either.