Fatal error: Uncaught Error: Class “Smarty” not found

I am new to this PHP and .tpl thing, And I found a template on this website. When openup the XAMPP Apache server, when I go to localhost/terminal, I get this error :

Fatal error: Uncaught Error: Class “Smarty” not found in C:xampphtdocsterminalindex.php:5 Stack trace: #0 {main} thrown in C:xampphtdocsterminalindex.php on line 5

Thanks in advance.

I have tried reinstall XAMPP, even downloaded Smarty in my project folder via composer, But still this error pops up. A homepage was expected.
This is my folder structure :
enter image description here
Code in index.php :

<?php
require_once 'vendor/autoload.php'; // Include Composer's autoload file

// Initialize Smarty
$smarty = new Smarty();

// Example usage
$smarty->setTemplateDir('templates/');
$smarty->assign('name', 'World');
$smarty->display('index.tpl'); // Make sure 'index.tpl' exists in 'templates/'

// Optional: Output a simple message
echo "Smarty is set up and running!";
?>

Apology for anything mistakes because this is my first time asking a question.

Member has protected visibility and is not accessible from the current context.PHP

My editor shows an error even the field is not a protected, now I wondering if model is valid column name or it just a bug in PHP debugging tools/extensions.

I am using VScode and I have this php related extensions:

PHP by DEVSENSE

PHP Profiler by DEVSENSE

PHP Intelephense

I disabled PHP by DEVSENSE and the errors gone so its likely a bug in an extension?

Error message: Member has protected visibility and is not accessible from the current context.PHP(PHP1416)
enter image description here

I tried to use it and I successfully display the data
enter image description here

ProductController.php

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsProduct;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        
    $products = Product::all();

    $products = $products->map(function ($product) {
        return [
            'id' => $product->id,
            'name' => $product->name,
            'brand' => $product->brand,
            'model' => $product->model,
            'description' => $product->description,
            'image_url' => $product->image_url,
            'price' => $product->price,
            'category_name' => $product->category->name ?? 'N/A',
            'supplier_name' => $product->supplier->name ?? 'N/A',
        ];
    });

    return response()->json($products);
    }
}

Product.php in Models

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Product extends Model
{
    use HasFactory;

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }
}

Here is how I create the table in migration

public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('category_id')->constrained('categories')->onDelete('restrict');
            $table->foreignId('supplier_id')->constrained('suppliers')->onDelete('restrict');
            $table->string('name');
            $table->string('brand');
            $table->string('model');
            $table->string('description');
            $table->string('image_url');
            $table->decimal('price');
            $table->timestamps();
        });

        DB::statement('ALTER TABLE products AUTO_INCREMENT = 100000;');
    } 

how can i use csrf token in html file inside laravel?

I don’t use blade.php because the file is uploaded by the admin and goes into storage. And in the html file there is a form that can be filled in, and it always gets 419.

I have tried using @csrf but the tag can only be used if using the .blade.php file, then I also tried to use native php in the same folder as the html file, but it still doesn’t work

Keep Domain Models Free from Doctrine Mapping and Return Collections from ServiceEntityRepository

I’m working on a Symfony project using Doctrine and I want to separate the database mapping from the domain model, following hexagonal architecture and DDD principles. I want my domain entities to be independent of data storage technologies like Doctrine.

What are the best practices for:

  1. Separating Domain Entities from Doctrine Entities: What are recommended ways to map domain entities to Doctrine entities and keep business logic separate from data storage technology?

    • Specifically, I want the domain models to focus solely on the
      business logic, while the mapping to the database should be handled
      separately in the infrastructure layer.
  2. Implementing Repositories: How should I implement repositories in Symfony to adhere to DDD principles while using Doctrine for CRUD operations?

    • Additionally, I have a repository that extends ServiceEntityRepository, and by default, operations like findAll() return an array. I’m looking for a solution that uses this extended class to return a ArrayCollection instead of an array, without rewriting the logic or creating a custom reflective class.

Here is the project structure I want to use:

  • src
    • Domain
      • Collection
      • Model
      • RepositoryInterface
    • Infrastructure
      • Persistence
        • Doctrine
          • Entity/MappingEntity
          • Repository

Code examples or best practices would be very helpful.

Thanks!

Solr search from nested json (php)

I am using solr as my search engine
Saving data in this format

 "id":1,
 "status_id":1,
 "availability":[
      "{children=1, form_date=1726790400, adults=3}",
      "{children=1, form_date=1726099200, adults=9}"
 ],

Trying to fetch details based in from_date > timestamp and adult >= 9

