WordPress Related Products have to match at least 3 tags

I have a WordPress website that has a related produts slider when inside a product, the related products slider has a filter to only relate produts by tags instead tags and categories.
I want to know if is possible to only have related produts that match at least 3 tags?

In the functions.php of the children theme i have this filter to only filter by tags:

add_filter( 'woocommerce_product_related_posts_relate_by_tag', '__return_false' );

Multi-Tenancy Laravel (Client-Server)

I have 2 projects
-> client: frontend
-> server: backend

My client is running at localhost:8001 and Server at localhost:8000

So, I open the localhost:8001 in my browser, and try to do the login
I’m using fortify to do the login, the project was already created. I’m trying to add multi tenancy

Request is sent with localhost:8000 in the header with username and pwd

How can I make a login connection if I have multi databases and how can I use backend to connect to right DB?
Is Synced resources a good way to do this first step?

We have a global users table, compare email and pwd?

Auto Login with sessions php

Im a begginer in php and i have a little project where i have a profile page with username and password, and i want the user to introduce them one time and if they are correct do whatever he wants and when he goes back to profile page he doesnt need anymore to introduce the credentials again and it does autologin with the credentials he introduced the last time.

I have tried to get the username and the password into a session but neither do i know to do it in a secure way nor how to do the autologin back in the form reading the session i have created previously containing the username and password.So i hope you can help me pls 🙂

array outside of the class, can’t access [duplicate]

Why i cant acess the $INI array inside the DB Class? I get always an null value.

php/db.php

<?php
class DB
{
    static function connection()
    {
        //mysqli_report(MYSQLI_REPORT_OFF);
        $mysqli = @new mysqli($INI["db_host"],
            $INI["db_user"],
            $INI["db_pass"],
            $INI["db_name"],
            $INI["db_port"]);
        if ($mysqli->connect_error) {
            echo "Error: " . $mysqli->connect_error;
        } else {
            echo "Success";
        }
    }
}

php/config.php

<?php
<?php
$INI = array(
    "db_host" => "localhost",
    "db_user" => "root",
    "db_pass" => "",
    "db_name" => "website",
    "db_port" => "3307"
);

index.php

<?php
require_once("php/config.php");
require_once("php/db.php");
DB::connection();
?>

Why i can’t access the $INI array values?

Fatal error: Uncaught mysqli_sql_exception: Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte in C:wamp64wwwwebsitephpdb.php on line 8

mysqli_sql_exception: Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte in C:wamp64wwwwebsitephpdb.php on line 8

Can’t generate roave/security-advisories audit in json format

I am trying to generate a sample output via composer update --dry-run roave/security-advisories --audit-format json as I need to know what the JSON structure looks like. Unfortunately, I can’t get it to install packages that have security vulnerabilities, since roave/security-advisories has packages with security vulnerabilities in its conflicts script.
Unfortunately I also can’t find any documentation regarding the JSON structure.
Does anyone here have an example output that they could provide me with or a reference where I can read about it?

How to get PHP cURL info such as execute time and number of HTTP request made

i am trying to calculate

  1. No of HTTP request made by cURL to example.com
  2. Total time taken for cURL to get string from example.com
  3. No of Redirect count.

Code :

function file_get_contents_curl($url) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);   
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);   
    curl_setopt($ch, CURLOPT_VERBOSE, true);

    // Get the content type
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_exec($ch);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    // Get the content
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    $data = curl_exec($ch);
    
    // Stats 
    $http_request = curl_getinfo($ch, CURLINFO_NUM_CONNECTS);
    $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    $request_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT) + 1;
    $connect_time = curl_getinfo($ch, CURLINFO_CONNECT_TIME);
    curl_close($ch); 

    // Set the content type header
    header('Content-Type:' . $content_type);

    echo "HTTP Request: " . $http_request . "<br>";
    echo "Total Time: " . $total_time . "<br>";
    echo "Redirect count: " . $request_count . "<br>";
    echo "Connection time: " . $connect_time . "<br>";

    return $data;
}

$homepage = file_get_contents_curl("https://example.com");
echo $homepage;

Error : $http_request value returning 0

Using vuejs 3 and modules with DOM prerendered by PHP without compilation

In a current project I work with the fatfreeframwork PHP Microframework. The pages contain recurring sections on multiple pages that only differ in the data displayed. Each of this sections is associated with a plain javascript file to handle interactions.

