Laravel Search by swapping origin and destination forms

I have a project to check shipping rates using Laravel 11, I already have a table with prices that have been determined from origin to destination.

enter image description here

I use a search form with these 2 fields, but how can I swap the search, for example origin 1 to destination 2 or origin 1 to destination 2, and the results are still in the same column. And if the origin and destination are different then the results should not be displayed or will be null. For example, origin 3 to destination 2.

I use the get method but the search results do not match what is in the database table.
enter image description here
Why does a search with input that does not match the data table still appear with a different origin and destination? The result should be null because it is not in the column?

I have tried the following code but it doesn’t work as I expected. And This is some of the code I used

From Search

<form action="{{ url('rates') }}" method="GET">
      @csrf
      <div class="form-row align-items-center row">
          <div class="col-md-5">
              <label>Origin</label>
              <select class="form-control single-select-field" name="origin">
                 <option selected>Origin...</option>
                   @foreach ($cities as $city)
                   <option value="{{ $city->id }}">{{ $city->id}}</option>
                   @endforeach
              </select>
            </div>
          <div class="col-md-5">
            <label>Destination</label>
            <select class="form-control single-select-field" name="destination">
               <option selected>Destination...</option>
                  @foreach ($cities as $city)
                    <option value="{{ $city->id }}">{{ $city->id }}</option>
                  @endforeach
            </select>
          </div>
          <div class="col-md-6 my-3">
             <button type="submit" class="btn btn-warning btn-block">Check Rates</button>
          </div>
         </div>
 </form>

Rates Controller

$origin = $request['origin'];
$destination = $request['destination'];
$result = RouteModel::where(['origin' => $origin, 'destination' => $destination])->orWhere(['destination' => $origin, 'origin' => $destination])->first();
return $result;

Thank you for the help

Encrypt Query Parameter in Flutter and decrypt in PHP to get Data

The IV and the key are up here.


 // Verschlüsselt den Job-Parameter
  String encryptJob(String job) {
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
    final encrypted = encrypter.encrypt(job, iv: iv);
    return encrypted.base64; // Base64-String des verschlüsselten Textes
  }

  String encryptMessage (String message){
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
    final encrypted = encrypter.encrypt(message, iv:iv);
    return encrypted.base64;
  }

Future<void> fetchData() async {
    final message = '&function=';

    // Verschlüsselung des Job-Parameters
    final encryptedJob1 = encryptJob('job=$job1');
    final encryptedJob2 = encryptJob('job=$job2');
    final encryptedJob3 = encryptJob('job=$job3');
    final encryptedJob4 = encryptJob('job=$job4');


    //IV und verschlüsselte Daten für die URL korrekt kodieren
    final encodedIV = Uri.encodeComponent(iv.base64);
    final encodedJob1 = Uri.encodeComponent(encryptedJob1);
    final encodedJob2 = Uri.encodeComponent(encryptedJob2);
    final encodedJob3 = Uri.encodeComponent(encryptedJob3);
    final encodedJob4 = Uri.encodeComponent(encryptedJob4);
    final encryptedMessage = encryptMessage('$message$encodedJob4');

    // Jetzt den IV korrekt in Base64 umwandeln und in die URL einfügen
    final webServiceURl = 'http://localhost/get_encrypt_request.php?iv=$encodedIV$message$encodedJob4';
    final url = Uri.parse(webServiceURl);
    final response = await http.get(url);

    print('$urln');
    print(response.body);

    setState(() {
      data = response.body;
    });

    if (response.statusCode == 200) {
      print('Erfolgreiche Antwort');
    } else {
      print('Fehler beim Abrufen der Daten: ${response.statusCode}');
    }
  }

My Task is to encrypt the queryParamters that no plaintext can be seen affter the ?.
I can encrypt my job but not my queryparameter in that case the message per se.
And after that the queryparameter must than be decrypt in php and send me the data from the job.

// Empfange den IV und die verschlüsselten Daten
$iv = isset($_GET['iv']) ? $_GET['iv'] : '';
$data = isset($_GET['function']) ? $_GET['function'] : '';
  final encryptedMessage = encryptMessage('$message$encodedJob4');