i am new to SOLR

query which i tried is

availability:[from_date:1726790400]

this gives error as
enter image description here

in solr data saved as

enter image description here

and the field type is text_general

PHP 8 + OpenAPI learning resources 2024

I am still strugling in writing the docs using php attributes in symfony project. Symfony 7, php 8. I am looking for better tutorials with practical examples for various cases which happens in real development.

For example current problem I am strugling is that it shows documenation from parent PHP class and not from the extended one while I need to overwrite documenation for one property from parent class. Not going into details, it will probably be better to create separate question for that specific problem.

Tried

https://symfony.com/bundles/NelmioApiDocBundle/current/index.html

https://swagger.io/docs/specification/

https://github.com/zircote/swagger-php/tree/master/Examples

https://swagger.io/specification/

https://symfony.com/doc/current/controller.html#automatic-mapping-of-the-request

https://www.openapis.org/

So this question is not about php itself. No need tutorials about php without OpenApi example. Need combination PHP8 + OpenApi, with attributes.

Some files are missing in Laravel 11

I recently installed Laravel 11, but I’m encountering some issues. I noticed that some files such as Kernel.php, Middleware.php, and api.php are missing. Thinking there was a problem with my initial installation, I reinstalled Laravel 11, but the same files are still missing. Can anyone help me understand what might be going wrong?

I previously worked with Laravel 10 and recently upgraded to Laravel 11. Just installed Laravel 11 twice and encountered the same issue.

PHP: saving a table, then download it

I am making a feature that allows the user to telecahrge table data directly into excel. But I have a problem when saving the file. I write my file with php spreadsheet, then I try to save it, before downloading the created file.
But I can’t save it. Do you know why?

My button to dl:

<td style='border:1px solid grey; border-top:0; border-bottom:0; border-left:0; border-right:0;' align='center' colspan='1'>
    <?php 
    $linkXlsx = './inc/fin/test/'.$_POST['soct'].date('Y-m-d').'.xlsx';
    ?>
    <a href='<?php echo $linkXlsx; ?>' download>
        <img src='./img/excel.png' height='30' alt='Télécharger' />
    </a>
</td>

My function:

function download () {

    $Ecritures = get_ListeEcrituresCegid ( $_POST['soct'] , $_POST['datd'] , $_POST['datf'] );

    $NomFichier = $_POST['soct'].date('Y-m-d').'.xlsx';

    $Classeur = new Spreadsheet();
    $Classeur->getDefaultStyle()->getFont()->setName('Arial Nova');
    $Classeur->getDefaultStyle()->getFont()->setSize(9);
    $Feuille = $Classeur->getActiveSheet(); 

    $Feuille->setCellValue('A1', 'EXERCICE' );
    $Feuille->setCellValue('B1', 'JOURNAL' );
    $Feuille->setCellValue('C1', 'PIECE' );
    $Feuille->setCellValue('D1', 'COMPTE CLIENT' );

    $Writer = new Xlsx($Classeur);
    $Writer->save('./inc/fin/test/'.$NomFichier);

    $cellColors = [
        'A1' => 'd4e6f1',   'B1' => 'd4e6f1',   'C1' => 'd4e6f1',
        'D1' => 'd4e6f1',
    ];

    foreach ($cellColors as $cell => $color) {
        $Feuille->getStyle($cell)->getFill()->setFillType(Fill::FILL_SOLID);
        $Feuille->getStyle($cell)->getFill()->getStartColor()->setRGB($color);
    }

    $rowIndex = 2;

    foreach ( $Ecritures as $e ) {  
        echo $Ecritures;
        $Feuille->setCellValue('A'.$rowIndex, $e['E_EXERCICE']);
        $Feuille->setCellValue('B'.$rowIndex, $e['E_JOURNAL']);
        $Feuille->setCellValue('C'.$rowIndex, $e['E_DEBIT']);
        $Feuille->setCellValue('D'.$rowIndex, $e['E_COMPTECLI']);       
        $rowIndex++;
    }

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $NomFichier . '"');
    header('Cache-Control: max-age=0');

    $Writer = new Xlsx($Classeur);
    $Writer->save('./inc/fin/test/'.$NomFichier);

    return $Writer;
}

Why does passing an instance of IlluminateHttpUploadedFile to a custom cast result in an infinite loop?

I have a Configuration model in which I have implemented a custom cast, the getter works perfectly but let’s look at the setter.

For clarity, I have trimmed down the code samples to only what’s relevant to the context.

App/Models/Configuration.php

