CodeIgniter 3, PHP 8 and jQuery AJAX

Morning
Do AJAX requests in PHP 8 work normally with CodeIgniter 3?

I installed an application under CodeIgniter 3 which works perfectly since a long time under PHP 7.4. I want to install the same application in another machine running PHP 8.1.2. And there the AJAX requests no longer pass.

in stock out of stock woocomerce color badge not working

guys, I have a little problem here, maybe you know how to solve it because it’s driving me insane.
So I have this code in my Theme Functions, functions.php, that goes like this:

function webis_stoc( $atts ){
   global $product;
   echo "<div class='stoc'>";
   $stoc=$product->stock_status;
   switch($stoc){
       case "onbackorder": echo "<span class='precomanda'; style='color:orange;'; >Precomanda</span>"; break;
      case "instock": echo "<span class='inStoc'; style='color:green;' >in stoc</span>"; break;
      case "outofstock": echo "<span class='farastoc'; style='color:red;' >Stoc epuizat</span>"; break;
      default : echo $stoc; break;
   }
   echo "</div>";
}
add_shortcode  ('webis_stoc','webis_stoc' ); 

The problem here is that the CSS in every these 3 cases are not displaying (it’s always green, no red or orange, even if it’s in on backorder or out of stock, it’s still green.
How can I solve this?
here is the onbackorder that is supposed to be orange

I tried to modify the colors with background-color , but it only changed the color of the text, and I want the full button to recolor

unable to displaying category image in my creating module

i want to display caregory images in my own module , so i create a module and frontend/templates/category-section.phtml , and this is the code , my problem is the source image is empty ,it returns null in my creating page ,all others properties like this works correctly

i uploaded the image in admin panel and when i click on the a tag it return the category pages with the image correctly but only in my displaying categories and images , the images arent displaying

the images here arent displayed

if i click on any one, the url and image exist here but in new module arent

<?php echo $category->getName() ?>

<section class="section-holder">
    <div class="all-categories">
        <p class='category-text'>categories</p>
        <div class='categories-flex'>
            <?php
            $categoryHelper = $this->helper('MagentoCatalogHelperCategory');
            $outputhelper   = $this->helper('MagentoCatalogHelperOutput');


            foreach ($categoryHelper->getStoreCategories() as $category) :

            ?>
                <a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>">
                    <div class='child-category'>
                        <div>
                            <img style="background-image: url('<?= $category->getImageUrl();  ?>');" alt="">
                        </div>

                        <p> <?php echo $category->getName() ?></p>
                    </div>
                </a>
            <?php
            endforeach;
            ?>
        </div>
    </div>
</section>


Realtime Cooldown HTML and PHP [closed]

First I have two file like this…

Thats My File

Inside Index.html, Like this…

var ValidTime = new Date('Jun 13, 2024 16:44:00').getTime();
var TimesOut = setInterval(function() {
  var DateNow = new Date().getTime();
  var Duration = ValidTime - DateNow;
  var Day = Math.floor(Duration / (1000 * 60 * 60 * 24));
  var Hours = Math.floor((Duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var Minute = Math.floor((Duration % (1000 * 60 * 60)) / (1000 * 60));
  var Second = Math.floor((Duration % (1000 * 60)) / 1000);
  document.getElementById('TimeRemaining').innerHTML = Day + ' Day ' +
    Hours + ' Hours ' + Minute + ' Minute ' + Second + ' Second ';
  if (Duration < 0) {
    clearInterval(TimesOut);
   // 'Target.txt > text change Using PHP Fopen + Fwrite Method'
  } else {
  //  'Nothing'
  }
}, 1000);
<p id='TimeRemaining'></p>

I try to add Jquery and use form + onsubmit + Ajax, i modify thats code and it worked.
but, thats is not my goal.

I want everything PHP based. **
i want Like This

Impossible to do it?**

Calculate all ipv6 subnets using php/laravel

I have to calculate all subnets of ipv6 using laravel /php
this is an example of what I am trying to do

the customer should provide me the prefix of the IP and length like this

$ip = ‘2407:cb00:250’;
$subnetPrefix = 64;

so I nned to generate all available subnets like this

2407:cb00:250:1/64
2407:cb00:250:2/64
2407:cb00:250:3/64 ..etc

actually, I tried a lot without success especially when the user set len to be for example 65,66,67 ..etc
are there any one can help me to get what i want or if there is any laravel library that can do the work

Mastercard qr code is not recognized when scanning to pay

I have created a qr code and i am using mastercard qr code library to be able to detect the qr code, when i use my banking app as a test to check if it recognizing. It fails as it shown the qr scan code is not recognized as Master card qr code or Zapper. I need some help with my code below.

//qr scan code

<?php
require "vendor/autoload.php";

use EndroidQrCodeQrCode;
use EndroidQrCodeErrorCorrectionLevel;
use EndroidMastercardQRMastercardQRCode;

// Define the payment data
$paymentData = [
    "merchant" => "****",
    "amount" => 100.00, // Payment amount
    "currency" => "USD", // Payment currency
    "reference" => "123456789" // Payment reference
];

// Generate the Mastercard QR code payload
$payload = "MC" . json_encode($paymentData);

// Create the QR code
$qrCode = new QrCode($payload);

// Set QR code options
$qrCode->setSize(300); // Set the size of the QR code
$qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::LOW); // Set error correction level
//$qrCode->setEncoding(new Encoding('UTF-8')); // Set encoding

// Save the QR code as a PNG image
$qrCode->writeFile('C:/wamp64/www/eCommerce/eshopper/eshopper-1.0.0/img/qrcode.png');

// Output the QR code image
header("Content-Type: image/png");
echo $qrCode->writeString();
exit();

echo "QR code generated successfully!";
?>

How to retrive user data from URL without the index page appears

I am creating a page that retireve user data from URL. http://localhost/test/index/john this is the url. My issue is I don’t want the index in my url.

example:-
http://localhost/test/john

current url:-
http://localhost/test/index/john

How can I do that? Thanks in advance

Here is the code of retrieving data

session_start();
$mylink = $_SERVER['PHP_SELF'];
$link_array = explode('/',$mylink);
$lastpart = end($link_array);
$fetch_user = rtrim($lastpart, ".php");
$path_parts = pathinfo($mylink);
if ($path_parts == "php") {
}else{
    $session['user'] = $fetch_user;
    $slug = $session['user'];
}

This is the code in index.php:

if ($session['user']) {
    echo "<div id='slide-right'>";
    include_once("user2.php");  
    echo "</div>";
}else{
    echo "<div id='slide-left'>";
    include_once("user.php");   
    echo "</div>";
}

i need help for a project in php and sql [closed]

I am a young web developer in formation.

Firstly, I have to apologize, I don’t have a perfect level of English, everything I know, I learned it by myself, I never had English at school. I’m French. There may be some errors, I searched for every error, but it is possible that there are still some

For my end’s year exam, I have to code a website. Mine will be on the theme of Yu-Gi-Oh! The users will be able to post publications, comment, like a forum, create 1 or more decks, and note and/or comment on other users’ decks. I have an API as a base from which I have managed to extract the data, and everything is displayed correctly, but I would like to be able to build a deck and I don’t managed “yet” to create a deck.

I had as original idea, building a deck, but later for storage, rather than storing the entire deck in the database, save the deck in a variable, and save the variable instead of the deck
I code in OOP with DAO in PHP. Thank you in advance for your help.

Mysql is inserting record twice, how can I prevent this?

I have a form that calls this script, this is generating invoices but sometimes it creates duplicate, I cant figure it out, please help thanks in advance. The duplicate data was inserted at the same time as the table has timestamp, both records where inserted 2023-06-12 10:36:40 x 2. On the top of the php code I have added some code to check for duplicate, but it seems when inserting it inserts twice with the same time 2023-06-12 10:36:40.

The script

<?php 

// inv binder stop the code if it wants to create dublicate give a message quotation created already
$inv_code = $_POST['inv_code']; 

// Below is optional, remove if you have already connected to your database.
$mysqli = mysqli_connect('localhost', 'root', '', 'crmsigni_crm');

$sql=mysqli_query($mysqli,"SELECT * FROM si_invoices where inv_code='$inv_code'")or die(mysql_error());

$row=mysqli_fetch_assoc($sql);

$compareinv = $row['inv_code'];

$invclient = $row['main_client'];

$jobtitle = $row['job_title'];

if( $inv_code === $compareinv ){
    
    echo "<h4>Same quotation is already created with the Client name of".$invclient." and Job title of: ".$jobtitle."</h4><br/>";
    
    die("Browse to check the invoice, your quotation was already created!");
}

?>

<?php

if(isset($_POST['price']) && !empty($_POST['price'])) {
     //conditional to insert itemsinv start
    $conn = $mysqli = mysqli_connect('localhost', 'root', '', 'crmsigni_crm');
/*
$data = $_POST;
echo "<pre>";
var_dump($data);*/

$count = count($_POST['qty']);

$name = $_POST['name'];
$price = $_POST['price'];

for ($i=0; $i<$count; $i++) {

    $sql = "INSERT IGNORE INTO itemsinv (ln_no, productname, particulars, qty, price, item_total, invidfk) VALUES ('{$_POST['ln_no'][$i]}','{$_POST['productname'][$i]}','{$_POST['particulars'][$i]}', '{$_POST['qty'][$i]}' , '{$_POST['price'][$i]}' , '{$_POST['item_total'][$i]}' , '{$_POST['invidfk'][$i]}')";

    $conn->query($sql);
} //conditional to insert itemsinv end
    
}

else {

echo "ERROR! Invoice cannot be created with no any details<br/>";

echo "<a href='choose-invoice-type.php'>Re-create Profoma again here</a>";

exit();
}

?>


<?php

/*Create contact first*/
$conn = $mysqli = mysqli_connect('localhost', 'root', '', 'crmsigni_crm');
mysqli_select_db($conn,'crmsigni_crm');

$main_client = $_POST['main_client'];
$contact_name = $_POST['contact_name'];
$billing_name = $_POST['billing_name'];
$postal_address = $_POST['postal_address'];
$cell_clnt = $_POST['cell_clnt'];
$offc_loc = $_POST['offc_loc'];
$site_loc = $_POST['site_loc'];

$email_addr = $_POST['email_addr'];
$job_title = $_POST['job_title'];
$clnt_tin = $_POST['clnt_tin'];
$clnt_vrn = $_POST['clnt_vrn'];
$vat_expt = $_POST['vat_expt'];
$expt_cert = $_POST['expt_cert'];
$our_tin = $_POST['our_tin'];
$our_vrn = $_POST['our_vrn'];

$inv_code = $_POST['inv_code']; 

$prepared_by = $_POST['prepared_by'];
$sales_person = $_POST['sales_person'];

// put discount and no discount values

$discamt = $_POST['amountUSD'];

if ($discamt == 0 ) {
    
$st = $_POST['sub_totl'];
$sub_totl = number_format($st / 1000, 3, ",", ",");

//discount value 
$dis_perc_sub = 0;

//discount total
$dis_val_sub = 0;

$vp = $_POST['vat_percent'];
$vat_percent = number_format($vp / 1000, 3, ",", ",");

$gt = $_POST['grand_total'];
$grand_total = number_format($gt / 1000, 3, ",", ",");

    
} else if ($discamt > 0 ) {

$st = $_POST['sub_totl'];
$dt = $_POST['amountNGN'];
$nsubttl = $st;   
$sub_totl = number_format($nsubttl / 1000, 3, ",", ","); 

//discount value 
$dis_perc_sub = $_POST['amountUSD'];

//discount total
$dstc = $_POST['amountNGN'];
$dis_val_sub = number_format($dstc / 1000, 3, ",", ",");

$vp = 0.18 * $nsubttl;
$vat_percent = number_format($vp / 1000, 3, ",", ",");

//grandtotal new
$gt = $vp + $nsubttl;
$grand_total = number_format($gt / 1000, 3, ",", ",");
   
}


//pending for lpo users to update lpo

$lpo_user = "UPDATE";
$lpo_status = "UPDATE";


date_default_timezone_set('Africa/Dar_es_Salaam');

$newDate = date('Y-m-d h:i:s T', time());


$sqlone= "INSERT IGNORE INTO si_invoices ( id, date_created, main_client, contact_name, billing_name, postal_address, cell_clnt, offc_loc, site_loc, email_addr, job_title, clnt_tin, clnt_vrn, vat_expt, expt_cert, our_tin, our_vrn, inv_code, prepared_by, sales_person, sub_totl, vat_percent, grand_total, dis_perc_sub, dis_val_sub, lpo_user, lpo_status)

VALUES (default, '$newDate', '$main_client', '$contact_name', '$billing_name', '$postal_address', '$cell_clnt','$offc_loc', '$site_loc', '$email_addr','$job_title','$clnt_tin','$clnt_vrn','$vat_expt','$expt_cert','$our_tin','$our_vrn','$inv_code','$prepared_by','$sales_person','$sub_totl','$vat_percent','$grand_total', '$dis_perc_sub', '$dis_val_sub', '$lpo_user','$lpo_status')";

if ($conn->query($sqlone) === TRUE) {
        echo '<div class="alert alert-success">
    <strong>OK!</strong>details added!.
</div>';

} else {
        echo "Error: else statement of insert invoices" . $sqlone . "<br>" . $conn->error;
}

?>


  <?php


$idswitch = $_POST['inv_code']; // id for viewing
// Below is optional, remove if you have already connected to your database.
$mysqli = $mysqli = mysqli_connect('localhost', 'root', '', 'crmsigni_crm');

$sql=mysqli_query($mysqli,"SELECT * FROM si_invoices WHERE inv_code ='$idswitch'")or die(mysql_error());

$row=mysqli_fetch_assoc($sql);

$idz = $row['id'];

header('Location: pdfy-invoices.php?id='.$row['id'].''); 

echo '<a href="pdfy-invoices.php?id='.$row['id'].'" target="_blank" >VIEW PROFOMA IN PDF FORMAT</a>';

?>

    </div>
</div>

</div>
<?php include('include/footer.php');?>

JWT Validation Authorization

please help,
I have a problem with my code, I tried to provide JWT Validation at login, replace Session Php, I managed to get a token when the user has sent an email and password which is validated with data in the database, but I have a problem after the user gets the token and will executes the next command, namely

:Error: “kid” empty, unable to lookup correct key.

I know maybe because I haven’t given an ID to every data that I have validated and retrieved from the database, but I’m confused and need your help, experience is a valuable value. Thank You.

<?php   
require_once __DIR__.'/../vendor/autoload.php';        
use FirebaseJWTJWT;
use FirebaseJWTKey;

class Session
{

    public function __construct(public string $username, public string $role)
    {
    }

}

class SessionManager
{

    public static string $SECRET_KEY = "ahwehahewaheksmdashdadjwadmawduaskahkk";

    public static function login(string $username, string $password): bool
    {   
        try {
            $pdo = new PDO("mysql:host=localhost;dbname=assabil", "root", "");
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $statement = $pdo->prepare("SELECT Username, password_col FROM pengurus");
            $statement->execute();
            $row = $statement->fetch(PDO::FETCH_ASSOC);
            if ($row && password_verify($password, $row['password_col'])) {
                $payload = [
                    'uid' => $id,
                    "Username" => $username,
                    "role" => "customer"
                ];
          
                $jwt = JWT::encode($payload, SessionManager::$SECRET_KEY, 'HS256');
                setcookie("A-SSB-SESSION", $jwt);
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            return false;
        }
    }
    public static function getCurrentSession(): Session
    {
        if (isset($_COOKIE['A-SSB-SESSION'])) {
            $jwt = $_COOKIE['A-SSB-SESSION'];
            try {
                $payload = JWT::decode($jwt, SessionManager::$SECRET_KEY, ['HS256']);
                var_dump($payload); // Check the value of $payload
                return new Session($payload->Username, $payload->role);
            } catch (Exception $exception) {
                echo "Error: " . $exception->getMessage();
                die(); // Terminate the script to see the error message
            }
        } else {
            throw new Exception("User is not login");
        }
    }
    
    
}


?>

I’m trying to find a solution regarding JWT Token validation, I hope you can get a solution.

How to get data from multiple database in multi tanent laravel website to base website?

I am working on a laravel application which is an SAAS application.

This application create an new database for each new tanent.
This application is an ecommerce application which create ecommerce website for customers.

Now, problem is that i want to develop an module for the base website in which the products from all the tanent’s website will be visible

For example:-

Base website – https://base.com/shoping

Will show all the products from all tanent’s websites-

https://customer1.base.com,
https://customer2.base.com,
etc.

Please suggest me the best way to achieve this.

Thanks

Get strict-origin-when-cross-origin error when using PHPMailer on localhost/xampp

I am new to the coding world.

I try to get this contact form I found working.
However, running it on localhost/xampp always gives me a Get strict-origin-when-cross-origin error.

I am trying that since a few days now.
Anyone an idea how to get that contact form with PHPMailer to work?

Dev Console

<?php

/* Handle CORS */

// Specify domains from which requests are allowed
header('Access-Control-Allow-Origin: *');

// Specify which request methods are allowed
header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');

// Additional headers which may be sent along with the CORS request
header('Access-Control-Allow-Headers: X-Requested-With,Authorization,Content-Type');

// Set the age to 1 day to improve speed/caching.
header('Access-Control-Max-Age: 86400');


 
/**
 * This example shows how to handle a simple contact form safely.
 */

//Import PHPMailer class into the global namespace
use PHPMailerPHPMailerPHPMailer;

$msg = '';
//Don't run this unless we're handling a form submission
if (array_key_exists('email', $_POST)) {
    date_default_timezone_set('Etc/UTC');

    require '../vendor/autoload.php';

    //Create a new PHPMailer instance
    $mail = new PHPMailer();
    //Send using SMTP to localhost (faster and safer than using mail()) – requires a local mail server
    //See other examples for how to use a remote server such as gmail
    $mail->isSMTP();                                           
    $mail->Host       = 'smtp.gmail.com';                   
    $mail->SMTPAuth   = true;                            
    $mail->Username   = '[email protected]';                
    $mail->Password   = 'xxx';                       
    $mail->SMTPSecure = 'ssl';                             
    $mail->Port       = 465; 

    //Use a fixed address in your own domain as the from address
    //**DO NOT** use the submitter's address here as it will be forgery
    //and will cause your messages to fail SPF checks
    $mail->setFrom('[email protected]', 'First Last');
    //Choose who the message should be sent to
    //You don't have to use a <select> like in this example, you can simply use a fixed address
    //the important thing is *not* to trust an email address submitted from the form directly,
    //as an attacker can substitute their own and try to use your form to send spam
    $addresses = [
        'sales' => '[email protected]',
        'support' => '[email protected]',
        'accounts' => '[email protected]',
    ];
    //Validate address selection before trying to use it
    if (array_key_exists('dept', $_POST) && array_key_exists($_POST['dept'], $addresses)) {
        $mail->addAddress($addresses[$_POST['dept']]);
    } else {
        //Fall back to a fixed address if dept selection is invalid or missing
        $mail->addAddress('[email protected]');
    }
    //Put the submitter's address in a reply-to header
    //This will fail if the address provided is invalid,
    //in which case we should ignore the whole request
    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = 'PHPMailer contact form';
        //Keep it simple - don't use HTML
        $mail->isHTML(false);
        //Build a simple message body
        $mail->Body = <<<EOT
Email: {$_POST['email']}
Name: {$_POST['name']}
Message: {$_POST['message']}
EOT;
        //Send the message, check for errors
        if (!$mail->send()) {
            //The reason for failing to send will be in $mail->ErrorInfo
            //but it's unsafe to display errors directly to users - process the error, log it on your server.
            $msg = 'Sorry, something went wrong. Please try again later.';
        } else {
            $msg = 'Message sent! Thanks for contacting us.';
        }
    } else {
        $msg = 'Invalid email address, message ignored.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact form</title>
</head>
<body>
<h1>Contact us</h1>
<?php if (!empty($msg)) {
    echo "<h2>$msg</h2>";
} ?>
<form method="POST">
    <label for="name">Name: <input type="text" name="name" id="name"></label><br>
    <label for="email">Email address: <input type="email" name="email" id="email"></label><br>
    <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br>
    <label for="dept">Send query to department:</label>
    <select name="dept" id="dept">
        <option value="sales">Sales</option>
        <option value="support" selected>Technical support</option>
        <option value="accounts">Accounts</option>
    </select><br>
    <input type="submit" value="Send">
</form>
</body>
</html>

Tried using different headers to allow CORS > same result

Prevent malicious code by checking for unallowed characters

I have a lot of inputs on a client side
Values are sent to php server as a json string
I need to ensure that any of the value does not contain any html tag or an executable function
I hope that is enough to check for some unallowed characters or strings like this – <, [,{, (), function
The question is – Is this way secure enough ?

$arr = json_decode($str, true);  

$values = array_values($arr);  
$err = 0;  
foreach($values as $val){  
    if(str_contains($val, "<") ||  
    str_contains($val, "[") ||  
    str_contains($val, "()") ||  
    str_contains($val, "{") ||  
    str_contains($val, "function")){$err = 1;}  
}  
if($err == 1){echo 'INPUT IS NOT ALLOWED'; exit();}

Can i get all messages from my channel or group? use telegram-bot-sdk

I use library telegram-bot-sdk and i have a question, exists method for get messages from channel or group? If not, how can i write my own method, where i should write this code? Or send me example code, how i can expand the library and add my own methods. Thank you!

I found API method https://core.telegram.org/method/channels.getMessages but don’t now how use it in my library.