How to fix the date comparing issue in php? [duplicate]

I want to compare a date is between two given dates or not and return the result. My logic is correct but I am unable to figure out why the statement is returning even if the date is exists in between two given dates. Can any one help me please?
Please remember the dates has to be in us format. The dates values assigned to $fromDate and $toDate coming from database but I just hardcoded them here for simplicity.

class Insurance {
        
    public $fromDate = '2019-10-01';
    public $toDate ='2020-10-01'; 
    
    public function checkDate($date) {
        $date = date('m-d-Y',strtotime($date));
        $fromDate = date('m-d-Y',strtotime($this->fromDate));
        $toDate = date('m-d-Y',strtotime($this->toDate)); 
        if(($date >= $fromDate) && ($date <= $toDate)) {
            return 'Yes';
        } else {
            return 'No';
        }
    
    }
}
    
$insuranace = new Insurance(1);
    
echo $insuranace->checkDate('01-01-2020');

Pulling laravel project to my computer with no local php and composer installed

I’m using docker for my local development on window 10. I’ve a folder on my local computer to manage and store codebase and other configuration files which in turn need to be mapped onto web root of the server running inside the docker. but the problem is that when i try to pull my laravel project using composer on my local machine, it gives error (composer not found) because there is no php and composer installed on my local machine. so, my question is:

  1. should i need to install php and composer on my local machine? it is
    a kind of running / managing php on local machine as well, I want to
    run my all-development stacks as the docker image only.
  2. or is there any way to use or refer the same php/composer which is running
    inside the docker to pull the codebase on my local computer?
  3. or are there other solutions around? please suggest, thanking you all!!

WP heartbeat for Laravel Nova?

WP heartbeat for Laravel Nova??

I need the option to lock a resource when someone opens it for edit.

So, like with WP heartbeat, that makes sure only one is using the resource.

Laravel Nova have the “Preventing Conflicts” functionality, but that does not prevent another user from opening the resource.
I want an icon or a message being displayed when you are trying to open a resource that is already in use,

Laravel attach data to pivot table

So i am working on a laravel project with multiple table’s and pivot table’s but i cant attach data to a specific pivot table because it wont accept the name.
as a user i want to be able to download files from the ‘file’ crud. That works. but after i downloaded i want to be able to see who downloaded what file as an admin, this does not work

the query i get is:INSERT INTO file_user (file_id, user_id) VALUES (7, 2)

i basically want to change the: file_user to download. but i have no idea how to do that without making a full query

table ‘file’

  • id
    -name
    -file (document)

table ‘user’
-id
-name
-username
-role

pivot table ‘download’
-id
-file_id
-user_id

user model:

 public function role(){
        return $this->belongsTo(Role::class,'role_id');
    }
    public function file(){
        return $this->belongsToMany(File::class);
    }
    

file model:

   public function user(){
        return $this->belongsToMany(User::class);
    }
    

    protected $table = 'file';

download model (pivot)

  protected $table = 'download';
    protected $fillable = [
        'file_id',
        'user_id',
    ];

    public function file() {
        return $this->belongsTo('file');
    }

    public function user() {
        return $this->belongsTo('users');
    }

controller:

 public function download(Request $request, int $fileId)
    {
        $id = Auth::user();
        $fullfile = File::find($fileId);
       
        $downloadfile = File::find($fullfile, ['file'])->pluck('file')->last();

       // return response()->download($downloadfile);
       dd($fullfile->user()->attach($id));
        return back();
    }

Laravel + JS – modal messages conflict

i’m using Laravel 9 and i have some buttons that need the user confirm. For example the user clicks on ‘confirm order’ a modal appears with message and two more buttons – cancel, confirm. If the user clicks on ‘confirm’ the form will be submitted and another modal message will pop out : ‘Order confirmed’ with button ‘ok’. The ‘Ok’ button for closing the widnow of second modal is not working. I don’t use often JS, can somebody tell me what’s wrong in the code?

view confirm form and modal:

        @if ($grid_data->first()->stato_ordine == 0) 
            <div>
                <button id="confirmBtn" class="btn btn-success me-3"><i class="fa-regular fa-circle-check me-2"></i>Conferma Ordine</button>
            </div>
                <!-- The Modal -->
                <div id="myConfirm" class="custom-confirm">
                    <!-- Modal content -->
                    <div class="modal-content text-center">
                        <p>Sei sicuro di voler confermare l'ordine?</p>                            
                        <form class="confirm-form" action="{{route('ordini.update', $grid_data->first()->id)}}" method="POST">
                            @csrf
                            @method('PATCH')
                            <input type="number" value="1" name="conferma_ordine" hidden>
                            <button type="submit" class="btn btn-success me-3">Conferma</button>
                            <span class="cancel btn btn-warning">Annulla</span>
                        </form>
                    </div>
                </div>
            @endif

