Replace pecl-math-stats library

I have a PHP 7.4 project featuring some statistical analysis using pecl-math-stats.
Since PHP 7.4 is end-of-life, I need to update to PHP8. On the extensions page of php.net this statistics package is mentioned without any notice of deprecation or other difficulties.

When i update the PHP to version 8, it turns that pecl-math-stats is incompatible with php8.
On the pecl site is stated that “This package is not maintained, if you would like to take over please go to this page.”

So i looked for other packages and found https://github.com/markrogoyski/math-php.
Does anyone have experience with it?

I want to replace stats_cdf_normal for calculating the cumulative distribution function.
When i use MathPHPProbabilityDistributionContinuous Normal, do I get equal results with the cdf function?

Creating PHP parralel treatments from a getResult doctrine request

I would like to do some kind of multi threading in a PHP8/Symfony6 environement which would work as follow:

I’m making a doctrine request which serve around a million of rows

I would like to create multiple parralel processes to treat those rows simultaneously.
My request is made with a getResult() which serve doctrine objects.
Is there a way I could create threads with an array of objects as parameter. And then process to create thread as long as my “queue” is filled with datas?

I found some informations about “pthreads” or “popen” but I’m not sure its still relevant as the topics are a bit old

GET request to retrieve product price and quantity from Woocommerce API , PUT request to update product price and quantity to Woocommerce API (in PHP)

Can someone send an example code snippet of a GET request sent to the Woocommerce API to retrieve product price and quantity?
And also, if possible, send an example code snippet of a PUT request to update the products price and quantity.

I would appreciate it if they’re both in PHP.
(I’m fairly new to programming).

I would also appreciate it if you could explain the code with comments.

Thank you in advance!

I’ve tried ChatGPT to write me the code but it didn’t work.
I’ve tried to study the official Woocommerce API docs however since i’m fairly new to programming, I couldn’t figure out much.

How to pass a value of a generated button from one PHP file to another?

I’d like to pass an id value of a PHP generated button from theory.php file to theory1.php file.
Here’s the code:

//theory.php file
require('components/db.php');
    $query = "SELECT * FROM `courses`";
    $result   = mysqli_query($connect, $query) or die("Error:" . mysqli_error($connect));;
    $numrows = mysqli_num_rows($result);

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

        $query = "SELECT * FROM `courses` WHERE courseID = '$i'";
        $result   = mysqli_query($connect, $query) or die("Error:" . mysqli_error($connect));;
        $rowQuery = mysqli_fetch_assoc($result);

        $_SESSION['course_ID'] = $i;

        echo '
        <div class="card">
                <img class = "cardImage" src="';
        echo $rowQuery['imageLink'];
        echo '" alt="Course 1">
                <h3>';
        echo $rowQuery['courseName'];
        echo '</h3>
                <p>';
        echo $rowQuery['courseTextOne'];
        echo '</p>
                <a href="theory1.php?course_ID=$i" class="button">Proceed</a>
            </div>'; //a - is a button which needs to have an ID to pass to theory1.php
    }

The code generates cards with buttons. I want each button to store a respective ID from the course from MySQL database. That ID needs to be passed to another page depending on which button (card) is clicked, so it can retrieve the right data from the database in the future.

Finding POST variable without apostrophe in code

I have a PHP application and since upgrading to PHP 8. I have discovered that in some random locations I have forgot to put apostrophe in some variable names so for example it should be:

$POST['VariableName']

But I have accidently put it as

$POST[VariableName]

And for some reason in previous PHP versions it just worked without breaking. However, in PHP 8, it’s not liking it. And I’m just not sure how I can go through so many files to look for this. Is there a way where I can maybe write a PHP code to go through a file and look for this error? or possibly use NotePad++ ?

Help and suggestions would really be appreciated.

Thanks

CORS policy error with vuejs in frontend and with php in the backend?

do you know what can cause the cors problem? When I worked on the project locally, there wasn’t any CORS error. Now when I deployed it live, I have the CORS error at fetching the data. If I understand it correctly, this is because the frontend app ist on example: https://myapp.com, and the backend is on https://myapp-backend.com. Also the problem comes from the backend side if I’m correct.

I tried some things what I found here stackowerflow’s posts. In the .htaccess file I added these lines:

 <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>

in the vite confing I added these lines:

cors:{
            "origin": "*",
            "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
            "preflightContinue": false,
            "optionsSuccessStatus": 204
        }

