Parse time error Fatal error: Uncaught DateMalformedStringException:

I’m studying the date function in PHP and ran into the same problem. An error occurs in my code that works with a large date. Help me understand what the problem is with this code.

   $start = new DateTime('02.12.20239');
   var_dump($start);

This code throws an error:
Fatal error: Uncaught DateMalformedStringException: Failed to parse time string (02.12.20239) at position 10 (9): Unexpected character in C:ProjectsPhptest1test1.php:2
How to work with large dates in php?

Hosting a simple PHP Websocket with Hostinger VPS + CloudPanel + Nginx

I have built a chat app that uses Ratchet as the websocket library which I want to host online. But before that, I want to test the websocket connection online first so that I can confirm everything is working well before hosting the actual application. For this, I have downloaded two files from Github which is a simple PHP websocket script. One is index.php for the client side browser connection and one is socket.php which runs the server and connects in the terminal. This both scripts run well in the Xampp environment on my PC. I just have to do php socket.php and the script runs with ease. However, same method is not working on the VPS when I try it using Putty (SSH Connection). The server is Nginx and VPS control panel is CloudPanel. The two files are uploaded are:

index.php

<!DOCTYPE html>
<html>
<body>
  <div id="root"></div>
  <script>
    var host = 'wss://mysite.app:9000/wsapp/';
    var socket = new WebSocket(host);
    socket.onmessage = function(e) {
      document.getElementById('root').innerHTML = e.data;
    };
  </script>
</body>
</html>

socket.php

$address = 'mysite.app'; // localhost on Xampp and it works well there
$port = 9000;

// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$client = socket_accept($server);

echo "Socket Accepted";

// Send WebSocket handshake headers.
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)rn#', $request, $matches);

$key = base64_encode(pack(
  'H*',
  sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));

$headers = "HTTP/1.1 101 Switching Protocolsrn";
$headers .= "Upgrade: websocketrn";
$headers .= "Connection: Upgradern";
$headers .= "Sec-WebSocket-Version: 13rn";
$headers .= "Sec-WebSocket-Accept: $keyrnrn";
socket_write($client, $headers, strlen($headers));

echo "Connection Established!";

// Send messages into WebSocket in a loop.
while (true) {
  sleep(1);
  $content = 'Now: ' . time();
  $response = chr(129) . chr(strlen($content)) . $content;
  socket_write($client, $response);
}

When I execute php socket.php in the command line using SSH (putty), the line echo "Socket Accepted"; is never executed. Which means the socket_accept code is not getting executed here. I have been through several articles and most talk about making changes to the Nginx.conf file. However, I am not sure if just making that change will be enough because it can be due to blocked port or something else. Which I don’t know how to open or debug. For reference, the code of Nginx.conf is given here:

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    {{ssl_certificate_key}}
    {{ssl_certificate}}
    server_name mysite.app;
    return 301 https://www.mysite.app$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    {{ssl_certificate_key}}
    {{ssl_certificate}}
    server_name www.mysite.app www1.mysite.app;
    {{root}}
    
    {{nginx_access_log}}
    {{nginx_error_log}}
    
    if ($scheme != "https") {
        rewrite ^ https://$host$uri permanent;
    }
    
    location ~ /.well-known {
        auth_basic off;
        allow all;
    }
    
    {{settings}}
    
    location / {
        {{varnish_proxy_pass}}
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_hide_header X-Varnish;
        proxy_redirect off;
        proxy_max_temp_file_size 0;
        proxy_connect_timeout      720;
        proxy_send_timeout         720;
        proxy_read_timeout         720;
        proxy_buffer_size          128k;
        proxy_buffers              4 256k;
        proxy_busy_buffers_size    256k;
        proxy_temp_file_write_size 256k;
    }
  
    location /wsapp/ {
        proxy_pass http://www.mysite.app/socket.php;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
    }
  
    location ~* ^.+.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
        add_header Access-Control-Allow-Origin "*";
        expires max;
        access_log off;
    }
    
    if (-f $request_filename) {
        break;
    }
}

