How do i Use Php in order to display image from the path on Xamp server under image folder? [closed]

I have a column and its fetching all the fields from the table fine, the issue is picking up the image as per course name is not shown and need some help as to how to display these images on each course name as per table.

How do i make a select column to allow a user to click as per course_name?

//php code

<!-- BOOKING COURSES -->
<div class="udb-sec udb-cour">
    <h4><img src="images/icon/db2.png" alt="" /> Booking Courses</h4>
    <p>The courses available for booking or registration by the student.</p>
    <form action="register_course.php" method="POST">
        <div class="sdb-cours">
        <?php
include 'db_connection.php'; // Include the database connection

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: index.html");
    exit;
}

$user_id = $_SESSION['user_id']; // Get the user ID from the session

// Check if the connection is still valid
if (!$conn->ping()) {
    die("Database connection failed.");
}

// Query to fetch available courses for the logged-in user
$sql = "
SELECT ac.course_id, ac.course_name, ac.duration, ac.image
FROM available_courses ac
LEFT JOIN student_modules sm ON ac.course_name = sm.module_name AND sm.student_id = ?
WHERE sm.student_id IS NULL";

// Prepare the SQL statement
$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Error preparing the query: " . $conn->error);
}

// Bind the parameters
$stmt->bind_param("i", $user_id); // Bind the user_id parameter

// Execute the statement
if (!$stmt->execute()) {
    die("Error executing the query: " . $stmt->error);
}

// Get the result
$result = $stmt->get_result();

// Base directory for images
$baseDir = '../img/Courses/';