So far so good, everything works just fine. As I am now delving into vuejs 3 I would like replace my Javascript Code, which mostly consists of DOM manipulation when users interact, with vuejs.

This works fine if I treat the page as a single page app. Because of the repeating sections in many pages I now have a lot of code duplication in my beginner vuejs code for each page, because I define the same functionality over and over again in different pages.

I would like to define my page as an app, load vue modules as independent js files (if possible without build step) and get the template string for the modules from the prerendered page. In general, treat vuejs like jquery from olden times.

Is it possible in vuejs to get a modules template from the prerendered page, or must I duplicate the code in a modules template? From a vue beginner perspective, is there maybe a better way to integrate vuejs into an existing PHP application without too much code duplication?

current state of application

Producing an array from a column in a mysql table using mysqli [duplicate]

I am trying use to mysqli to select an array of links from a mysql table.

What I want to do is put all of the selected links into an array, so I can then echo them later in a webpage. I want to index by number, like $image_link[0], or $image_link[7], etc.

In my query, $id is a foreign key in a table called images. The table contains images uploaded by many users.

So, the command works fine in mysql, the users primary ID is the foreign key and it correctly selects all the links for the user’s images. The row is called image_link.

I tried this code, I feel I am on the right track, but I cannot make it work. Can I have any pointers. I spent all day searching for the answer, but to no avail.

<?php
session_start();
$id = $_SESSION["id"];
$conn = mysqli_connect(
    "localhost", "user", "password", "DB_name"); 
    
// Check connection 
if (mysqli_connect_errno()) { 
    echo "Database connection failed."; 
} 
  
$query = "SELECT image_link FROM images WHERE userID='$id'";
//$query = "SELECT id, domain FROM services";
echo "test";
    $result = $sql->query($query);
$data = [];
while ($row = $result->fetch_assoc()) {
  $data[$row['image_link']] = $row;
}
mysqli_close($conn);
?>

Same relationship works in one event listener but not in the other one which is the same

Hello I’m facing this problem. I have this 2 listeners which are the same.

What I do not understand is that in SendTargetCompletedNotification when trying to access $event->client->contacts I get the error Undefined property: IlluminateDatabaseEloquentRelationsBelongsTo::$contacts but doing the same in SendTargetAssignedContactNotification works. Also if I access $client->contacts before entering SendTargetCompletedNotification It returns the contacts, so it should work apparently.

<?php

namespace AppListeners;


use AppEventsTargetCompleted;
use AppNotificationsTargetCompletedContactNotification;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesNotification;

class SendTargetCompletedContactNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AppProvidersTargetCompleted  $event
     * @return void
     */
    public function handle(TargetCompleted $event)
    {
        dd($event->client->contacts);
        foreach($event->client->contacts as $contact) {
            $contact->notify(new TargetCompletedContactNotification($event->kpi, $event->points));
        }
    }
}

<?php

namespace AppListeners;

use AppEventsTargetAssigned;
use AppNotificationsTargetAssignedContactNotification;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesNotification;

class SendTargetAssignedContactNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AppProvidersTargetAssigned  $event
     * @return void
     */
    public function handle(TargetAssigned $event)
    {
        dd($event->client->contacts);
        foreach ($event->client->contacts as $contact) {
            $contact->notify(new TargetAssignedContactNotification($event->kpi, $event->causer));
        }
    }
}

Get value from TXT file and import it into PHP value [closed]

I have an TXT file with approximately 10.000 lines to read, and each line contains a number, barcodes, EAN, UPC etc, I would like to get the value, each line by line and export it as an JSON/CSV or similar format which I can use later on.

How to fetch the $product_code = “GetBarcodeFromText” into the PHP code and execute it.

barcodes.txt contains for an example:

022517707319
015561756228
015561756211
015561822619
015561822626
015561825269
015561825276

Here is the code I have from GO-UPC.com. (I just need the results in any reading format that I can use in Excel.)


$api_key = 'API_KEY';
$product_code = '01020504050505';
$api_base_url = 'https://go-upc.com/api/v1/code/';
$url = $api_base_url . $product_code;

$ch = curl_init();

$data = get_product_data($url, $api_key, $ch);

$product_data = json_decode($data);

var_dump($product_data);

$product_name = $product_data->product->name;
$product_description = $product_data->product->description;
$product_image = $product_data->product->imageUrl;

?>

<p><?php echo $product_name; ?>,<?php echo $product_description; ?>,<?php echo $product_image; ?></p>

<?php

function get_product_data($url, $api_key, $ch) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $api_key
    ));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