use IlluminateDatabaseEloquentModel;

class Configuration extends Model
{ 
    protected function casts(): array
    {
        return [
            'value' => AppCastsConfigValue::class,
        ];
    }
}

App/Casts/ConfigValue.php

use IlluminateContractsDatabaseEloquentCastsAttributes;
use IlluminateDatabaseEloquentModel;
use IlluminateHttpUploadedFile;

class ConfigValue implements CastsAttributes
{ 
    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    { 
        $saveable = $value instanceof UploadedFile || 
                     (isset($value[0]) && $value[0] instanceof UploadedFile);

        echo 1; // Take note of this

        return match (true) {
            ...// Other conditions
            $saveable => $this->doUpload(UploadedFile|array $value),
            ...// Other conditions
            default => (string) $value,
        };
    }
}

Let’s also not bother about the logic for the file uploads, the problem here is that X-Debug throws an infinite loop error after terminating the script when proccessing the upload. But if I straight out return the output, you can see from the image below that the script is run several times before it returns the response, adding upload logic to this ends us in an infinite loop.

example response from postman, here you can see that 1 is being outputed several times.

App/Controllers/ConfigController.php

$config = Configuration::where('key', $key)->first();

$config->value = $value;
$config->save();

On the Controller $key and $value are from a foreach loop of $request->configurations, the above works well when $value is anything but an instance of IlluminateHttpUploadedFile in which case we fall into the infinite loop.

What am I doing wrong here?

Has anybody success with PHP sqlsrv-connection on macOS Sonoma 14.6.1 with XAMPP 8.1.17?

I could install und use the sqlsrv and sqlsrv_pdo driver packages from Microsoft on Windows and Ubuntu24.04 but for MacOS always failed to load connect to the driver at runtime!!!! Not even any php screen error logging works as in the php-file enabled:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$serverName = "1nnnnn“; // Or your server name
$connectionOptions = array(
    "Database" => "Ifffffff“, // Your database name
    "Uid" => "ddddddd“,
    "PWD" => „passwoooord“,
);
//echo "???"; // when this two commented lines are uncommented the site shows ???
//exit(); // when this two commented lines are uncommented the site shows ???
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}
echo "Connection successful!";
?>

XAMPP/Apache works fine for any php but when calling sqlsrv_connect the browser shows ‘unable to open’ and error in php_error_log-file is:

dyld[8251]: Assertion failed: (this->magic == kMagic), function loadAddress, file Loader.cpp, line 163.

The driver files are in correct location:

@MacBook-Pro-von-Ha---en no-debug-non-zts-20210902 % ls
opcache.so  pdo_dblib.so    pdo_sqlsrv.so   pgsql.so    sqlsrv.so

In the php.ini file extensions are loaded:

extension=sqlsrv.so
extension=pdo_sqlsrv.so

Correct access given:

-rwxr-xr-x@ 1 root  admin   26720  6 Apr  2023 pdo_dblib.so
-rwxr-xr-x@ 1 root  admin  333216 11 Sep 15:42 pdo_sqlsrv.so
-rwxr-xr-x@ 1 root  admin  117680  6 Apr  2023 pgsql.so
-rwxr-xr-x@ 1 root  admin  336880 11 Sep 17:14 sqlsrv.so

ODBC installed

g@MacBook-Pro-von-Ha---en no-debug-non-zts-20210902 % odbcinst -j

unixODBC 2.3.12
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /Users/hjbeling/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

How to add dynamic frequency for scheduled command in laravel 11

I have a custom command for taking backups of my laravel website and I want to make its frequency dynamic, how to achieve that??

My command takes two optional options –only-files and –only-db.
These options and the its frequency based on user preference.

my custom command:

<?php

namespace AppConsoleCommands;

use AppModelsScheduledBackup;
use IlluminateConsoleCommand;
use IlluminateConsoleSchedulingSchedule;

class BackupWebsite extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'BackupWebsite:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backup db and files of the website';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $scheduleBackup = self::scheduledBackups();
        if($scheduleBackup){
            $this->call('backup:run', [
                '--only-files' => $scheduleBackup['onlyFiles'],
                '--only-db' => $scheduleBackup['onlyDb'],
            ]);
        }
    }

    function scheduledBackups(){
        $scheduleBackup = ScheduledBackup::first();
        $files = $scheduleBackup->files;
        $database = $scheduleBackup->database;
        $repetition = $scheduleBackup->repetition;
        if($scheduleBackup->is_active){
            if($files && $database){
                return  ['onlyFiles' => false, 'onlyDb' => false, 'repetition' => $repetition];
            }elseif($files){
                return ['onlyFiles' => true, 'onlyDb' => false, 'repetition' => $repetition];
            }elseif($database){
                return ['onlyFiles' => false, 'onlyDb' => true, 'repetition' => $repetition];
            }
        }
        return false;
    }
}