In this line you can see that i have tried to put the message with the job but than for the job it is a “double encryption” and that is indeed not that sence.

    final webServiceURl = 'http://localhost/get_encrypt_request.php?iv=$encodedIV$encryptedMessage';

When i change the queryparameters to this for sure it doesn’t work.

Dynamic pagination using JavaScript Datatable is not working? [closed]

Upon reinitializing warning is shown and existing pagination is missing, current pagination show the default 50 records only.

I have alternatively implemented another pagination which is working,but I require the in built javascript pagination.

Below is my HTML code-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    

<!-- Styles -->
<link href="assets/css/style.css" rel="stylesheet">
<style>
    #pagination a {
        padding: 5px;
        text-decoration: none;
        color: #007bff;
    }
    #pagination .current {
        padding: 5px;
        font-weight: bold;
        color: #000;
    }
    #loading-message {
        text-align: center;
        display: none;
    }
</style>
 <title> Dashboard</title>
<div class="content-wrap">
    <div class="container mt-5">
        <h5>Journal Subscriptions and Revenue</h5>
        <table id="bootstrap-data-table-export" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Cust_No_</th>
                    <th>Journal_ID</th>
                    <th>Content_Year</th>
                    <th>Subject</th>
                    <th>Journal_Title</th>                
                    <th>Type_of_Subscription</th>
                </tr>
            </thead>
            <tbody id="table-body">
                <!-- Data will be loaded here -->
                <?php  foreach ($results as $row): ?>
        <tr>
            <td><?= htmlspecialchars($row['Name']); ?></td>
            <td><?= htmlspecialchars($row['Cust_No_']); ?></td>
            <td><?= htmlspecialchars($row['Journal_ID']); ?></td>
            <td><?= htmlspecialchars($row['Content_Year']); ?></td>
            <td><?= htmlspecialchars($row['Subject']); ?></td>
            <td><?= htmlspecialchars($row['Journal_Title']); ?></td> 
            <td><?= htmlspecialchars($row['Type_of_Subscription']); ?></td>
                                                                
        </tr>
        <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Pagination Links -->
        <div id="pagination">
            <!-- Pagination links will be loaded here -->     
            <?php if ($page > 1): ?>
                <a href="?page=<?= $page - 1; ?>">Previous</a>
            <?php endif; ?>

            <span>Page <?= $page; ?> of <?= $totalPages; ?></span>

            <?php if ($page < $totalPages): ?>
                <a href="?page=<?= $page + 1; ?>">Next</a>
            <?php endif; ?>                  
        </div>
    </div>
    <div id="loading-message">
        <p>Loading more data...</p>
    </div>