server {
    listen 8080;
    listen [::]:8080;
    server_name www.mysite.app www1.mysite.app;
    {{root}}
    
    try_files $uri $uri/ /index.php?$args;
    index index.php index.html;

    location ~ .php$ {
        include fastcgi_params;
        fastcgi_intercept_errors on;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        try_files $uri =404;
        fastcgi_read_timeout 3600;
        fastcgi_send_timeout 3600;
        fastcgi_param HTTPS "on";
        fastcgi_param SERVER_PORT 443;
        fastcgi_pass 127.0.0.1:{{php_fpm_port}};
        fastcgi_param PHP_VALUE "{{php_settings}}";
    }
    
    if (-f $request_filename) {
        break;
    }
}

I have added this block in the config file above:

location /wsapp/ {
    proxy_pass http://www.mysite.app/socket.php;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
}

Then, I restarted the Nginx server and in the terminal proceeded to the root folder of the website and tried running again php socket.php or php -q socket.php. However, it still doesn’t work. The function socket_accept is still never executed. In the browser also, I always get Firefox can’t establish a connection to the server at wss://mysite.app:9000/wsapp/.

And lastly, my OS is Ubuntu 22.04. Please let me know if anymore info is needed to diagnose and I shall add it.

Repetitive optional parameters in route

I’ve been looking for a solution that would allow me using multiple optional parameters in a route.

Something like
/product/{category?*}/{productname}

Let’s say I have 1 product that belongs to 4 categories and a second product that belongs to 7 categories. These categories are in a parent-child relation (it’s a tree). I would like to see the whole category family in the url when I go to the product page.

For example, the first product url would look like this:

www.myshop.com/product/main1/sub1/sub11/sub111/myproduct

With the second product it would be:

www.myshop.com/product/main2/sub2/sub22/sub222/sub2222/sub22222/sub222222/myproduct2

Is there a solution that would allow behaviour like this?

Call Symfony Controller from Gotenberg, itself called from an other Symfony Controller

I encountered the following problem using Gotenberg 7 and Symfony 6.4 together.

It seems like I cannot make a Request in a Controller which awaits for an other Request’s answer. The first Request calls Gotenberg API and waits for its answer, while Gotenberg makes a Request to an other Controller and waits for its answer.

According to Gotenberg-php documentation and Gotenberg’s, If I want to generate a PDF I have two choices: sending an HTML string to Gotenberg, or sending an URL to it. The latter feels simpler since I don’t have to inject Webpack’s generated script and style files while modifying their path in my HTML string.

For development purposes, I’m using Symfony-CLI server, which serves itself on port 8000. I haven’t tested this in Prod yet. Gotenberg is ran from inside a Docker container, on port 3000.

So, in my Symfony project there is this static webpage that I created, it’s rendered when going to https:/localhost:8000/home.

If I go to https:/localhost:8000/pdf/, I want a Gotenberg-generated PDF to be displayed.

Here’s my HomeController:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;

class DefaultController extends AbstractController
{
    #[Route(path: "/home", name: "home")]
    public function showHome(): Response
    {
        return $this->render('Website/home.html.twig');
    }
}

And here’s my PdfController:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use GotenbergGotenberg;

class PdfController extends AbstractController
{

    $request = Gotenberg::chromium('http://localhost:3000/')
        ->url('https://localhost:8000/home');

    try {
        $gotenbergResponse = Gotenberg::send($request);

        $contents = $gotenbergResponse->getBody()->getContents();

        return Response(
            $content,
            Response::HTTP_OK,
            [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => 'inline; filename="home.pdf"'
            ]
        )
    } catch (Exception $e) {
        throw new RuntimeException('Error: ' . $e->getMessage());
    }
}

If I put a breakpoint in DefaultController and an other one in ̀PdfController, I can see that:

  • PdfController is correctly hit;
  • In my Gotenberg logs, the route http://localhost:3000 is correctly hit and Gotenberg tries to access https://localhost:8000/home;
  • After a while, after no answer from https://localhost:8000/home, Gotenberg returns a 503 HTTP Response to my PdfController, which returns with an error;
  • At this precise moment, the breakpoint in DefaultController stops my Symfony application, showing that it was correctly hit.