this is my routesconsole.php

// I wanna make "daily()" dynamic. Its value stored in db model "ScheduledBackup" column "repetition"
Schedule::command(BackupWebsite::class)->daily() 

I did it before in laravel 9 like this:

protected function schedule(Schedule $schedule)
    {
        $scheduleBackup = self::scheduledBackups();
        if($scheduleBackup){
            $schedule->command($scheduleBackup['cmd'])->{$scheduleBackup['repetition']}();
        }


    }

Database Query Error with Dibi in PHP Script

I am having a script written like this:

<?php
date_default_timezone_set('Europe/Prague');

// Start time recording
$time_start = microtime(true);

include('./_includes.php');
$db = db_connector::connect();
if (!$db) {
    die('Database connection failed.');
}

// Instantiate audit object
$audit = new Audit(Audit::$udalost_typ[1]);

// Function to fetch data from DB using Dibi with error handling
function fetchFromDB($query, $params = []) {
    global $db;
    try {
        $result = $db->query($query, ...$params)->fetch();
        if (!$result) {
            throw new Exception('Query failed.');
        }
        return $result;
    } catch (Exception $e) {
        throw new Exception('Database query error: ' . $e->getMessage());
    }
}

try {
    // Retrieve JSON input
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON input.');
    }

    // Validate input data
    $requiredFields = ['uuid', 'task_id', 'typ_pozadavku', 'tel_cislo', 'datum'];
    $missingFields = array_filter($requiredFields, fn($field) => empty($data[$field]));

    if (!empty($missingFields)) {
        throw new Exception('Missing fields: ' . implode(', ', $missingFields));
    }

    // Extract and sanitize data
    $uuid = $data['uuid'];
    $task_id = (int)$data['task_id'];
    $typ_pozadavku = $data['typ_pozadavku'];
    $tel_cislo = $data['tel_cislo'];
    $datum = $data['datum'];

    // Begin transaction
    $db->begin();

    // Fetch org_id from device table
    $device = fetchFromDB('SELECT org_id, id, active FROM device WHERE uuid = %s', [$uuid]);
    if (!$device->active) {
        throw new Exception(ERROR_MSG['user_inactive']);
    }
    $org_id = (int)$device->org_id;

    // Fetch szif_task_id from task table
    $task = fetchFromDB(
        'SELECT szif_task_id FROM task WHERE org_id = %i AND id = %i',
        [$org_id, $task_id]
    );
    if (!$task) {
        throw new Exception('Task not found.');
    }
    $szif_task_id = (int)$task->szif_task_id;

    // Validate typ_pozadavku and phone number
    $valid_types = ['0', '1', '2'];
    if (!in_array($typ_pozadavku, $valid_types, true)) {
        throw new Exception(ERROR_MSG['input_validation_error']);
    }
    if (!validate_phonenumber($tel_cislo)) {
        throw new Exception(ERROR_MSG['input_validation_error']);
    }

    // Fetch last request and determine if another request can be sent
    $last_request = fetchFromDB(
        'SELECT last_time_sent, number_sent FROM contact_requests WHERE org_id = %i AND task_id = %i ORDER BY sent_at DESC LIMIT 1',
        [$org_id, $task_id]
    );

    $now = new DateTime();
    $can_send = true;

    if ($last_request) {
        $last_time_sent = new DateTime($last_request->last_time_sent);
        $interval = $now->diff($last_time_sent);

        if (($interval->h < 1 && $last_request->number_sent >= 2) || $interval->days < 1) {
            $can_send = false;
        }
    }

    if (!$can_send) {
        throw new Exception(ERROR_MSG['sync_needed']);
    }

    // Prepare and send IS_MACH request
    $ismach_data = [
        'ji' => $org_id,
        'task_id' => $szif_task_id,
        'typ_pozadavku' => $typ_pozadavku,
        'tel_cislo' => $tel_cislo,
        'datum' => $datum
    ];

    $ch = curl_init('http://localhost/ws/ismach/test_rozhrani.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($ismach_data));

    $ismach_result = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($http_code !== 200 || $curl_error) {
        throw new Exception('IS_MACH Request Failed: ' . $curl_error);
    }

    // Check IS_MACH Response
    $ismach_response = json_decode($ismach_result, true);
    if (json_last_error() !== JSON_ERROR_NONE || $ismach_response['status'] !== 'success') {
        throw new Exception('IS_MACH response error: ' . ($ismach_response['message'] ?? 'Unknown error'));
    }

    // Determine platform from audit logs
    $platform = 'web';
    $audit_log = fetchFromDB('SELECT poznamka FROM audit WHERE uuid = %s ORDER BY created DESC LIMIT 1', [$uuid]);
    if ($audit_log) {
        $note = $audit_log->poznamka;
        $platform = (strpos($note, 'android') !== false) ? 'Android' : ((strpos($note, 'iOS') !== false) ? 'iOS' : 'web');
    }

    $query = 'INSERT INTO contact_requests 
    (org_id, task_id, typ_pozadavku, tel_cislo, datum, last_time_sent, number_sent, platform_of_request, uuid, request_status, request_note, szif_task_id) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';

$params = [
    $org_id, $task_id, $typ_pozadavku, $tel_cislo, $datum,
    $now->format('Y-m-d H:i:s'),
    ($last_request ? $last_request->number_sent + 1 : 1),
    $platform, $uuid, 'ok', 'Request successfully sent to IS_MACH', $szif_task_id
];

    $db->query($query, $params);

    // Commit transaction
    $db->commit();

    // Log success in audit
    $audit->set_dulezitost(Audit::$udalost_dulezitost[0]);
    $audit->execute('Interface - success', json_encode($data), $ismach_result);

    echo json_encode(['status' => 'ok', 'message' => 'Request successful']);

} catch (Exception $e) {
    // Rollback transaction
    $db->rollback();

    // Log error in audit
    $audit->set_dulezitost(Audit::$udalost_dulezitost[1]);
    $audit->execute('Interface - error', json_encode($data), $e->getMessage());

    // Return error response
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

// End time recording and log execution time
$time_end = microtime(true);
$audit->set_exec_time($time_end - $time_start);
?>

It throws an error like:

Array
(
    [status] => error
    [message] => Database query error: Query failed.
)
{"status":"error","message":"Database query error: Query failed."}

But I really don’t know why so…

How to fetch WordPress page with exact style and render on a PHP website?

I was looking for a way to render a WordPress page in a custom PHP based website. I succeeded in that but it is not styled as it is on WordPress.

Please tell me how can I fetch the page exactly as it is on WordPress?

I have this code to display the webpage:

<?php include('view/header_copy.php'); ?>

<div class="pt-20 pt-md-18 pt-lg-20 pb-13 pb-md-17 pb-lg-33 px-10 px-md-20 px-lg-20 px-xl-30">
  <div id="wp-content-container"></div>
</div>

<script>
  fetch('https://blogs.domainnamehere.com/wp-json/wp/v2/pages?slug=success-stories')
  .then(response => response.json())
  .then(data => {
    const page = data[0];
    document.getElementById('wp-content-container').innerHTML = page.content.rendered;
  })
  .catch(error => console.error('Error fetching page:', error));
</script>

<?php include('view/footer_copy.php'); ?>

Why I am having the email protected problem in laravel? [closed]

I have a view on which I am displaying some text. That is generating through API url. When I am printing that page in flutter application. I am getting the problem that the email in that text is converting to email protected. What is the solution to this.

this is the code:

<center style="margin-bottom: 30px;" class="">
        <strong class="company-header">{!! nl2br(e(str_replace(',', "n", $adminUser->company_header))) !!}</strong>
      
    </center>

And this is the output of the view on web:
enter image description here

When I am printing this in the flutter application, the email changes to email protected.

Getting error:invalid_grant in Salesforce for grant type authorization_code if giving authorization from another org

I am having issue on granting authorization for user that is outside of my app’s org.

here is the http post request I am trying to make, I am using authorization_code so I can get refresh token as I need it.

$response = $client->post($tokenUrl, [
 'form_params' => [
  'grant_type' => 'authorization_code',
  'client_id' => $clientId,
  'client_secret' => $clientSecret,
  'redirect_uri' => $redirectUri,
  'code' => $authorizationCode,
 ],
]);

I am not sure if I’m missing something on my salesforce set up, below are screenshots:

Screenshot of Oauth Settings 1

Screenshot of Oauth Settings 2

Oauth Policy Settings

Here is a screenshot of granting permission

Permission Grant

The error I got

{“error”:”invalid_grant”,”error_description”:”authentication failure”}

I want to successfully grant any org to access my connected app