// Check if courses exist for the logged-in user
if ($result->num_rows > 0) {
    echo '<table class="table table-striped">';
    echo '<thead class="table-dark">';
    echo '<tr>';
    echo '<th scope="col">Select</th>';
    echo '<th scope="col">Image</th>';
    echo '<th scope="col">Course Name</th>';
    echo '<th scope="col">Duration</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    while ($row = $result->fetch_assoc()) {
        $imagePath = $baseDir . htmlspecialchars($row['image']);
        echo '<tr>';
        echo '<td><input type="checkbox" name="courses[]" value="' . htmlspecialchars($row['course_id']) . '"></td>';
        echo '<td><img src="' . $imagePath . '" alt="' . htmlspecialchars($row['course_name']) . '" width="100"></td>';
        echo '<td>' . htmlspecialchars($row['course_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['duration']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
} else {
    echo '<p>No courses available at the moment.</p>';
}

// Close the statement and the connection
$stmt->close();
$conn->close();
?>

        </div>
        <button type="submit" class="btn btn-primary">Register</button>
    </form>
</div>

Authorize.net refund Transaction error: has invalid child element ‘payment’ in namespace

On the sandbox API endpoint i try to refund a previously valid transaction (120053733345) with the following createTransactionRequest array (converted into JSON):

Array
(
    [merchantAuthentication] => Array
        (
            [name] => mytestname
            [transactionKey] => mytestkey
        )
    [refId] => 1041-352205
    [transactionRequest] => Array
        (
            [transactionType] => refundTransaction
            [amount] => 29.00
            [currencyCode] => CAD
            [refTransId] => 120053733345
            [payment] => Array
                (
                    [creditCard] => Array
                        (
                            [cardNumber] => 5121212121212124
                            [expirationDate] => 2028-01
                        )
                )
        )
)

While the authCaptureTransaction operation works fine, i receive an error with the refundTransaction operation:

The element ‘transactionRequest’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’ has invalid child element ‘payment’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’. List of possible elements expected: ‘splitTenderId, order, lineItems, tax, duty, shipping, taxExempt, poNumber, customer, billTo, shipTo, customerIP, cardholderAuthentication, retail, employeeId, transactionSettings, userFields, surcharge, merchantDescriptor, subMerchant, tip, processingOptions, subsequentAuthInformation, otherTax, shipFrom, authorizationIndicatorType’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’.

I’ve tried to follow the instruction in
https://developer.authorize.net/api/reference/index.html#payment-transactions-refund-a-transaction
and
Is it possible to refund a transaction in Authorize.Net sandbox account?
but with no success.

Laravel nwidart “$CLASSServiceProvider” not found

After installing the package nwidart/laravel-modules and configuring it with the commands provided in the package documentation, I encounter the following error after creating a simple module:

Class “ModulesPhpMyAdminProvidersPhpMyAdminServiceProvider” not
found

Here are the changes made to the composer.json file to use the module:

{
    "$schema": "https://getcomposer.org/schema.json",
    "name": "laravel/laravel",
    //........................
    "require": {
        "php": "^8.2",
        //........................
        "nwidart/laravel-modules": "^11.1"
    },
    "require-dev": {
        //........................
    },
    "autoload": {
        "psr-4": {
            "Modules\": "Modules/",
            //........................
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    //........................
    "extra": {
        "laravel": {
            "dont-discover": [
            ],
            "merge-plugin": {
                "include": [
                    "Modules/*/composer.json"
                ]
            }
        }
    },
    //........................
    "minimum-stability": "dev",
    "prefer-stable": true
}

After running the command composer dump-autoload, I expected to access the route within the phpmyadmin module using the address localhost:8000/phpmyadmin:
php

Route::get('phpmyadmin', function () {
    dd('test');
})->name('phpmyadmin');

What I’ve noticed is that in the file bootstrap/cache/module.php, the service provider for the module I created is defined as follows:

<?php return array (
  'providers' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'eager' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'deferred' => 
  array (
  ),
);

When I remove these service providers, the error goes away, but the issue of accessing the page still persists, resulting in a 404 error, and this route is not visible in the Laravel routes list when I run:

php artisan route:list

Feel free to post this on Stack Overflow for assistance!

Facebook Ad replacing UTMs with FBCLID

I am promoting landing pages with forms through Facebook Ads.

The form is designed to capture UTM parameters passed in the landing page URL.
In the Facebook Ad, I add the UTM parameters using the appropriate fields. However, when I click on the ad and get redirected to my landing page, I notice that Facebook modifies the URL, removing the UTM parameters and adding the “fbclid” parameter instead.

How can I retrieve the UTM parameters?

I see that landing pages created by platforms like EverAd are still able to capture them, but after analyzing the landing page code, it’s unclear how they manage to do it.

How to show a message, redirect user, and generate PDF in the background?

I need to implement a flow where, when a user clicks the “Generate PDF” button, a message appears saying “Your PDF is being generated,” and the user is redirected to the homepage. Meanwhile, the PDF generation continues in the background on the server.

I’m using JavaScript for the frontend and PHP on the backend. The PDF generation may take some time, so I want to ensure the user isn’t blocked during this process. I plan to send an asynchronous request to start PDF generation and then redirect the user. On the backend, I want to run the PDF generation in the background (via a worker or exec()).

What’s the best approach to implement this without blocking the user’s experience?

Use of LDAP in PHP generates an error when the wrong password is supplied

I’m using the LDAP functions in PHP.

My code works quite well, but a problem arises when the user types the wrong password.

In that case my expectation is a message that says “wrong password inserted” (I created a function for it) but instead of it PHP returns an error that blocks the script execution.

Warning: ldap_bind(): Unable to bind to server: Invalid credentials in
/var/www/html/0functions/logon.php on line 83

Warning: ldap_search(): Search: Operations error in
/var/www/html/0functions/logon.php on line 85

Fatal error: Uncaught TypeError: ldap_get_entries(): Argument #2
($result) must be of type LDAPResult, false given in
/var/www/html/0functions/logon.php:86 Stack trace: #0
/var/www/html/0functions/logon.php(86):
ldap_get_entries(Object(LDAPConnection), false) #1
/var/www/html/login.php(22): logdap(‘USER’, ‘PWD’) #2 {main} thrown in
/var/www/html/0functions/logon.php on line 86

My perception is that this is a DLL error. Is there a way to get around this error and let my function go to the end?

It is annoying for the user because they receive the error 500 and get stuck without understanding that it is just because the password is wrong.

I need to change a field number_format

I need your help.
I have this code that I need to change

$metMessage = "";
        foreach($batches as $batch)
        {
            $metMessage .= '<tr>
            <td>' . $batch['comp_code'] . '</td>
            <td>' . $batch['description'] . '</td>
            <td>' . number_format($batch['quantity'], 0, '.', '') .'</td>
            </tr>';
        }

What i need:

If $batch['quantity'] < 3 then . 
    number_format($batch['quantity'], 2, '.', '') .'
else . 
    number_format($batch['quantity'], 0, '.', '') .'

I don’t know how to add this condition

Uncaught Error: Call to undefined function wp_kses() with PHP 8.3.6

I migrated my WordPress (multisite) website from PHP 7.4 to PHP 8.3.6 and got the following error:

Fatal error: Uncaught Error: Call to undefined function wp_kses() in /home/devnote/www/wp-includes/functions.php:6073 
Stack trace:
#0 /home/devnote/www/wp-includes/functions.php(5554): wp_trigger_error()
#1 /home/devnote/www/wp-includes/class-wpdb.php(1333): _deprecated_function()
#2 /home/devnote/www/wp-content/sunrise.php(11): wpdb->escape()
#3 /home/devnote/www/wp-includes/ms-settings.php(47): include_once('...')
#4 /home/devnote/www/wp-settings.php(155): require('...')
#5 /home/devnote/www/wp-config.php(107): require_once('...')
#6 /home/devnote/www/wp-load.php(50): require_once('...')
#7 /home/devnote/www/wp-blog-header.php(13): require_once('...')
#8 /home/devnote/www/index.php(17): require('...')
#9 {main} thrown in /home/devnote/www/wp-includes/functions.php on line 6073

./wp-includes/functions.php:

$message = wp_kses(
    $message,
    array(
            'a'      => array( 'href' => true ),
            'br'     => array(),
            'code'   => array(),
            'em'     => array(),
            'strong' => array(),
    ),
    array( 'http', 'https' )
);

I disabled the plugins and changed the theme, see here for details, but it did not help.

Apache is running on Docker but is not receiving a response on host

Trying to run a Moodle instance on Docker using php-apache

Hi, I am currently trying to set up a moodle instance using Docker.

  • A mariadb container (image: mariadb:latest)
  • A php container (image: php:8.3-apache)

According to docker everything is running and if I use nmap to ping the adress, I get:

Nmap scan report for localhost (127.0.0.1)
Host is up (0.000099s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
3306/tcp open  mysql

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds

My code is a simple fork from Github – Moodle and has correctly been installed in /var/www/html/moodle on build.

Error: Empty response

When I open my localhost in the browser, I get 127.0.0.1 didn’t send any data. (note: this is a browser message, not an apache error message). I am not getting any error/log messages in my docker containers..

I updated the apache DocumentRoot to match the WORKDIR, but the problem still persists.
Due to the lack of error/feedback I am finding it difficult to figure out where to look.

Setup Docker

Here are my docker files in case you want to replicate my scenario:

  • create a /moodle directory in your root containing a clone from this Github repository
  • create a /moodledata repository that is empty (make sure it has write/create rights)

docker-compose.yml

name: 'moodle_405'

services:
  mariadb:
    image: mariadb:latest
    container_name: mariadb
    environment:
      - MYSQL_ROOT_PASSWORD=bitnami
      - MYSQL_DATABASE=moodle
      - MYSQL_USER=admin
      - MYSQL_PASSWORD=password
    volumes:
      - ./mariadb:/var/lib/mysql
    ports:
      - "3306:3306"

  moodle:
    image: php:8.3-apache
    container_name: moodle
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MOODLE_DATABASE_HOST=mariadb
      - MOODLE_DATABASE_NAME=moodle
      - MOODLE_DATABASE_USER=admin
      - MOODLE_DATABASE_PASSWORD=password
    volumes:
      # ./moodle contains a simple fork from moodle's github repository
      - ./moodle:/var/www/html/moodle
      # ./moodledata is an empty folder that will be updated during moodle's setup
      - ./moodledata:/var/www/moodledata
    depends_on:
      - mariadb
    ports:
      - "80:8080"
      - "443:8443"

Dockerfile

FROM php:8.3-apache

LABEL maintainer="John Whick <[email protected]>"
LABEL description="John's Moodle setup for docker"
LABEL version="1.2"

# PHP extensions
RUN apt-get update && apt-get install -y 
    libpng-dev 
    libjpeg-dev 
    libfreetype6-dev 
    libxml2-dev 
    libzip-dev 
    unzip 
    git 
    && docker-php-ext-install mysqli zip gd xml soap intl 
    && a2enmod rewrite

# Set Apache DocumentRoot
RUN sed -ri -e 's!/var/www/html!/var/www/html/moodle!g' 
    /etc/apache2/sites-available/*.conf 
    /etc/apache2/apache2.conf 
    /etc/apache2/conf-available/*.conf

WORKDIR /var/www/html/moodle

EXPOSE 80
EXPOSE 8080

Thank you for your time.

Only allow purchases from one group product at a time WooCommerce

I’m trying to restrict the user to only being able to add items to the cart from one grouped product at a time.

I’ve tried writing the code in two different approaches but neither work.

These are my 2 attempts.

Attempt One:

function limit_cart_items_to_one_group ( $passed, $product_id, $quantity ) {
    if (current_user_can('stallholder') ) {

        if( WC()->cart->is_empty() ) return $passed;

        $product_type = array('terms' => array('grouped'));
        $products = wc_get_products( $args );
        $found = $current = false;

        foreach ( $products as $product ) {
           $children = array();
           foreach ( $product->get_children() as $child_id ) {
              $children[] = $child_id;
           }
        }

        if( has_term( $children, 'product_cat', $product_id ) ){
            $current = true;
        }

            foreach ( WC()->cart->get_cart() as $cart_item ){
            if( has_term( $children, 'product_cat', $cart_item['product_id'] ) ) {
                $found = true;
                $current = true;
                break; // stop the loop.
            }
        }

        if( $found && $current ){
            $passed = false;
            $cats_str = implode('" and "', $children );
            wc_add_notice( sprintf( __('Only one Market date is allowed to be booked at a time. Thank you.', 'woocommerce' ), $cats_str ), 'error' );
        }
        return $passed;
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_to_one_group', 10, 3 );

Attempt 2:

function is_product_the_same_group($valid, $product_id, $quantity) {
    if (current_user_can('stallholder') ) {
    
        $product_type = array('terms' => array('grouped'));
        $products = wc_get_products( $args );

        foreach ( $products as $product ) {
           $children = array();
           foreach ( $product->get_children() as $child_id ) {
              $children[] = $child_id;
           }
        }

        global $woocommerce;
        if($woocommerce->cart->cart_contents_count == 0){
             return true;
        }
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            $terms = get_the_terms( $_product->id, $children );
            $target_terms = get_the_terms( $product_id, $children );
            foreach ($terms as $term) {
                $group_ids[] = $term->term_id;  
            }
            foreach ($target_terms as $term) {
                $target_group_ids[] = $term->term_id; 
            }           
        }
        $same_group = array_intersect($group_ids, $target_group_ids);
        if(count($same_group) > 0) return $valid;
        else {
            wc_add_notice( 'This product is in another group!', 'error' );
            return false;
        }
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_group',10,3);

Basically I’m trying to restrict what this specific user role to only being able to book from one group of products at a time.

Access to fetch / has been blocked by CORS policy [duplicate]

I am developing a file upload and editing plugin and I encounter this error when I want to make a fetch request;

Access to fetch at ‘…mylink/create_folder.php’ from origin ‘http://localhost:8081’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

My php file starts like this;

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

Why do I encounter this error even though there are relevant headers in my php file? Anyone have any ideas?

Email verification in wave v3 Saas template

Im new to laravel and Ia m using wave v3 from devdojo for my saas app which is actualy done except for one thing and that is email verification of regustered user. Documentations says that I meed to enable it in auth/setup url butthis only send email to user after he registers. Columns in db are still empty ( verification_code, verifed and emal_verified_at). Inside routes/web.php in wave folder there are some commented out routes but after uncommentig it still does nt work. Question is: what do I have to in order to have email verficiation using wave saas template( it uses devdojo auth under the hood)?

Thanks a lot!

I need quidelines how to add this functionality since I think it is not regar laravel implementation

Set Mautic ver. 5.1.1 limit messages per hour to 90

I’m using Mautic version 5.1.1 but I can’t find the option send the emails with delay to avoid blocking. My goal is to slow down sending emails to 90 per hour. I’ve tried with cron jobs but didn’t work. Also I read that the option was supported in older versions “How should email be handled?“ and then I can set queue and limit the messages easy. Unfortunately in the newer version 5.1.1 that option does not exist. I usually use Mautic-> Channels -> Emails from there I send the messages to segmented groups. No matter how much I tried to limit them through cron jobs they were sent immediately. Do you have any ideas on how to achieve it?

The value that I want to assign to the variable is printed, but it is not assigned to the variable, it says that it is null in php

In this function there is a value and it is not null. But when we put the same value in the variable and print the variable, it says that the variable is null.

public function h2h($game_id)
{
  $game = Game::find($game_id);
  $team1 = $game->team1;
  $team2 = $game->team2;

  $games = Game::where('team1', $team1)
    ->where('team2', $team2)
    ->orWhere('team1', $team2)
    ->where('team2', $team1)->get();

  $h2h = [];

  foreach ($games as $game) {
    $team1Goals = count(json_decode($game->stat->team1Goals));
    $team2Goals = count(json_decode($game->stat->team2Goals));

    $h2h[] = [
      'date' => verta($game->date)->format('l d M'),
      'team1' => [
        'name' => $game->home->name,
        'logo' => $game->home->logo,
        'goals' => $team1Goals
      ],
      'team2' => [
        'name' => $game->away->name,
        'logo' => $game->away->logo,
        'goals' => $team2Goals
      ],
    ];
  }

  dd($h2h);
  return $h2h;
}

The problem is:

count(json_decode($game->stat->team1Goals));

This piece of code, when assigned to a variable, says it is null, but when you print it, the correct value is printed.