Laravel and Tailwind Elements: Modal Illegal Invocation Error

We have a basic laravel project with tailwind css (tailwind elements), PHP8, MySQL and JQuery. During initial development we used jquery to toggle modals inside the application. However recently all the modals are stopped working during button/link clicks and is showing the error:

selector-engine.js:38 Uncaught TypeError: Illegal invocation
    at Object.findOne (selector-engine.js:38:44)
    at fs._showElement (modal.js:247:38)
    at modal.js:156:35
    at et (index.js:307:5)
    at backdrop.js:78:7
    at et (index.js:307:5)
    at tt (index.js:317:5)
    at Gi._emulateAnimation (backdrop.js:152:5)
    at Gi.show (backdrop.js:77:10)
    at fs._showBackdrop (modal.js:356:20)
findOne @ selector-engine.js:38
_showElement @ modal.js:247
(anonymous) @ modal.js:156
et @ index.js:307
(anonymous) @ backdrop.js:78
et @ index.js:307
tt @ index.js:317
_emulateAnimation @ backdrop.js:152
show @ backdrop.js:77
_showBackdrop @ modal.js:356
show @ modal.js:156
(anonymous) @ modal.js:450
each @ jquery.min.js:2
each @ jquery.min.js:2
jQueryInterface @ modal.js:439
(anonymous) @ dashboard:436
dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3

And the modal toggle is as simple as the code below:

$('.invite-customer').on('click', function () {
        $('#customerInviteModal').modal('show');
});

Modal Code:

<div
        class="modal fade fixed top-0 left-0 hidden w-full h-full outline-none overflow-x-hidden overflow-y-auto"
        id="customerInviteModal" tabindex="-1" aria-labelledby="customerInviteModalTitle" aria-modal="true"
        role="dialog">
        <div class="modal-dialog modal-dialog-centered relative w-auto pointer-events-none">
            <div class="modal-content border-none shadow-lg relative flex flex-col w-full pointer-events-auto bg-white bg-clip-padding rounded-md outline-none text-current">
                <div class="modal-header flex flex-shrink-0 p-8 border-b border-gray-200 rounded-t-md bg-yellow-700">
                    <h5 class="text-xl font-medium leading-normal w-full text-center text-white"
                        id="exampleModalScrollableLabel">
                        Invite Customer
                    </h5>
                    <button type="button"
                            class="hidden btn-close box-content w-4 h-4 p-1 text-white border-none"
                            data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body relative p-12">
                    <form action="">
                        <div class="grid gap-6">
                            <label class="block">
                                <span class="text-gray-400">Name</span>
                                <input id="customerName" type="text"
                                       class="mt-1 rounded-md border-gray-light block w-full"
                                       required
                                       placeholder="">
                                <span class="error name-error pl-5 text-center text-red-700" hidden></span>
                            </label>

                            <label class="block">
                                <span class="text-gray-400">Email</span>
                                <input id="customerEmail" type="email"
                                       class="mt-1 rounded-md border-gray-light block w-full"
                                       required
                                       placeholder="">
                                <span class="error email-error pl-5 text-center text-red-700" hidden></span>
                            </label>

                            <label class="block">
                                <span class="text-gray-400">Phone</span>
                                <input id="customerPhone" type="text"
                                       class="phone mt-1 rounded-md border-gray-light block w-full"
                                       required
                                       maxlength="20"
                                       placeholder="">
                                <span class="error phone-error pl-5 text-center text-red-700" hidden></span>
                            </label>
                        </div>
                        <div
                            class="modal-footer flex flex-shrink-0 flex-wrap items-center justify-between mt-14">
                            <button type="button"
                                    class="inline-block px-6 py-2.5 text-yellow-700 font-medium text-xs leading-tight uppercase rounded hover:text-white border-2 border-yellow-600 hover:bg-yellow-600 focus:yellow-600 focus:outline-none focus:ring-0 active:yellow-600 transition duration-150 ease-in-out"
                                    data-bs-dismiss="modal">
                                Cancel
                            </button>
                            <button type="button" id="customerInviteBtn"
                                    class="close inline-block px-6 py-2.5 bg-yellow-700 text-white font-medium text-xs leading-tight uppercase rounded focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out ml-1">
                                Send Invite
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

However all modals are not showing.

We tried converting the modal to use tailwind element modal functions based on the documentation .

However we need to close the modal using jquery as we have to send an ajax request during a click of a button inside the modal, is this possible? or do we have to use pure javascript like the one here ?