User clicks confirm and this pops out:

  @if(session()->has('status'))
    <!-- The Modal -->
        <div id="myModal" class="custom-modal">
            <!-- Modal content -->
            <div class="modal-content shadow-success">
            <div class="text-center">
                <p class="text-success fs-5">{{ session()->get('status') }}</p>
                <i class="fa-regular fa-circle-check text-success fs-1 d-block"></i>
                <button class="modal-btn btn btn-success mt-4">Ok</button>
            </div>
            </div>
        </div>
    @endif

JS:

var myConfirm = document.getElementById("myConfirm");


var confirmBtn = document.getElementById("confirmBtn");


var cancel = document.getElementsByClassName("cancel")[0];

// When the user clicks on the button, open the modal
confirmBtn.onclick = function() {
  myConfirm.style.display = "block";
}


cancel.onclick = function() {
  myConfirm.style.display = "none";
}


window.onclick = function(event) {
  if (event.target == myConfirm) {
    myConfirm.style.display = "none";
  }
}

var modal = document.getElementById("myModal");


var closeBtn = document.getElementsByClassName("modal-btn")[0];


closeBtn.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

Cannot release variable’s memory with unset($var) or $var=null

I am trying to release the memory by useing unset() and $var = null;, but not obvious changes with just Only reduced a few KB

here is my code

var_dump(memory_get_usage()/1024/1024);   // output: 0.420059204102
$paginator = new Paginator( $mysql, $sql );

var_dump(memory_get_usage()/1024/1024);   // output: 0.420318603516

$ret = $paginator->getData('all', 1);
var_dump(memory_get_usage()/1024/1024);   // output: 80.0789031982

$form = $ret->items;
unset($paginator);
unset($ret);
// $paginator = null;
// $ret = null;
gc_collect_cycles();   // try to force free
var_dump(memory_get_usage()/1024/1024);   // output: 80.0779571533

How to call a laravel api route from web route using sail?

My Laravel App runs in sail on port 8000. I build a simple api route, that I can successfully call using postman: POST http://localhost:8000/api/auth/token:

Route::post('/api/auth/token', function () {
    return [
        'success' => true,
        'auth_token' => bin2hex(random_bytes(16)),
    ];
});

When I try to call the endpoint from the web routes, it is timing out:

Route::get('/auth', function () {
    $client = new GuzzleHttpClient();
    return json_deconde($client->post('http://localhost/api/auth/token')
        ->getBody()
        ->getContents());
});

I tried to following hosts

Inside of the sail container curl --request POST 'http://localhost/api/auth/token' is successfully working.

Is it possible to pass props from non ReactApp template (when using CDN import of React) to a ReactJS component?

I am importing ReactJS via CDN links into a huge existing PHP project (latte templates). So it is not a classic ReactApp. And I would like to play with it and see the options of React when used this way.

So far pretty good. But I would like to know if it is possible to pass props/data to a component generated this way? Have anybody here had some experience with it?

My latte code:

<div id="react_container"></div>

My js code:

'use strict'

const e = React.createElement
const { useState } = React

const ReactFun = () => {
  const [color, setColor] = useState('')

  const changeColor = () => {
    const newColor = color == 'black' ? '#1E88E5' : 'black'
    setColor(newColor)
  }

  return (
    <div className='pb-5 d-flex gap-regular'>
      <h4 className='mb-3' style={{ color: `${color}` }}>
        Magic
      </h4>
      <div className='btn btn-outline-primary' onClick={changeColor}>
        <span>Click to change color</span>
      </div>
    </div>
  )
}

const domContainer = document.querySelector('#react_container')
const root = ReactDOM.createRoot(domContainer)
root.render(e(ReactFun))

I found old solutions for class components here: How to pass server data into React component, so I guess there is a way, but I am trying now for hours and I can’t figure out how to pass anything into my component written this way.. has anyone any idea?

I would like to achieve something like this with a color for example:

<div id="react_container" data-defaultColor="red"></div>


const e = React.createElement
const { useState } = React

const ReactFun = ({defaultColor}) => {
  const [color, setColor] = useState(defaultColor)

  const changeColor = () => {
    const newColor = color == 'black' ? '#1E88E5' : 'black'
    setColor(newColor)
  }

  return (
    <div className='pb-5 d-flex gap-regular'>
      <h4 className='mb-3' style={{ color: `${color}` }}>
        Magic
      </h4>
      <div className='btn btn-outline-primary' onClick={changeColor}>
        <span>Click to change color</span>
      </div>
    </div>
  )
}

const domContainer = document.querySelector('#react_container')
const root = ReactDOM.createRoot(domContainer)
root.render(e(ReactFun))

here are the cdn links I am using now:

<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

PHP createdatabase if not exists is not working

While trying to create a database if not exists, I encountered the following errors, my code can be seen below. It is in two files, the createDatabase.php and the connectionDB.php.