It seems like my Symfony application, under this configuration, cannot handle more than one request at the same time. Is it because of my application, do I have to sue an other specific configuration for it to work, is it because I’m using Symfony server, or is it by design?

Not all cookie saved from one page

I have a long text that needs to be saved in cookies. I break it down by the number of characters and try to save it into cookies cyclically, but only the last one is saved. Below is an example of code that should do this.

To save cookies:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}

$token = generateRandomString(8851);
$name = 'ck';
$exp = 3600;
$domain = '.example.local';

if(strlen($token) > 4096) {
    $values = str_split($token, 4095);
    foreach ($values as $key => $value) {
        setcookie(
            name: $name . '_' . $key,
            value: $value,
            expires_or_options: time() + $exp,
            domain: $domain
        );
    }
} else {
    setcookie(
        name: $name,
        value: $token,
        expires_or_options: time() + $exp,
        domain: $domain
    );
}

For view cookies:

<?php
echo '<pre>';
var_dump($_COOKIE);

Display previously ordered products in WooCommerce admin Related Orders

I would like to show previously ordered items under Related Orders in WooCommerce.

I found this code by @loictheaztec that almost do what I am looking for : https://wordpress.stackexchange.com/questions/348105/display-order-items-names-in-woocommerce-admin-orders-list

enter image description here

But insted of the general Order list I would like to have in added under Related Orders at the buttom of each Order page.

I tried to modify the code but can’t get it to work

Calculate daily minutes from an appointment lasting several days

I need a PHP array at the end based on the following information.

$startDateTime = "2024-01-06 14:00:00";
$endDateTime = "2024-01-13 14:00:00";

However, the working hours from
Monday to Friday 9:00 a.m. to 6:00 p.m.
and
Saturday 9:00 a.m. to 2:00 p.m.
should be taken into account.

My output as a PHP array should look like this (Date => Minutes – but only in Working hours):

Array
(
    [2024-01-06] => 0
    [2024-01-07] => 0
    [2024-01-08] => 540
    [2024-01-09] => 540
    [2024-01-10] => 540
    [2024-01-11] => 540
    [2024-01-12] => 540
    [2024-01-13] => 300
)

For explanation:

06 January 2024 is a Saturday and the appointment starts after work ends.

From 2024-01-07 to 2024-01-12 he works the full 9 hours every day. January 2024, 13 is again a Saturday and 5 hours are part of the working time.

I would be very happy about a solution.

I’ve tried a lot, but can’t find a correct solution in PHP.

shopify fulfillment not working with rest api

I am trying to fulfilment by line items with shopify API but it is not working
this is my demo store