Curl error connection reset by peer in Laravel

I have a problem when I want to call an api which is config in my vendor file, Yesterday that worked and all was fine but now i can’t make any call and I have this error “Curl Error, connection reset by peer’.

I’m in laravel project and i call my Api with that command :

$api = new ItemFamily($url,$user,$password)
$data = $api->call()

Trying to put a PHP math result into JavaScript chart

I’ve been trying to figure this out for days. I hope I can explain this clear. I am trying to call up the results of this simple math equation in JavaScript code below:

             <?php  
             $x=37;  
             $y=15;  
             $z=$x-$y;  
             echo " ",$z;  
             ?> 

part of the script code

        { y: $z, label: "slice" },
        { y: 2, label: "pepper" },
        { y: 15, label: "sprite" },
        { y: 23, label: "coke" }

I now trying to put the $z in the script code

i tried using JavaScript and call tags, but that just messes up the JavaScript code. It only works if the number is posted only. Let know if what I did is possbile

Why mysqli_stmt_bind_param function not working as expected when using prepared query?

When I am using mysqli_stmt_bind_param($stmt, "sssi", $title, $content, $published_at, $id); function for binding the parameters received through post request, It’s working fine as it returns true and execute successfully, But If I use $title instead of $id in 4th parameters as mysqli_stmt_bind_param($stmt, "sssi", $title, $content, $published_at, $title);, then it should return false because we are binding string type to integer as the $title contains varchar type and for this time, I was using the value of $title as alphabetic characters but instead of returning false because of data-types mismatching, it’s returning true.
I know it won’t update the database as I am passing title instead of id, but I just wanted to know the behavior because it’s returning true for mismatched types also.

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $title = $_POST['title'];
    $content = $_POST['content'];
    $published_at = $_POST['published_at'];
    
    // function to validate empty fields
    $errors = validateArticle($title, $content, $published_at);

    if (empty($errors)) {

        $sql = "UPDATE article
                set title = ?,
                    content = ?,
                    published_at = ?
                WHERE id = ?";

        $stmt = mysqli_prepare($conn, $sql);

        if ($stmt === false) {
            echo mysqli_error($conn);
        } else {

            if ($published_at == ''){
                $published_at = null;
            }            

            // Binding the parameters to prepared query
            $check = mysqli_stmt_bind_param($stmt, "sssi", $title, $content, $published_at, $id);
            var_dump($check);

            if (mysqli_stmt_execute($stmt)) {
                
                print_r("already executed");
                if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'){
                    $protocol = 'https';
                }else{
                    $protocol = 'http';
                }
                // header("Location: {$protocol}://" . $_SERVER['HTTP_HOST'] . "/article.php?id={$id}");
                exit;
            } else {
                echo mysqli_stmt_error($stmt);
            }
        }
    }
}

Searching for multipole orders on admin order list

i want to search for multiple order numbers so i created this snippet:


function woo_multiple_order_search(  $query_vars ) {

global $typenow;
global $wpdb;
global $pagenow;

    if ( 'shop_order' === $typenow && isset( $_GET['s'] ) && 'edit.php' === $pagenow ) {

        $search_term = esc_sql( sanitize_text_field( $_GET['s'] ) );
        
        if (strpos($search_term, '|') == false) 
            return $query_vars;
        $order_ids = explode('|',$search_term);

        $meta_query = array(
            'relation' => 'OR'
        );
        if(is_array($order_ids) && $order_ids) {
            foreach($order_ids as $order_id) {
                $meta_query[] = array(
                    'key' => '_order_number',
                    'value' => $order_id,
                    'compare' => '='
                );
            }
        }   
        $args = array(
            'posts_per_page'  => -1,
            'post_type'       => 'shop_order',
            'post_status'     => 'any',
            'meta_query'      => $meta_query
        );
        $posts = get_posts( $args ); 
        if ( ! $posts ) return $query_vars;

        foreach($posts as $post){
            
            $query_vars['post__in'][] = $post->ID;
        }

    }
    return $query_vars;

}
add_filter( 'request', 'woo_multiple_order_search', 20 );

the logic behind is whenever “|” is detected inside the search string it should check inside a meta_key and return the results.
now i can verify that up to:

get_posts( $args ); 

it works as it gives the correct results.
However i can’t figure out how to return them to the admin list.
probably

$query_vars['post__in'][] = $post->ID;

is incorrect. any ideas?