I found some extensions for chorme, but they also didn’t work.

What else can I try to solve this CORS error?

How to pass the selected value from Dropdown to PHP Variable?

I am using ajax and returning the json data like this that comes from my database.

{"id":"2","Day":"Monday","Open_hour":"15:00","Closed_hour":"22:00"}

My ajax call is as below. #add_r_date its the id of my dropdown select box.

$(document).ready(function(){   
    $("#add_r_date").change(function() {    
        var id = $(this).find(":selected").val();
        var dataString = 'Dateid='+ id;

        $.ajax({
            url: 'getTimeslots.php',
             type: "POST",
            dataType: "json",
            data: dataString,  
            cache: false,
            success: function(empData) {
               if(empData) {
                    $("#errorMessage").addClass('hidden').text("");
                    $("#recordListing").removeClass('hidden');                          
                    $("#selDay").text(empData.Day);
                    $("#openHour").text(empData.Open_hour);
                    $("#closedHour").text(empData.Closed_hour);

                } else {
                    $("#recordListing").addClass('hidden'); 
                    $("#errorMassage").removeClass('hidden').text("No record found!");
                }       
            } 
        });
    }) 
});

The data returns fine from getTimeslots.php as below in html.

<div id="selDay"></div>  
<div id="openHour"></div>
<div id="closedHour"></div> 

But i want to get the Selection from the dropdown on a php variable so i can use on my functions like
if(selectedDay === $selDay) { do something} .. So the $selDay should change everytime i use the dropdown and fetch the correct values from database.Basically its checking if the day is Sunday get the correct Open hour,closed hour and get the Day name. Any help is appreciated. Thanks in advance.

I tried decoding json. I am tried using the json as an array on a foreach loop but nothing worked.I dont know how to get the return value in a php variable after the dropdown selection.

Securing a PHP data request for code injection

The small website I am managing for my club is currently seeing an increased amount of attack attempts. Until now those attacks have not been very sophisticated and therefore nothing happened (yet). Now I just want to make sure that the way we request content is as protected as possible and not a huge hole in our defence. For that I think I need additional changes to the code, but don’t really know where to start.

The setup:
We load our content pages by using $_GET arguments to tell which site to get and then get parsed to a database to get more data for the specific site. This is all done using a rewrite rule so we don’t have to use index.php?arg1=this&arg2=that as our URL but can use /pages/arg1/1rg2

The code:

The rewrite rule looks as follows:

RewriteRule ^pages/([^/]*)/([^/]*)$ /index.php?arg1=$1&arg2=$2 [B,NE,L]

The code to then request the data from the database:

$statement = $connection->prepare("SELECT * FROM `navigation` WHERE `Name` = :arg2");
$statement->bindParam(":name", $name);
$statement->execute();
$result = $statement->fetch();

Now what I think i need to do is make additional checks for the arg2 string before I hand it to the database request, since I’m not sure if the binding actually prevents injections, but I am not sure what to check for as the string itself could contain special characters like

à l’ ù

and likewise symbols like

; . _ ( ) –

so I can’t just check if it is letters. I though about using regex to check if that string matches anying, like so:

if (!preg_match("/^([0-9a-z_s; ._à'ù()-])+$/i",$arg2)) {
        echo "Non valid string";
        exit;
  }

But I am not sure if this is enough to prevent code injection to either the php request or the database or at wore even both?
Do you guys have any tips or idea on how to close it down even more, so that only valid entries (i.e. non code text) will actually result in a query to the system? Or did I already do that and there is – for now – nothing more I can do?

Magento 2 email template edit url in html page

I’m trying to redirect to external URL with token in email template html path:

/vendor/magento/module-customer/view/frontend/email/password_reset_confirmation.html

I copy the html to my file in my path

/app/design/frontend/My_THEME/Magento_Customer/email/password_reset_confirmation.html

the code

<a href="{{var this.getUrl($store,'customer/account/createPassword/',[_query:[token:$customer.rp_token],_nosid:1])}}" target="_blank">{{trans "Set a New Password"}}</a>        </td>

I need to redirect this url to extrnal url, I tried:

<a href="{{var this.getUrl('https://www.my-simple.com/reset-password/',[_query:[token:$customer.rp_token],_nosid:1])}}" target="_blank">{{trans "Set a New Password"}}</a>```

but not working,
any help please 

recrusive looping and printing category Tree with multipule children

I have multiple Questions about my approach to my problem and how to solve it etc.

Problem: I need to a function that loops through a category tree which could have up to 6 drop downs and also returns an HTML String that contain the name of category link and its sub category’s

  1. Is recursive really the best approach to what I am doing? if not why and what should I be using instead of the recursive method?
  2. In my code I am trying to loop through the children of the parent and printing an HTML string that should look like thisul class="child first"><li class="parent"><a class="arrow-right" href="#">(parent name in the list)</a><ul class='child second'><li class="parent"><a class="arrow-right" href="#">(the name of the first sub child in parent)</a><ul class='child third'><li class="parent"><a href="#">last child of the previous sub child </a></li> which I am getting only when looping through the first child and after looping through the first child to the second every previous child gets duplicated for example:
    ul class="child first"><li class="parent"><a class="arrow-right" href="#">(parent name in the list)</a><ul class='child second'><li class="parent"><a class="arrow-right" href="#">(the name of the first sub child in parent)</a><ul class='child third'>ul class="child first"><li class="parent"><a class="arrow-right" href="#">(parent name in the list)</a><ul class='child second'><li class="parent"><a class="arrow-right" href="#">(the name of the first sub child in parent)</a><ul class='child third'><li class="parent"><a href="#">last child of the previous sub child </a></li> <ul class='child second'><li class="parent"><a class="arrow-right" href="#">(the name of the second sub child in parent)</a><ul class='child third'> and I know its because of the way I am calling the recursive function but I am lost and don’t know how to call it otherwise.

My code:

    function loopingThroughTree($listAllEntries, $categoryTree, $i = 0): string
    {
    
        $childLists =
            [
                0 => 'second',
                1 => 'third',
                2 => 'fourth',
                3 => 'fifth',
                4 => 'sixth'
            ];
    
    
    
        foreach ($categoryTree['sub'] as $categoryLevel) {
    
                $children [] = $categoryLevel;
                if ($categoryLevel['sub'] != null) {
                    $listAllEntries .= '<li class="parent"><a class="'
                        . appendArrow($categoryLevel) . '" href="'
                        . $categoryLevel['link'] . '">' .
                        $categoryLevel['name'] .
                        "</a><ul class='child {$childLists[$i]}'>";
                    $i++;
                    $children[] = $listAllEntries;
                    $listAllEntries .= loopingThroughTree($listAllEntries, $categoryLevel, $i);
                } else {
                    $listAllEntries .= '<li class="parent"><a href="'
                        . $categoryLevel['link'] . '">' .
                        $categoryLevel['name'] .
                        '</a></li>';
                }
        }
    
    
        $listAllEntries .= "</ul>";
    
        return $listAllEntries;
    
    }
$listAllEntries = '<ul class="child first">';
loopingThroughTree(listAllEntires,categoryTree)

Note:(I know that my HTML strings are wrong its and that’s because I am only focusing on the logic for the moment)

Example of what my list looks like:

parent => child[0]=>child[0]=>child[0]
                              child[1]
                              child[2]=>child[0]
                                        child[1]=>child[0]
                                                  child[1]
                                                  child[2]=>child[0]
                                                            child[1]
                                                            child[2]
                                        child[2]
                    child[1]
                    child[2]


          child[1]=>child[0]
                    child[1]
                    child[2]=>child[0]
                              child[1]
                              child[2]=>child[0]
                                        child[1]=>child[0]
                                                  child[1]
                                                  child[2]=>child[0]
                                                            child[1]
                                                            child[2]
                                        child[2]

Convert Apple Maps coordinates in universal format

I would like to convert the coordinates displayed in Apple Maps as

38,89016° N, 1,22427° O

(German notation)

or

38.89016° N, 1.22427° E

(English notation)

into something like

38.89016, 1.22427

(Expected result)

but only if the user did enter a expression matching this pattern and not if the user enters something like an address or anything in the input field.

Therefore I would be using PHP preg_replace()

However I have difficulties building a matching regex and was wondering if someone found a solution to this already?

I already tried different regex variations on my own already, but they did not work anything like what I would expect, so I did not add them here.

I though have a regex to verify, the expected result is in the correct form which does work as expected, though I wasn’t able to modify it for the replacement:

/^[-+]?([1-8]?d(.d+)?|90(.0+)?),s*[-+]?(180(.0+)?|((1[0-7]d)|([1-9]?d))(.d+)?)$/

i have developed a php project from XAMPP for Windows 8.1.10 but after uploading to cpanel mysql 8.1.10 projects misbehave

i have developed a php project with xampp 8.1.10 now when i upload it to cpanel the project duplicates data. below is the query

 $conn=db();
    $query = mysqli_query($conn,"SELECT * FROM items 
    JOIN item_unit ON item_unit.unitId=items.unitId 
    JOIN stock_category ON stock_category.categoryId=items.categoryId 
    JOIN warehouse ON warehouse.warehouseId=items.warehouseId
         WHERE warehouse.branchId=$branchId ORDER BY itemName ASC $limit");

    if(!$query || mysqli_num_rows($query) <= 0){

    }else{
        return $query;
    }

this is the offline project results
this is the online project results

the projects tends to duplicates items fives times each and i do not know what is the problem

i have not tried anything. i was expecting thr project to behave the same as offline

Search value in database with html and php

I just want to add search system for my website
My PHP Code:

<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];

//connect db
$con=mysqli_connect("localhost","root","","website");
    $sql = "SELECT * FROM search WHERE MATCH(language, title, command) AGAINST ('$" . $search . "%')";

    $run = mysqli_query($con,$sql);
    $foundnum = mysqli_num_rows($run);

    if($foundnum == 0){
        echo "Sorry we don't found any '<b>$search</b>'.";
    }else{
        echo "<h1> $foundnum Result found for "".$search.""</h1>";

        //get num of results stored in db
        $sql = "SELECT * FROM website WHERE MATCH(language,title,command) AGAINST ('%" . $search . "%')";
        $getquery = mysqli_query($con,$sql);

        while($runrows = mysqli_fetch_array($getquery)){
            $link = $runrows["URL"];

            echo "<h5>".$runrows["title"]."</h5>";
        }
    }
?>

My HTML Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Search</title>
    </head>
    <body>
        <form name="searchForm" method="get" action="search.php">
            <input type="text" placeholder="Search" name="search" aria-label="Search" required>
            <input type="submit" value="Search" name="submit"></input>
        </form>
    </body>
</html>

My database:

language    title          command
  sql    SELECT in sql     SELECT

but I got error when I press “Search” button :


Fatal error: Uncaught mysqli_sql_exception: Can't find FULLTEXT index matching the column list in D:NewXAMPPhtdocsTestsearchsearch.php:18 Stack trace: #0 D:NewXAMPPhtdocsTestsearchsearch.php(18): mysqli_query(Object(mysqli), 'SELECT * FROM s...') #1 {main} thrown in D:NewXAMPPhtdocsTestsearchsearch.php on line 18

I just try to search about my problem in internet but I didn’t get any answer. Please help me everyone thanks!

The alert message could not show up in PHP after inserting a new record in database

<?php
require_once('connMySql.php');

function function_alert($message) {
  
    // Display the alert box 
    echo "<script type='text/javascript'>alert('$message');</script>";
}

if($_POST){
    $brandName = $_POST["brandName"];
    $brandStatus = '1';
    $brandActive = $_POST["brandStatus"];
    $sql = "INSERT INTO brands(brand_name, brand_active, brand_status) VALUES (?,?,?)";
    $stmt = $db_link->prepare($sql);
    $stmt->bind_param('sss',$brandName,$brandActive,$brandStatus);
    $stmt->execute();
    $stmt->close();
    $db_link->close();

    header("Location: brand.php");
    function_alert('A new record has been inserted');
}

?>

I am expecting the code should show up the alert message after I called the function function_alert when redirecting to the page brand.php but after inserting a new record it just only redirects to the page without showing up the alert message. Any methods could show up the alert message after redirecting to the page?

I tried JavaScript method to show up the alert message but it does not work.

Web application security – where to start

I’m new to web application development and I wonder how to secure my app. Lately, I hear a lot of cases in the news where hackers stole data. If this happens regularly to professionally developed systems then how do I deal with this as starting web developer? I know this is a very general question but it seems very relevant nowadays. So where do I start with security? What are the aspects to consider? Which parts of the system are vulnerable? Etc.

Some details about my systems: I have developed a web application in PHP, JavaScript, HTTPS, HTML, and my§SQL. For logging in I used the strategy described in: https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php. The application is hosted on a shared server (apache) at a hosting company. The server runs php version 8.1.