</div>
<script>
    let currentPage = 1;
    let totalPages = 1;
    let loading = false;

    function loadData(page) {
        $.ajax({
            url: 'journal_data_19.php',
            type: 'GET',
            data: { page: page },
            dataType: 'json',
            success: function(data) {
                if (data.error) {
                    alert('Error: ' + data.error);
                    return;
                }
                totalPages = data.totalPages;
                currentPage = data.currentPage;

                const tableBody = $('#table-body');
                tableBody.empty(); // Clear existing data

                data.results.forEach(row => {
                    tableBody.append(
                        `<tr>
                            <td>${row.Name}</td>
                            <td>${row.Cust_No_}</td>
                            <td>${row.Journal_ID}</td>
                            <td>${row.Content_Year}</td>
                            <td>${row.Subject}</td>
                            <td>${row.Journal_Title}</td>
                            <td>${row.Type_of_Subscription}</td>
                        </tr>`
                    );
                });

                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
            }
        });
    }

    function updatePagination() {
        const paginationElement = document.getElementById('pagination');
        if (paginationElement) {
            let paginationHtml = '';

            // Previous button
            if (currentPage > 1) {
                paginationHtml += `<a href="#" onclick="loadData(${currentPage - 1}); return false;">Previous</a> `;
            }

            // Page numbers
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHtml += `<span class="current">${i}</span> `;
                } else {
                    paginationHtml += `<a href="#" onclick="loadData(${i}); return false;">${i}</a> `;
                }
            }

            // Next button
            if (currentPage < totalPages) {
                paginationHtml += `<a href="#" onclick="loadData(${currentPage + 1}); return false;">Next</a>`;
            }

            paginationElement.innerHTML = paginationHtml;
        } else {
            console.error('Pagination element not found');
        }
    }

    function loadMoreData(page) {
        if (loading) return; // Prevent multiple requests at the same time
        loading = true;
        $('#loading-message').show();

        $.ajax({
            url: 'journal_data_19.php',
            type: 'GET',
            data: { page: page },
            dataType: 'json',
            success: function(data) {
                if (data.error) {
                    alert('Error: ' + data.error);
                    return;
                }
                totalPages = data.totalPages;
                currentPage = data.currentPage;

                const tableBody = $('#table-body');

                // Append the fetched rows to the table
                data.results.forEach(row => {
                    tableBody.append(
                        `<tr>
                            <td>${row.Name}</td>
                            <td>${row.Cust_No_}</td>
                            <td>${row.Journal_ID}</td>
                            <td>${row.Content_Year}</td>
                            <td>${row.Subject}</td>
                            <td>${row.Journal_Title}</td>
                            <td>${row.Type_of_Subscription}</td>
                        </tr>`
                    );
                });

                loading = false;
                $('#loading-message').hide();
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                loading = false;
                $('#loading-message').hide();
            }
        });
    }

    $(document).ready(function() {
        loadData(currentPage); // Initial load

        // Event listener for scrolling
        $(window).scroll(function() {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100 && !loading && currentPage < totalPages) {
                loadMoreData(++currentPage);
            }
        });
    });




    //JAVASCRIPT PAGINATION SECTION---------------------$(document).ready(function() {
    $('#bootstrap-data-table-export').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "journal_data_19.php",
            "type": "GET",
            "dataSrc": function (json) {
                // Check if json.data exists and contains data
                if (json.data && json.data.length > 0) {
                    return json.data;
                } else {
                    console.error('No data found or incorrect format');
                    return [];
                }
            },
            "error": function (xhr, error, thrown) {
                console.error('An error occurred while fetching data:', error);
            }
        },
        "pageLength": 50,
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "columns": [
            { "data": "Name" },
            { "data": "Cust_No_" },
            { "data": "Journal_ID" },
            { "data": "Content_Year" },
            { "data": "Type_of_Subscription" },
            { "data": "Journal_Title" },
            { "data": "Subject" }
        ],
        "paging": true,
        "searching": true,
        "ordering": true,
        "dom": 'Bfrtip',
        "buttons": ['copy', 'csv', 'excel', 'pdf', 'print'],
        "scrollY": "500px",
        "scrollCollapse": true,
        "responsive": true
    });
});

    </script>
<script src="assets/js/lib/jquery.nanoscroller.min.js"></script>
<!-- nano scroller -->
<script src="assets/js/lib/menubar/sidebar.js"></script>
<script src="assets/js/lib/preloader/pace.min.js"></script>
<!-- sidebar -->

<!-- bootstrap -->

<script src="assets/js/scripts.js"></script>
<!-- scripit init-->
<script src="assets/js/lib/data-table/datatables.min.js"></script>
<!-- <script src="assets/js/lib/data-table/buttons.dataTables.min.js"></script> -->
<script src="assets/js/lib/data-table/dataTables.buttons.min.js"></script>
<script src="assets/js/lib/data-table/buttons.flash.min.js"></script>
<script src="assets/js/lib/data-table/jszip.min.js"></script>
<script src="assets/js/lib/data-table/pdfmake.min.js"></script>
<script src="assets/js/lib/data-table/vfs_fonts.js"></script>
<script src="assets/js/lib/data-table/buttons.html5.min.js"></script>
<script src="assets/js/lib/data-table/buttons.print.min.js"></script>
<script src="assets/js/lib/data-table/datatables-init.js"></script>

This is my PHP code-

<?php
session_start();
ob_start(); // Start output buffering

if (!isset($_SESSION['loggedin'])) {
    header('Location: index.html');
    exit;
}

ini_set('max_execution_time', 0); // No time limit