I have add all the thing original demo store name and access key

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://bforbay.myshopify.com/admin/api/2023-10/fulfillments.json',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "fulfillment": {
        "line_items_by_fulfillment_order": [
            {
                "fulfillment_order_id": 5749831630946, // this one is order id
                "fulfillment_order_line_items": [
                    {
                        "id": 13418123853922, // one iteam id 
                        "quantity": 1 
                    }
                ]
            }
        ],
        "tracking_info": {
            "number": "AWEADSF898",
            "url": "https://www.my-shipping-company.com?tracking_number=MS1562678"
        }
    }
}',
  CURLOPT_HTTPHEADER => array(
    'X-Shopify-Access-Token: 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',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

I am geting error {“errors”:”Not Found”} why?

I have read_fulfillments,write_fulfillments scope also

php not recieving json object from javascript and shows an empty array string(0) “”, but still shows a successful response in javascript console.log

i’m building an app that asks you questions you can answer, i’m building it in react js, and my back-end is in php. the questions i’m showing comes from a database that php fetches and sends that in a json object to the javascript, this is successful. however, when i want to send the answers to the php in json format to save it in the database, the php is recieving an empty array, when i var_dump() the object it shows string(0) “” but in the console.log in javascript it is showing a successful php response with the correct json object.

this is very strange to me, i checked the json object in javascript before sending it to php and it is correct. but the $_POST php recieves is empty.

this is the php response i get in the javascript console.log:

string(700) "{"0":[{},{"done":false},{"answer":"","skip":true},{"answer":"NAETNAETNETN","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"abegegnwegn","skip":false},{"answer":"","skip":false},{"answer":"","skip":false}],"1":[{},{"done":true},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"","skip":false},{"answer":"SFBSFBsfb","skip":false},{"answer":"","skip":false}]}"
Done: 
Answer: , Skip: 1
Answer: NAETNAETNETN, Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: abegegnwegn, Skip: 
Answer: , Skip: 
Answer: , Skip: 
Done: 1
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: , Skip: 
Answer: SFBSFBsfb, Skip: 
Answer: , Skip: 
Data received successfully`

but when I open the php in the browser I see this:

string(0) "" {"error":"Invalid JSON data"}

here is my code:

javascript function:

export const ExportJSON = async (jsonObject) => {

  try {
    // Send a POST request to the PHP script using async/await
    const response = await fetch('http://my-IP-adress/documentation-chat/import.php', {
      "method": 'POST',
      "headers": {
        'Content-Type': 'application/json',
      },
      "body": JSON.stringify(jsonObject),
    });


    // Check if the HTTP response is successful (status code 200-299)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}, Message: ${await 
      response.text()}`);
    }

    // Parse the response text
    const result = await response.text();
    console.log(result); // Display the response from the PHP script
    console.log(jsonObject)
    return result;
  } catch (error) {
    console.error(error);
    return error;
  }
};

php file:

<?php

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// If it's an OPTIONS request, send the necessary headers and exit
// If it's an OPTIONS request, send the necessary headers and exit
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('HTTP/1.1 200 OK');
    header('Access-Control-Allow-Credentials: true');
    header('Content-Type: application/json');

    exit();
}



// Read the raw POST data
$jsonData = file_get_contents('php://input');
var_dump($jsonData); // Log the received data

// Decode JSON with boolean values 
$decodedData = json_decode($jsonData, true);

// Check if decoding was successful 
if ($decodedData === null) {
    // Handle JSON decoding error
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Invalid JSON data']);
    exit();
}

// Iterate through the outer array
foreach ($decodedData as $section) {
    // Access values in the inner array
    $done = $section[1]['done'] ?? false;

    // Example: Print the value from the outer array
    echo "Done: $donen";
    // Iterate through the questions
    for ($i = 2; $i < count($section); $i++) {
        // Access values in the question array
        $answer = $section[$i]['answer'] ?? '';
        $skip = $section[$i]['skip'] ?? false;

        // Perform any necessary processing or storage of the data
        // ...

        // Example: Print the data for demonstration purposes
        echo "Answer: $answer, Skip: $skipn";
    }
}

// Send a response back to the client
echo 'Data received successfully';
?>

I met an error syntax when testing SQL injection with login page

When I try to test how SQL injection works in my login page and my code is:

public function login() {
      
        $db = new Database();
    
 
//---------------------------------------------------------------- --------------------------------
        $p = $this->getPhone();
        $pa = $this->getPassword();
//--------------------------------------------------------------------------------------------------------------------------------
       
    // $sql = "SELECT * FROM dbo.Account WHERE phone = ? and password = ?";
//----------------------------------------------------------------------------------------------------
      
        $sql = "SELECT * FROM dbo.Account WHERE phone = $p and password = $pa";
//----------------------------------------------------------------------------------------------------
        // Use an array to pass parameters in the correct order
        // $params = array($this->phone, $this->password);
        // var_dump($sql); 
 //----------------------------------------------------------------------------------------------------       
 
        // $result = $db->query($sql,$params);
//--------------------------------------------------------------------------------------------------
        $result = $db->query($sql);
    //    var_dump($result);
     
            if ($result) {
                // Check if there is a matching user
                if ($result > 0) {
                    return true;

It
                    
                } else {
                    // Incorrect phone or password
                    return false;
                }
            } else {
                // Error in the query
                // You might want to log the error or handle it appropriately
                return false;
            }
        
       
    }
    