it is showing me this error below:

Fatal error: Uncaught mysqli_sql_exception: Unknown database ‘dictionary’ in
C:xampphtdocsdictionaryconfigcreateDatabase.php:8 Stack trace: #0
C:xampphtdocsdictionaryconfigcreateDatabase.php(8): mysqli_select_db(Object(mysqli),
‘dictionary’) #1 C:xampphtdocsdictionaryconfigcreateDatabase.php(28): checkIfDatabaseExist()
#2 {main} thrown in C:xampphtdocsdictionaryconfigcreateDatabase.php on line 8

createDatabase.php

    function checkIfDatabaseExist(){
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dictionary";
        $conn = mysqli_connect($servername,$username,$password);
        if(!mysqli_select_db($conn,$dbname)){
            $createDatabase = "CREATE DATABASE IF NOT EXISTS $dbname";
            mysqli_query($conn,$createDatabase);
        }
        mysqli_close($conn);
    } 
    function checkIfTableExist(){
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dictionary";
        $conn = mysqli_connect($servername,$username,$password,$dbname);
        $checkTable = "SELECT 1 FROM dictionary_resource LIMIT 1";
        $result = mysqli_query($conn, $checkTable);
        if($result){
            echo "exist";
        }else {
            echo "noExist";
        }
    }
    checkIfDatabaseExist();
    checkIfTableExist();
?>```


 connectionDB.php

 ``<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "dictionary";
    $conn = mysqli_connect($servername,$username,$password,$dbname);
    if(!conn){
        die("Connection Failed: ".mysqli_connect_error());
    }
?>`

  



“An error occurred whilst communicating with the server” or “Error connecting to the server” Moodle 3.7

I am getting “An error occurred whilst communicating with the server” or “Error connecting to the server” on a Moodle 3.7 site when I try to upload audio or video files. May be becuase the error shows up in a pop up message no debug messages are displayed even though i enabled it in the settings. Strange thing is previously i was able to upload without such errors.

Action taken so far to relove the issue;
increasing following values in php.ini

memory_limit
upload_max_filesize 
post_max_size 
max_input_time 

increasing uploadReadAheadSize, appConcurrentRequestLimit in IIS

I can see the following error in network tab of the browsers inspector
repository/repository_ajax.php?action=upload [HTTP/1.1 413 Request Entity Too Large 448ms]
or
course/dndupload.php [HTTP/1.1 413 Request Entity Too Large 455ms]
I am only trying to upload an audio in 50M size. Uploading word or PDFs produce no errors. I’m trying to resolve this since yesterday. Any help is greatly appriciated!

calling inkscape cli from php with shell_exec, return different value than running directly from cmd

I need to get height of a text from SVG files (id : textmaster) with php.

When running inkscape with shell_exec, the return value is different than running it directly from cmd :

<?php
        $heightpx = shell_exec('inkscape --query-id="textmaster" --query-height drawing_edit.svg');
        echo $heightpx;
?>

the return value was :

74.5301

But when run directly from cmd :

inkscape --query-id="textmaster" --query-height drawing_edit.svg

the return value was :

128.778

the svg files :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   width="210mm"
   height="297mm"
   viewBox="0 0 210 297"
   version="1.1"
   id="svg5"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:svg="http://www.w3.org/2000/svg">
  <defs
     id="defs2" />
  <g
     id="layer1">
    <text
       xml:space="preserve"
       style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:25.4773px;line-height:1.25;font-family:Austria;-inkscape-font-specification:Austria;stroke-width:0.367463"
       x="20.467245"
       y="47.263172"
       id="textmaster"><tspan
         id="tspan7489"
         x="20.467245"
         y="47.263172"
         style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Austria;-inkscape-font-specification:Austria;stroke-width:0.367463">Hello World!</tspan></text>
  </g>
</svg>

The right value was when it run directly from cmd prompt.
How to make the shell_exec called from php return the same values?

embed pkcs7 in pdf with php

I am trying to implement digital signature in PDF with PHP.

Implementation steps are:

  • Ask user to upload PDF that needs to be signed
  • Validate user with their Unique identifier
  • API process data to generate DSC and responds with document signature digested value as Pkcs7 in xml format (Third party)
  • Embed pkcs7 in PDF (need help in this)

I have checked TCPDF library but it does not explain on how to attach Pkcs7 in PDF.

I am trying to find something like Java bouncycastle library for PHP.

save coords of my image in variable each clicks

I currently have an image where when I click on it I have the coordinates which are displayed on my php page however I would like to be able to store each time I click on it the coordinates in a variable and that the old coordinates are not erased when I click again on the image. I tried a for loop with array variable but I dont know how it really works

Image of my page, showing coords when I click on it, but not getting saved in variable
[1]: https://i.stack.imgur.com/kHMzy.png