$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'destination_db';

// Number of records to display per page
$limit = 50;

// Get the current page number from the AJAX request
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1; // Ensure page number is at least 1

// Calculate the offset for the SQL query
$offset = ($page - 1) * $limit;

// Parameters from DataTables
$start = $_GET['start'];
$length = $_GET['length'];
$searchValue = $_GET['search']['value']; // For search filtering

try {
    $pdo = new PDO("mysql:host=$DATABASE_HOST;dbname=$DATABASE_NAME;charset=utf8", $DATABASE_USER, $DATABASE_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get the total number of records
    $totalStmt = $pdo->query('SELECT COUNT(*) FROM journal_subscription js 
                              JOIN journal_revenue jr 
                              ON js.Cust_No_ = jr.Ship_to_no_ 
                              AND js.Type_of_Subscription = jr.Type_of_Sales 
                              AND js.Content_Year = jr.Content_Year 
                              AND js.Journal_ID = jr.Journal_ID');
    $totalRows = $totalStmt->fetchColumn();
    $totalPages = ceil($totalRows / $limit);

    // Prepare the SQL query with LIMIT and OFFSET
    $stmt = $pdo->prepare('SELECT js.Cust_No_, js.Name, js.Journal_ID, js.Content_Year, js.Type_of_Subscription, jr.Subject, jr.Journal_Title
FROM journal_subscription js
JOIN journal_revenue jr
ON js.Cust_No_ = jr.Ship_to_no_
AND js.Type_of_Subscription = jr.Type_of_Sales
AND js.Content_Year = jr.Content_Year
AND js.Journal_ID = jr.Journal_ID
LIMIT :limit OFFSET :offset');
    
    // Bind parameters
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    
    // Execute query
    $stmt->execute();
    
    // Fetch results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Return JSON response
    echo json_encode([
        'results' => $results,
        'totalPages' => $totalPages,
        'currentPage' => $page
    ], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
   
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage()]);
}
ob_end_clean(); // End output buffering and clean output
?>

Output

Can’t get current session’s database row on Laravel

I am trying to store the user’s geolocation information in an extra column on sessions table.
I use Fortify for authentication.
I created an extra column on sessions table for that.
migration:

public function up(): void
    {
        Schema::table('sessions', function (Blueprint $table) {
            $table->json('geolocation')->after('user_agent')->nullable();
        });
    }

Then I created a Session model which accesses the session table:

<?php
namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Session extends Model
{
    use HasFactory;

    protected $casts = [
        'id' => 'string',
        'user_agent' => 'collection',
        'geolocation' => 'collection'
    ];

    protected $fillable = [
      'geolocation',
      'created_at'
    ];
}

I created a listener for successfull login event. In the handle method, I try to get the session id to match the session with the row on the database. However session()->id() or session()->getId() return a different value which does not exist in the sessions table.

The question is;
What should I do in order to be able to update the active session’s database column?
What alternative approach might be tried?

I try to match the user’s active session with the row on the sessions table and update a column of it.

Adding a new column on ‘customers’ tab on Restrict Content Pro – Agree terms

I am using Restrict Content Pro and I am trying to introduce a new column to my customers table on the WordPress dashboard.

I want the column to be named something like ‘Agreed Terms’ and for each customer it should output the result of whether that customer agreed to terms which I think is currently either ‘none’ or the date in which the user signed up.

The agree to terms is in reference to whether the user accepts email communication and it isn’t required to tick.

Does anybody know how to do this? Thanks.

I have managed to get to the point of actually adding the column, however, I have been unable to pull any of the content through. I have looked online at the documentation but wasn’t able to find any kind of function or hook that allows me to get the result of the terms agreed.

This is the code I have come up with so far

function ag_rcp_customers_list_table_columns( $columns ) 
{
  $key = 'terms'; // All lowercase, no spaces. Your unique ID for your column.
  $name = __( 'Agree Terms', 'rcp' ); // Label to be displayed on the column header. Spaces are okay.
  $columns[ $key ] = $name;

  return $columns;
}

add_filter( 'rcp_customers_list_table_columns', 'ag_rcp_customers_list_table_columns' );

function ag_rcp_customers_list_table_column_company( $value, $customer ) 
{
  $terms = rcp_get_membership_meta( $customer->get_id(), 'agree-terms', true );
  
  return $terms;
}

add_filter( 'rcp_customer_list_table_column_company', 'ag_rcp_customers_list_table_column_company', 10, 2 );

This code was taken from the documentation from restrict content pro but applied to memberships. I have tried to tailor it towards customers instead.

documentation is here: documentation

Custom PHP settings PHP-FPM best practice [closed]

I am setting up a LEMP server (Ubuntu/Nginx/PHP) with PHP-FPM, and I was wondering what is the best practice for modifying global PHP settings? There seems to be a few options:

  1. Edit /etc/php/8.3/fpm/php.ini directly.
  2. Edit /etc/php/8.3/fpm/php-fpm.conf directly.
  3. Edit /etc/php/8.3/fpm/pool.d/www.conf directly (although this is normally per site files).
  4. Create a file /etc/php/8.3/fpm/conf.d/GLOBAL.ini.

I did some research, but couldn’t find any useful suggestions. I am guessing it’s not that important, but surely there are some strong opinions? I am inclined to use the last option #4, because that seems the most tidy. Thanks for suggestions.

Laravel 11 API: Always got unauthenticated message

I am using Laravel 11 for API with sanctum for authorization. Login works fine but logout always get unauthenticated with Http Status 401.

How to solve this problem and return HTTP status 200 as it suppose to do?

Here are my code and Postman’s API request

AuthController

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'message' => 'Logged out successfully',
        ],200);
    }