So i met this ERROR when run by PHP with XAMPP:

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ‘&’. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ‘&’. ) )

How can i fix this?

I tried to fix it but this wasn’t working

tinymce placeholder containing HTML

I have a placeholder I’d like to add to my tinymce editor, which contains HTML so when it displays it, it closes the placeholder attritube because of the double quotes in the HTML.

The HTML looks like this:

<p style="font-family: Arial;">hello</p>

I tried using strip_tags in PHP, which does work, however it removes all of the line breaks from the <p> tags.

I tried using nl2br and replacing the <br /> tag with PHP_EOL and rn which didn’t work.

str_replace('<br />', 'rn', nl2br(strip_tags('<p style="font-family: Arial;">hello</p>')));

How can I add this placeholder in with or without the HTML, but keeping the line breaks.

Better way of storing this data on MYSQL and used in laravel project

I want to store schools general results in a database in the most efficient way with less repetitions, so the data will be from different schools for different years and the data is in this way, from division 0-4 and for each division it show number of male and female with that division in distinction. preferably i would like a single row,but don’t know if it will be easy to utilize during use in analysis,pulling in tables and graphs.

What i have done.

public function up()
    {
        Schema::create('csee', function (Blueprint $table) {
            $table->id();
            $table->integer('school_id');
            $table->integer('year');
            $table->json('division1')->comment('json with 2 entries which will respectively male then female');
            $table->json('division2')->comment('json with 2 entries which will respectively male then female');
            $table->json('division3')->comment('json with 2 entries which will respectively male then female');
            $table->json('division4')->comment('json with 2 entries which will respectively male then female');
            $table->json('division0')->comment('json with 2 entries which will respectively male then female');
            $table->timestamps();
        });
    }

below is a picture of the results tableenter image description here

Sample of insertion to database would look like this

DB::table('csee')->insert([
    'school_id' => 1,
    'year' => 2023,
    'division1' => json_encode([4, 6]), // 4 males, 6 females
    'division2' => json_encode([5, 7]), // 5 males, 7 females
    'division3' => json_encode([6, 8]), // 6 males, 8 females
    'division4' => json_encode([7, 9]), // 7 males, 9 females
    'division0' => json_encode([8, 10]), // 8 males, 10 females
    'created_at' => now(),
    'updated_at' => now(),
]);

how to read and modify php variables using javascript [duplicate]

I want to access php variables in javascript, to be able to pass variables between devices (for example user 1 clicks a button and a function is triggered on user 2’s device)
Something like this:

PHP.php:

<?php 
$variable = 1;
?>

SCRIPT.js

var jsvar = NaN;
function sendvariable(value)
{
//php variable
$variable = value;
}
function getvariable()
{
//return a php variable
return $variable;
}
function tick()
{
jsvar = getvariable();
}
setInterval(tick,1000);

I tried something like this:
jsvar = '<?php echo $variable; ?>';
but it just outputed it as a string

Role base access control

i have crated a admin panel in php codeigeniter, i have to implement Role base access control in this admin panel.i want to add Role base acceass control through php codeigeniter.

Please help me for dovelopemt in that through csource code.

Could not resolve host from Curl PHP but not from Postman. Why?

I send a PHP Curl request and get the message: Could not resolve host.

The only thing from all of the variety answers that could help me is writing “IP => host” into the /etc/hosts (referring to https://stackoverflow.com/a/56580719/6104996). Only then I can get data from URL

Meanwhile, if I send the request with Postman, I can get the data even if didn’t write anything in /etc/hosts.

Why? How do I see is the actual request from Postman to copy it in my code? I don’t want to write anything in the /etc/hosts


P.S. if I click “Code” -> “PHP – cURL” and copy paste it to my code, it returns me “Could not resolve host” anyway

enter image description here