routes/api.php

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});

Postman

{
    "name": "Logout",
    "request": {
        "method": "POST",
        "header": [
            {
                "key": "Authorization",
                "value": "Bearer {{access_token}}"
            },
            {
                "key": "Content-Type",
                "value": "application/json"
            },
            {
                "key": "Accept",
                "value": "application/json",
                "type": "text"
            }
        ],
        "url": {
            "raw": "{{base_url}}/api/logout",
            "host": [
                "{{base_url}}"
            ],
            "path": [
                "api",
                "logout"
            ]
        }
    },
    "response": []
},

Thanks in advance.

I tried adding gaurds but npt working
config/auth.php

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
    ],

How to correctly configure PHP/Appache to self-host a Kanban server?

i am having issues with setting up a Vhost hosting Kanboard

It is the first time i use shell, php and apache. I wanted to install ‘Kanboard’ on MacOS Sonomoa to use it for a personnal purpose. I want to be able to access it from a browser at the adress : “kanboard.local” without having to do anything in the terminal when starting my computer.

I was not able to connect to my virtual host.

I did the following :

  • Installed Homebrew with the .pkg from their site

  • Installed php with homebrew

  • Installed MySQL and SQLite with homebrew

  • Installed HTTPD/Apache with homebrew

  • Downloaded the Kanboard master.zip from GitHub and unzipped it

Then :

I went to the HTTPD configuration file (httpd.conf) and added a line to load the php module:

LoadModule php_module lib/httpd/modules/libphp.so

I’ve checked which Directory has been declared, I’ve put : Require granted all on this directory ( …./var/www )

I added the line:

DirectoryIndex index.php index.html 

on the advice of ChatGPT

In the declared directory, I created an ‘html’ folder in which I put the kanboard folder I had unzipped Then, I went to my hosts database (/etc/hosts) and added the line:

127.0.0.0.1 kanboard.local

Finally, I went to the virtual hosts configuration file ( …/etc/extra/httpd-vhosts.conf) And I configured a virtual host like this:

Listen 8080 
<VirtualHost *:8080> 
DocumentRoot ‘/usr/local/var/www/html/kanboard’ 
ServerName kanboard.local
<Directory ‘/usr/local/var/www/html/kanboard’> 
Options Indexes FollowSymLinks MultiViews 
AllowOverride All 
Require all granted 
</Directory> 

I started php then httpd, then restarted them. I checked the ‘localhost:8080’ page it works correctly. I can use this page to browse kanboard files but the application itself is not built at all. When I try to connect to ‘kanboard.local’, I get a message “connection failed”. Can you help me / do you have any idea what is missing or causing the problem?

Date Format with PHP using Datetime

I have two dates I need to show it in format

29th and 30th November 2024
or
28th to 30th November 2024
or 
28th October to 30th November 2024
or
30th November and 1st December2024

What I tried so for is the code below.

                $date1 = new DateTime('2024-09-29');
                $month1 = $date1->format('m');
                $date2 = new DateTime('2024-09-30');
                $month2 = $date2->format('m');
                $interval = $date1->diff($date2);
                if($month1 == $month2){
                    if($interval->days == 1){
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' and ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    } else {
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' to ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    }
                } else {
                    if($interval->days == 1){
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' and ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date2->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    } else {
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' to ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date2->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    }
                }

Is there a better way to achieve this?

php password and user doesn’t after a new post call [closed]

I created a simple log-in form in php to access an archive with user and password (encrypted in MD5 without hash or salt).
I then decided to insert a filter in the archive page (to filter only results of a specific date).
When I run the filter the page no longer finds the user and password pair and redirects me to the login page.
The file is Archivio.php

Code without filter:

<?php
$utente = $_POST["Utente"];
$password = $_POST["Password"];
$password = md5($password);

$id=
$sql=mysqli_query($mysqli, "select * from Utenti_Archivio where Utente='".$utente."' and          Password='".$password."'");
    if (mysqli_num_rows($sql) == 1){
    }
    else{
        header( "Location: Login.html" );
        die;
    }

$querySQL = mysqli_query($mysqli, "select Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno from  `Archivio`");
?>

Code with filter:

 <div class="filtro">
            <form method="POST">
                <div class="textfiltro">
                    Filtra per giorno:
                </div>
                <div class="field">
                    <input type="text" name="data" id="data">
                </div>   
                <div>
                    <button class="filtrobutton">FILTRA</button>
                </div>        
            </form>
        </div>
<?php
$utente = $_POST["Utente"];
$password = $_POST["Password"];
$password = md5($password);

$id=
$sql=mysqli_query($mysqli, "select * from Utenti_Archivio where Utente='".$utente."' and          Password='".$password."'");
    if (mysqli_num_rows($sql) == 1){
    }
    else{
        header( "Location: Login.html" );
        die;
    }

$data = $_POST["data"];
if (!empty($data)) {
    $querySQL = mysqli_query($mysqli, "SELECT Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno FROM `Archivio` WHERE Giorno = '$data'");
} else {
    $querySQL = mysqli_query($mysqli, "SELECT Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno FROM `Archivio`");
}
?>

Login html file

   <body>
      <div class="login-form">
         <form id="host" action="Archivio.php" method="post">
            <div class="field">
               <input type="text" name="Utente" placeholder="Utente" required>
            </div>
            <div class="field">
               <input type="password" name="Password" placeholder="Password" required>   
            </div>
            <button type="submit">ENTRA</button>
         </form>
         <button onclick="document.location='Home.html'">INDIETRO</button>
         <button onclick="location.reload()">RIPRISTINA</button>
      </div>
    </body>

Can you help me?

I have tried moving the credential verification query after the filter and using the get method for the filter but it does not solve the problem.

Convert encoding from ISO 8859-1 to UTF-8 in PHP project

I have an old PHP project written in PHP 5.2, and am updating it to PHP 8.2

It extracts data from a SQL Server database, and on specific button presses it fills out this data into existing Excel templates.

Since PHPExcel does not exist any more I have used composer to replace it with phpspreadsheet across my project. The project is using UTF-8 for encoding (Header and meta included in my PHP and HTML), and also when connecting to the database.

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8

I have also changed the default charset = UTF-8 in my php.ini file

On my webpage all the German umlauts are showing without any problem, but the Excel files are not being filled out properly. It seems there is an encoding mismatch somewhere. In my Excel file the word Prüfung"shows like this: prüfung

The collation of my SQL Server database is Latin1_General_CI_AS.

Any ideas? I am expecting the German umlaut characters to be displayed and printed correctly.

With Nesbot Carbon diffForHumans(), display 19 months instead of 1 year when less than 26 months

I display a diffForHumans with one part

echo Carbon::create('1 hour 59 minutes ago')->diffForHumans(); // 1 hour ago
echo Carbon::create('1 day 23 hours ago')->diffForHumans(); // 1 day ago
echo Carbon::create('1 month 23 days ago')->diffForHumans(); // 1 month ago
echo Carbon::create('1 year 10 months ago')->diffForHumans(); // 1 year ago

For up to 25 months, I’d prefer to see months before it switches to year: e.g. to see 23 months instead of 1 year.

More generaly, I would like to keep the lower unit (like month) when the higher unit (like year) is 1 or 2.

I would also like the display to be as compact as possible.

How do I do that?

Woocommerce not using the right templates

I’m having some template hierarchy issues trying to add woocommerce to a custom theme I made for a client. The site isn’t using the templates it should be. The shop page the plugin generates is using ‘page.php’ instead of ‘archive-product.php’ and products are using ‘single.php’ instead of ‘single-product.php’. I created a folder called woocommerce in my theme folder and copied those two WC template files over, but they’re not being used. I used a function to force using the right templates, which worked but now the products don’t appear on the shop page like they did when the wrong templates were being used. I’ve never worked with WC before, so is there something basic I’ve missed?

Things I’ve tried:

  • switching to a default theme
  • turning off all plugins
  • double checking the folder structure (the files are in /mytheme/woocommerce/)
  • double checking the products are published
  • adding a debug line to the template echo

    Products found!

    which echoes that they are being found (just not showing)

  • checked the console for CSS or JS Issues
  • confirmed that the correct page is assigned as the Shop Page

Uncaught PHP Exception Error: “Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization” at DocType.php

I’ve been using Pimcore for a month, working on my localhost machine. Yesterday, I uploaded my Pimcore project to my server. I copied all the files and added the necessary permissions to the folders, but I keep getting the following error when I log in or refresh the page.

Would anyone be able to help?

request.CRITICAL: Uncaught PHP Exception Error: “Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization” at DocType.php line 134 {“exception”:”[object] (Error(code: 0): Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization at httpdocs/vendor/pimcore/pimcore/models/Document/DocType.php:134)”} []

I have tried looking inside every single file mention in the error log (If anybody needs the error log screenshot I will send it to you).
The only temporary solution is editing the following file:

httpdocs/vendor/pimcore/pimcore/models/Document/DocType/Listing/Dao.php
on line 60

    public static function sortByPriority(DocType $a, DocType $b): int
    {
        $a->getPriority();
        if ($a->getPriority() === $b->getPriority()) {
            return strcasecmp($a->getGroup() . $a->getName(), $b->getGroup() . $b-      >getName());
        }

        return $a->getPriority() <=> $b->getPriority();
    }

Overriding the following code by commenting the code and returning 0 the error doesn’t take place.
This doesn’t make sense for two main reasons:

  1. Is in the vendor folder so it gets frequently updated;
  2. In my local machine this error is not present, and I copied every folder 1to1 on my server.

Set Python Environment and Execute Python Code in PHP Script

I am trying to convert the vcd file to wavedrom json file using the python library

https://github.com/Toroid-io/vcd2wavedrom

when I run on my terminal the below code works fine

 source /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate && 
 python3 /var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py 
 -i /var/www/xxx/uuids/abcd/dump.vcd 
 -o /var/www/xxx/uuids/abcd/dump.json

When i execute the same code in my php script as

$env = 'source /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate';

cmd = "python3 /var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py -i ".$uuid_dir."/dump.vcd -o ".$uuid_dir."/dump.json";

#!/bin/sh

shell_exec($env ." && ". $cmd);

I am getting sh: 1: source: not found error.

How can set the venv from php script.

I am not a python developer. Please elaborate your answer as much as possible for me to understand better.

I tried to remove the source, but I got

 sh: 1: /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate: Permission denied
 Traceback (most recent call last):
 File "/var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py", line 9, in <module>
 from vcdvcd.vcdvcd import VCDVCD
 ModuleNotFoundError: No module named 'vcdvcd'

I set verilog-env folder to 777 but still the same error persists