I’m trying to create show transaction from Coinbase Api in php but I don’t get any response from Coinbase Api

I’m trying to create show transaction from Coinbase Api in php but I don’t get any response from the Coinbase api

<?php

function sendTransaction($private_key, $api_key , $transaction_id , $account_id){
    $json = new stdClass();
    $json->method = "GET";
    $json->path = "/v2/accounts/".$account_id."/transactions/".$transaction_id."";
    $json->secretapikey = $private_key;
    $json->apikey = $api_key;

    $body = new stdClass();
    $body->type = "read";
    $body->transaction_id = $transaction_id;

    $result = json_encode($json);
    $body = json_encode($body);
    $time= time();
    $sign = $time.$json->method.$json->path.$body;
    $hmac = hash_hmac("SHA256", $sign, $json->secretapikey);

    $header = array(
        "CB-ACCESS-KEY:".$api_key,
        "CB-ACCESS-SIGN:".$hmac,
        "CB-ACCESS-TIMESTAMP:".time(),
        "CB-VERSION:2019-11-15",
        "Content-Type:application/json"
    );

    $ch = curl_init($URL);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
};

//Creating URL For Sending Request
$account_id = 'a2ae96db-c4f6-5364-b4d3-dd142af658c9'; //Coinbase Account ID
$private_key = 'QyxtlM3nKpI9E6U6aZXpIN**'; //Coinbase Private Key
$api_key = '4d13sW2jCJ**'; //Coinbase API KEY
$transaction_id = '1313a82c-10fc-532e-bc75-90801f482d74'; //Transaction id

$url = "https://api.coinbase.com/v2/accounts/".$account_id."/transactions/".$transaction_id."";

$tranx_id = sendTransaction(
    $private_key,
    $api_key,
    $transaction_id,
    $account_id
);

print_r($tranx_id);
?>

Here is the documentation url
https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-transactions

documentation image

How to count number of days left using PHP [duplicate]

I’m trying to count the number of days left,
NOTE: Due date is available in database, but number of days left not stored in the database

$sql="SELECT count(id) AS total FROM clients WHERE round((((strtotime.due_date- 
   time())/24)/60)/60))<=30";
   $result=mysqli_query($con,$sql);
   $values=mysqli_fetch_assoc($result);
   $num_rows=$values['total'];
   echo $num_rows ;

how to access a network shared folder from php code

credential window of shared folder
without manually entering the credentials i want to access the shared folder from my php code

<?php
 $user = 'lol';
 $password = 'noob'

$upload_dir = "\\192.168.1.2\uploaded_files\";    //this only works if i manually enter username and password for the shared folder
$allowed_types = array('jpg', 'png', 'jpeg', 'gif');
 
// Define maxsize for files i.e 2MB
$maxsize = 2 * 1024 * 1024;

// Checks if user sent an empty form
if(!empty(array_filter($_FILES['uploadedFile']['name']))) {

    // Loop through each file in files[] array
    foreach ($_FILES['uploadedFile']['tmp_name'] as $key => $value) {
         
        $file_tmpname = $_FILES['uploadedFile']['tmp_name'][$key];
        $file_name = $_FILES['uploadedFile']['name'][$key];
        $file_size = $_FILES['uploadedFile']['size'][$key];
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);

        // Set upload file path
        $filepath = $upload_dir.$file_name;

?>

// this code is seems to work for some users but in my case it doesn’t

exec(‘net use “\192.168.1.2uploaded_files” /user:”‘.$user.'” “‘.$password.'” /persistent:no’);

How to generate Fedex tracking numbers using APIs?

I want to create a web service like getmoretracks.com tracktaco.com or ecomhutsy.com in these websites they find valid FedEx trackings by zip code, city, or state and also filter results by shipping status in-transit or delivered and shipping and delivery date ranges so I created FedEx developer account and API keys but not found any API like the given criteria can someone help me to reach how getmoretracks.com tracktaco.com or ecomhutsy.com these websites works or find trackings so I can also build software where I can search for trackings by date ranges and zip codes.

Thanks in advance.

MPDF not downloading PDF on cPanel but works fine when locally hosted (XAMPP)

Here is the generatepdf.php:

    <?php
include('db.php');
require_once 'vendor/autoload.php';
ob_start();

?>

<?php
$student_id = 0;

if (isset($_GET['id'])) {
    $student_id = $_GET['id'];
}

// var_dump($student_id);

$fetchUser = $conn->query("SELECT * from student where id = $student_id")->fetchAll(PDO::FETCH_ASSOC);
$subjects = $conn->query("SELECT * FROM subjects WHERE student_id = $student_id")->fetchAll(PDO::FETCH_ASSOC);

// 
// var_dump($fetchUser);

// Student Info

$name = $fetchUser[0]['name'];


$rollno = $fetchUser[0]['rollno'];

$image = $fetchUser[0]['image'];
$center = $fetchUser[0]['center'];
$division = $fetchUser[0]['division'];
$academic_year = $fetchUser[0]['academic_year'];

$class = $fetchUser[0]['class'];
$session = $fetchUser[0]['session1'] . ' - ' . $fetchUser[0]['session2'];
$father = $fetchUser[0]['father'];
$stream = $fetchUser[0]['stream'];
$totalmarks = $fetchUser[0]['totalmarks'];;
$obtmarks = $fetchUser[0]['obtmarks'];
$marksinwords = $fetchUser[0]['marksinwords'];

$percentage = ($fetchUser[0]['obtmarks'] / $fetchUser[0]['totalmarks']) * 100;
$percentage = number_format($percentage, 2);

$todaysDate = gmdate("M d, Y", strtotime('now'));


$html = '
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
}
p { margin: 0pt; }
table.items {
    border: 0.1mm solid #000000;
}
td { vertical-align: top; }
.items td {
    border-left: 0.1mm solid #000000;
    border-right: 0.1mm solid #000000;
}
table thead td { background-color: #EEEEEE;
    text-align: center;
    border: 0.1mm solid #000000;
    font-variant: small-caps;
}
.items td.blanktotal {
    background-color: #EEEEEE;
    border: 0.1mm solid #000000;
    background-color: #FFFFFF;
    border: 0mm none #000000;
    border-top: 0.1mm solid #000000;
    border-right: 0.1mm solid #000000;
}
.items td.totals {
    text-align: right;
    border: 0.1mm solid #000000;
}
.items td.cost {
    text-align: "." center;
}
</style>
</head>
<body>

<!--mpdf
<htmlpageheader name="myheader">
<table width="100%"><tr>
<td width="80%" style="color:#000; "><span style="font-weight: bold; font-size: 14pt;">Online Marksheet For TELEGANA UNIVERSITY</span></td>
// <td width="20%" style="text-align: right;">Date: ' . $todaysDate . '<br />
</tr></table>
</htmlpageheader>

<htmlpagefooter name="myfooter">
<div style="border-top: 1px solid #000000; font-size: 9pt; text-align: center; padding-top: 3mm; ">
Page {PAGENO} of {nb}
</div>
</htmlpagefooter>

<sethtmlpageheader name="myheader" value="on" show-this-page="1" />
<sethtmlpagefooter name="myfooter" value="on" />
mpdf-->
<img style="margin-top: -50px;padding: 15px; border: 2px solid #000; height: 100px;margin: auto !important;width: 100px;background-size: contain;background-repeat: no-repeat;background-position: center;margin-left: 80px !important;" src="images/' . $image . '" class="img-thumbnail">
<table width="100%" style="font-family: serif;" cellpadding="10"><tr>
<td width="55%"><br /><br /><span style="font-weight: bold;">Name:</span> ' . $name . '<br /><span style="font-weight: bold;">Father:</span> ' . $father . '<br /><span style="font-weight: bold;">Center:</span> ' . $center . '<br /><span style="font-weight: bold;">Division:</span> ' . $division . '<br /><span style="font-weight: bold;">Class:</span> ' . $class . '</td>
<td width="5%">&nbsp;</td>
<td width="40%"><br /><br /><span style="font-weight: bold;">Hall Ticket / Roll No:</span> ' . $rollno . '<br /><span style="font-weight: bold;">Session:</span> ' . $session . '<br /><span style="font-weight: bold;">Stream:</span> ' . $stream . '<br /><span style="font-weight: bold;">Year of Passing:</span> ' . $academic_year . '</td>
</tr></table>

<br />

<table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; " cellpadding="8">
<thead>
<tr>
<td width="15%">Sub Code</td>
<td width="40%">Subject Name</td>
<td width="10%">Theory</td>
<td width="15%">Practicals</td>
<td width="20%">Marks Secured</td>
</tr>
</thead>
<tbody>
<!-- ITEMS HERE -->
';

foreach ($subjects as $subject) {

    $html .= '<tr>';
    $html .= '<td align="center">' . $subject['subcode'] . '</td>';
    $html .= '<td align="center">' . $subject['subject_name'] . '</td>';
    $html .= '<td>' . $subject['total_marks'] . '</td>';
    $html .= '<td class="cost">' . $subject['obtained_marks'] . '</td>';
    $html .= '<td class="cost">' . $subject['marksinwords'] . '</td>';
    $html .= '</tr>';
}
$html .= '
<tr style="border-top: 2px solid #000;">
<td style="border-top: 2px solid #000;" align="center" >Percentage: ' . $percentage . '</td>
<td style="border-top: 2px solid #000;" align="center"></td>
<td style="border-top: 2px solid #000;">' . $totalmarks . '</td>
<td style="border-top: 2px solid #000;" class="cost">' . $obtmarks . '</td>
<td style="border-top: 2px solid #000;" class="cost">' . $marksinwords . '</td>
</tr>
</tbody>
</table>

</body>
</html>
';

require_once 'bootstrap.php';

$mpdf = new MpdfMpdf([
    'margin_left' => 10,
    'margin_right' => 10,
    'margin_top' => 30,
    'margin_bottom' => 25,
    'margin_header' => 10,
    'margin_footer' => 10
]);

$mpdf->SetTitle("Online Marksheet");
$mpdf->SetDisplayMode('fullpage');


$mpdf->WriteHTML($html);

$mpdf->Output();

This is working perfectly fine in XAMPP for me, and is downloading the PDF every time I load the page.

But when I hosted these exact same files on cPanel’s File Manager – it’s only showing me a blank page. No errors. What can I do?

I’ve checked the PHP versions of both my XAMPP (v8.0) and PHP(v7.3) but that doesn’t seem to be the issue (unless one of you think it is?)

Uploading Image form a file

I want to upload an image via an input field and then display it. How do I make it work.
In principle, I would simply like to upload a picture that serves as a profile picture, which is later saved in a database. But first it should be easy to upload so that it is displayed

function Speichern() {
    var Profilbild = document.getElementById('pb').value;
    var c = Profilbild + ".png"
    document.getElementById('Profilbild').src = c;
}
 <form action=""onsubmit="Speichern();return false">
     <label for="username">Nutzername:</label>
     <input id="username" id="username" type="text" placeholder="<?php
         echo $_SESSION['username']; 
     >">
     <label for="email">Email:</label>
     <input id="email" id="email" type="text" placeholder="<?php
         echo $_SESSION["email"];
     >">
     <label for="pw">Passwort:</label>
     <input id="pw" id="pw" type="password" placeholder="<?php
         echo $_SESSION["pw"];
     >">
     <label for="pb">Profilbild:</label>
     <input type="file" id="pb" name="pb" accept="image/*">
     <button type="submit" >Ändern/Speichern</button>
 </form>
```

why is i got error eventhough is is the same file type using laravel but in the validation?

public function upload(Request $request)
{

        date_default_timezone_set('Asia/Jakarta');
        $user = Auth::user();

        $validation = Validator::make($request->all(), [
            'file' => 'mimes:jpeg,bmp,png,svg,pdf',
        ]);



        if ($validation->validated()) {



            $file = $request->file('file');
            $input['filename'] = rand() . '.' . $file->getClientOriginalExtension();

            $destinationPath = 'assets/img_po';
            $destinationPathpdf = 'assets/pdf_po';

            $img = Image::make($file->getRealPath());
            $img->resize(400, 400, function ($constraint) {
                $constraint->aspectRatio();
            })->save($destinationPath . '/' . $input['filename']);




            return response()->json([
                'message'  => 'Upload Anda Tersimpan',
                'icon' => 'success',
                'name' => $input['filename'],
                'status' => '1',
            ]);
        } else {

            return response()->json([
                'message' => $validation->errors()->all(),
                'icon' => 'error',
                'status' => '0',
            ]);
        }
    }

<——- html form——–>

File PO :

        <input type="hidden" class="isi" id="filepo">
        <div id="gambar">
          <div onclick="$('#uploadpo').click();">
              <button class="btn btn-primary">
                <span class="tf-icons bx bx-upload"></span>&nbsp; Upload PO
              </button>
          </div>
          <input id="uploadpo" name="file" type="file" style="display:none;" multiple/>
        </div>

<————–the javascript————->

$(“#uploadpo”).on(“change”, function() {

$(‘.loading’).attr(‘style’,’display: block’);

var formData = new FormData();
formData.append(‘file’, $(‘#uploadpo’)[0].files[0]);

$.ajax({
url: “{{ route(‘po.upload’) }}”,
method:”GET”,
data: formData,
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
},
dataType:’JSON’,
contentType: false,
cache: false,
processData: false,

  success:function(data) {

    $('.loading').attr('style','display: none');

      if(data.status == '1'){

        $("#filepo").val(data.name);

        $('#gambar').html("<button class='btn btn-success'><span class='tf-icons bx bx-check'></span>&nbsp; PO Sudah Terupload</button>")

          swal({
              title: "Berhasil!",
              text: "Upload Berhasil!",
              icon: "success",
              buttons: false,
              timer: 2000,
          });

      } else {

          swal({
              title: "Gagal!",
              text: "Pastikan File yang Anda Upload Benar!",
              icon: "error",
              buttons: false,
              timer: 2000,
          });


      }
  }

});

});

<————-route————>

Route::get(‘/po/add’, [AppHttpControllersPOController::class, ‘add’])->name(‘po.add’);

Route::get(‘/po/upload’, [AppHttpControllersPOController::class, ‘upload’])->name(‘po.upload’);

Query SQL to variable error but echo is working

I would like why I’m unable to load a row result from mysql db

This code works and result the echo: 180(value stored in PT):

$sql = "SELECT * FROM `user` WHERE pt;";
$result = mysqli_query($conn, $sql);
if (!$result) exit("The query did not succeded");
else {
    while ($row = mysqli_fetch_array($result)) {
        echo $row['pt'];
    }
}

this code result in nothing:

$sql = "SELECT * FROM user WHERE pt=?"; // SQL with parameters
$stmt = $conn->prepare($sql); 
$stmt->bind_param("i", $pt);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$usert = $result->fetch_assoc(); // fetch the data   
echo $usert

testing SELECT * FROM user WHERE pt=? in phpmyadmin

1 errors were found during analysis.

Variable name was expected. (near “?” at position 38) SQL Command:
Copy Documentation

SELECT * FROM user WHERE en=? LIMIT 0.25

MySQL Messages : Documentation

#1064 – Do you have a syntax error in your SQL next to ‘? LIMIT 0.25’ on line 1

where did i go wrong and why?

Bind_param causes an internal server error (500) [duplicate]

I can’t seem to wrap my head around this, I can’t find where the issue lays.

My code works perfectly fine without the bind_param, however, with it, it keeps throwing out a 500 Error (Internal Server Error).

 $connect = new PDO('mysql:host=localhost;dbname=db', 'root', '');

        $data = array();

        $query = "SELECT * FROM `events` WHERE `user_id`=? ORDER BY `id`";

        $statement = $connect->prepare($query);

        $statement->bind_param('i', $user_id); // casts error. Without it it works perfectly.

        $user_id = $this->session->userdata('user_id'); // I've tested it and it works, it returns the correct id.

        $statement->execute();

        $result = $statement->fetchAll();

        foreach($result as $row)
        {
         $data[] = array(
          'id'   => $row["id"],
          'title'   => $row["title"],
          'start'   => $row["start_event"],
          'end'   => $row["end_event"]
         );
        }

        if ($_SERVER['REQUEST_METHOD'] == "GET") { echo json_encode($data); }

The issue shall be somewhere in the SQL, the other code works just fine.

Issues with Electronic Signature Scipt

I am trying to create a script to upload an electronic signature to the a customers record but keep getting ID not specified error message 🙁

This is what I have come up with so far.

Code

if (isset($_GET['id'])) {

    $stmt = $pdo->prepare('SELECT * FROM contacts WHERE id = ?');
    $stmt->execute([$_GET['id']]);
    $contact = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare('SELECT id,username FROM accounts');
    $stmt->execute();
    $all_account_info = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $folderPath = "upload/";
    $image_parts = explode(";base64,", $_POST['signature']);
    $image_type_aux = explode("image/", $image_parts[0]);

    $image_type = $image_type_aux[1];

    $image_base64 = base64_decode($image_parts[1]);

    $file = $folderPath . $name . "_" . uniqid() . '.' . $image_type;

    file_put_contents($file, $image_base64);

    if(isset($_POST['name']) == null || isset($_POST['signature_img'])){
        $msg    =   '';
    }else{
        $id = isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != 'auto' ? $_POST['id'] : auto;
        $stmt = $pdo->prepare('INSERT INTO skreading1 VALUES (?, ?, ?, ?)');
        $result = $stmt->execute([$id, $_GET['id'], $_POST['$name'], $_POST['$file']]);
        $msg    =   "Signature has been recorded.";

    }

    if (!$contact) {
        exit('Help');
    }
} else {
    exit('No ID specified!');
}

?>

Form

                        <form action="add-sig.php" method="post">
                            <h1>Signature Pad</h1>
                            <div class="col-md-12">
                                <label class="form-label" for="name">Name</label> <input class="form-control" id="name" name="name" required="" type="text">
                            </div>
                            <div class="col-md-12">
                                <label class="" for="">Signature:</label><br>
                                <div id="sig"></div><br>
                                <textarea id="signature64" name="signature" style="display: none"></textarea>
                                <div class="col-12">
                                    <button class="btn btn-sm btn-warning" id="clear">&#x232B;Clear Signature</button>
                                </div>
                            </div><br>
                            <button class="btn btn-success" name="submit" type="submit">Submit</button>
                        </form>
                    </div>

Database

  `id` int(11) NOT NULL,
  `client_id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `signature_img` varchar(255) NOT NULL

It loads the ID when clicking add signature and the address link looks something like .php?id=29 from the clients record.

When I am in the clients record, I would like to be able to view the signature on their record.

The form converts the signature into an image file.

HTML to PDF: content overlapping from row table

i want to export PDF from php and using HTML2PDF but the content from is overlapping like picture below
picture

i already use

.tdbreak {
  word-break: break-all

but still overlapping. and below is the code i use. any idea would be so great. thank you

<?php
session_start();
ob_start();

// Panggil koneksi database.php untuk koneksi database
require_once "../../config/database.php";
// panggil fungsi untuk format tanggal
include "../../config/fungsi_tanggal.php";

$hari_ini = date("d-m-Y");

// ambil data hasil submit dari form
$tgl1     = $_GET['tgl_awal'];
$explode  = explode('-',$tgl1);
$tgl_awal = $explode[2]."-".$explode[1]."-".$explode[0];

$tgl2      = $_GET['tgl_akhir'];
$explode   = explode('-',$tgl2);
$tgl_akhir = $explode[2]."-".$explode[1]."-".$explode[0];

if (isset($_GET['tgl_awal'])) {
    $no    = 1;
    // fungsi query untuk menampilkan data dari tabel barang keluar
    $query = mysqli_query($mysqli, "SELECT a.id_barang_keluar,a.tanggal_keluar,a.id_barang,a.jumlah_keluar,a.ket_keluar,b.id_barang,b.nama_barang,b.id_satuan,c.id_satuan,c.nama_satuan
                                    FROM is_barang_keluar as a INNER JOIN is_barang as b INNER JOIN is_satuan as c
                                    ON a.id_barang=b.id_barang AND b.id_satuan=c.id_satuan
                                    WHERE a.tanggal_keluar BETWEEN '$tgl_awal' AND '$tgl_akhir'
                                    ORDER BY a.id_barang_keluar ASC") 
                                    or die('Ada kesalahan pada query tampil Transaksi : '.mysqli_error($mysqli));
    $count  = mysqli_num_rows($query);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml"> <!-- Bagian halaman HTML yang akan konvert -->
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>LAPORAN DATA BARANG KELUAR</title>
        <style>
            table {
  width: 140px;
  border: 1px solid #bbb
}

.tdbreak {
  word-break: break-all
}

        </style>
        

    </head>
    <body>
        <div id="title">
            LAPORAN DATA BARANG KELUAR 
        </div>
    <?php  
    if ($tgl_awal==$tgl_akhir) { ?>
        <div id="title-tanggal">
            Tanggal <?php echo tgl_eng_to_ind($tgl1); ?>
        </div>
    <?php
    } else { ?>
        <div>
            Tanggal <?php echo tgl_eng_to_ind($tgl1); ?> s.d. <?php echo tgl_eng_to_ind($tgl2); ?>
        </div>
    <?php
    }
    ?>
        
        <hr><br>
        <div>
            <table border="0.3" cellpadding="0" cellspacing="0">
                <thead style="background:#e8ecee">
                    <tr>
                        
                        <th>KET.KELUAR</th>   
                    </tr>
                </thead>
                <tbody>
<?php
    // jika data ada
    if($count == 0) {
        echo "  <tr>
                    
                    <td></td>
                </tr>";
    }
    // jika data tidak ada
    else {
        // tampilkan data
        while ($data = mysqli_fetch_assoc($query)) {
            $tanggal       = $data['tanggal_keluar'];
            $exp           = explode('-',$tanggal);
            $tanggal_keluar = tgl_eng_to_ind($exp[2]."-".$exp[1]."-".$exp[0]);

            // menampilkan isi tabel dari database ke tabel di aplikasi
            echo "  <tr>
                        
            <td class='tdbreak'>$data[ket_keluar]</td>
                    </tr>";
            $no++;
        }
    }
?>  
                </tbody>
            </table>

            <div id="footer-tanggal">
                Jakarta, <?php echo tgl_eng_to_ind("$hari_ini"); ?>
            </div>
            <div id="footer-jabatan">
                TTD
            </div>
            
            <div id="footer-nama">
                Andika.
            </div>
        </div>
    </body>
</html><!-- Akhir halaman HTML yang akan di konvert -->
<?php
$filename="LAPORAN DATA BARANG KELUAR.pdf"; //ubah untuk menentukan nama file pdf yang dihasilkan nantinya
//==========================================================================================================
$content = ob_get_clean();
$content = '<page style="font-family: freeserif">'.($content).'</page>';
// panggil library html2pdf
require_once('../../assets/plugins/html2pdf_v4.03/html2pdf.class.php');
try
{
    $html2pdf = new HTML2PDF('P','F4','en', false, 'ISO-8859-15',array(10, 10, 10, 10));
    $html2pdf->setDefaultFont('Arial');
    $html2pdf->writeHTML($content, isset($_GET['vuehtml']));
    $html2pdf->Output($filename);
}
catch(HTML2PDF_exception $e) { echo $e; }
?>

Prevent ~Sign in with google~ to automatically sign in on page

I have a problem from a few days on my site on -Sign in with google-. It automatically signs in when access the page. This wasn’t happened before, and i didn’t change anything on code. I don’t see where could be the problem…
Here is the code from my pages.
Google sign in button:

 <div id="my-signin2" class="googleSignIn" style="align:center"></div>

Script:

<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
<script>
function onLoad() {
    gapi.load('auth2', function() {
        gapi.auth2.init();
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 240,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': loginSuccess,
        });
    });

}


function loginSuccess(userInfo) {
    var data = userInfo.getBasicProfile();

    //ajax call update data in database
    $.ajax({
        type: "POST",
        url: "update_data.php",
        data: {
            'id': data.getId(),
            'name': data.getName(),
            'image': data.getImageUrl(),
            'email': data.getEmail(),
        },
        success: function(result) {
            window.location.href = "page to redirect";
        }
    });
}


</script>

update_data.php:

    session_start();
include_once 'config.php';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$user_id =  $_POST['id'];
$name = $_POST['name'];
$image =  $_POST['image'];
$email =  $_POST['email'];



$sql = "SELECT * FROM utilizatori WHERE email_utilizator = :email";
$query = $dbh->prepare($sql);

$query->bindParam(':email',$email,PDO::PARAM_STR);

$query->execute();

$results=$query->fetchAll(PDO::FETCH_ASSOC);
if($query->rowCount() > 0)
{
    foreach($results as $result)
    {
    $_SESSION['USER_NAME']= $name;
    $_SESSION['USER_EMAIL']= $result['email_utilizator'];
    $_SESSION['USER_ID']= $result['id_utilizator'];
    $_SESSION['USER_IMAGE']= $image;
    $_SESSION['USER_TYPE']= $result['tip_utilizator'];
}}
else
    echo 'Nu exista utilizatorul';
    

logout.php

    <?php
session_start();
include('config.php');

session_destroy();

echo "<script type='text/javascript'> document.location ='index.php'; </script>";

?>
<script>
 function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
  </script>

Calculate Total Price with Symfony

I have the following problem with shopping cart. I don’t know where to place the calculation, so it can update total price dynamically (Such when the cart item is removed, or the quantity updated). Because I need to call updateTotalPrice() method almost everywhere, but I don’t want to repeat the code that many times

So far it look like this
enter image description here

CartService

class CartService extends AbstractController
{

    private CartRepository     $cartRepository;
    private ManagerRegistry    $managerRegistry;
    private CartItemRepository $cartItemRepository;

    public function __construct(CartItemRepository $cartItemRepository, CartRepository $cartRepository, ManagerRegistry $managerRegistry)
    {
        $this->cartItemRepository = $cartItemRepository;
        $this->cartRepository = $cartRepository;
        $this->managerRegistry = $managerRegistry;
    }

    /**
     * Get Cart by ID
     *
     * @return Cart|null
     */
    public function getCartByUserId(): ?Cart
    {
        /**
         * @var User $user
         */
        $user = $this->getUser();

        return $this->cartRepository->findOneBy(['customer' => $user->getId()]);

    }

    /**
     * Create Cart for Customer
     *
     * @return Cart|null
     */
    public function createNewCart(): ?Cart
    {
        $entityManager = $this->managerRegistry->getManager();
        $cart = new Cart();
        /**
         * @var User $user
         */
        $cart->setCustomer($this->getUser());
        $entityManager->persist($cart);
        $entityManager->flush();

        return $cart;
    }

    /**
     * @param Cart $cart
     * @param Product $product
     * @return CartItem|null
     */
    public function isProductInCart(Cart $cart, Product $product): ?CartItem
    {
        return $this->cartItemRepository->findOneBy(['product' => $product->getId(), 'cart' => $cart->getId()]);
    }

    /**
     * Add new product to cart
     *
     * @param Cart $cart
     * @param Product $product
     * @param int $quantity
     * @return void
     */
    public function insertProduct(Cart $cart, Product $product, int $quantity): void
    {
        $entityManager = $this->managerRegistry->getManager();

        $insertProduct = new CartItem();
        $insertProduct->setCart($cart)
                      ->setCart($cart)
                      ->setQuantity($quantity)
                      ->setProduct($product);
        $cart->addCartItem($insertProduct);
        $cart->setTotalprice($cart->getTotalprice() + $insertProduct->getQuantity() * $insertProduct->getProduct()->getPrice());
        $entityManager->persist($insertProduct);
        $entityManager->flush();
    }

    /**
     * Update item's quantity
     *
     * @param CartItem $cartItem
     * @param int $quantity
     * @return void
     */
    public function updateCartItemQuantity(CartItem $cartItem, int $quantity): void
    {
        $entityManager = $this->managerRegistry->getManager();
        $cartItem->setQuantity($quantity);
        $entityManager->persist($cartItem);
        $entityManager->flush();
    }

    /**
     * Remove specific product from cart
     *
     * @param int $id
     * @return void
     */
    public function removeProductFromCart(int $id): void
    {
        $product = $this->cartItemRepository->findOneBy(['product' => $id]);
        $entityManager = $this->managerRegistry->getManager();
        $entityManager->remove($product);
        $entityManager->flush();
    }

    /**
     * Set or update total price
     *
     * @param Cart $cart
     * @param float $totalprice
     * @return void
     */
    public function updateTotalPrice(Cart $cart, float $totalprice): void
    {
        $entityManager = $this->managerRegistry->getManager();
        $cart->setTotalprice($cart->getTotalprice() + $totalprice);
        $entityManager->persist($cart);
        $entityManager->flush($cart);
    }

    /**
     * Add Product to Cart
     *
     * @param Product $product
     * @param $cartItem
     * @return void
     */
    public function addOrUpdateProduct(Product $product, $cartItem): void
    {
        $cart = $this->getCartByUserId();

        if (!$cart instanceof Cart) {
            $cart = $this->createNewCart();
        }

        $isProductInCart = $this->isProductInCart($cart, $product);

        //If product doens't exist, insert it inside cart. If exist, update quantity and add message
        if (!$isProductInCart) {
            $this->insertProduct($cart, $product, $cartItem->getQuantity());
            $this->addFlash('productAdded', 'Product added to Cart');
        } else {
            $this->updateCartItemQuantity($isProductInCart, $cartItem->getQuantity() + $isProductInCart->getQuantity());
            $this->updateTotalPrice($cart, $cartItem->getQuantity() * $cartItem->getProduct()->getPrice());
            $this->addFlash('productAdded', 'Product already in cart. Quantity Updated');
        }
    }

OrderController (That’s the cart)

<?php

namespace AppController;

/**
 * @IsGranted("IS_AUTHENTICATED_FULLY")
 */
#[Route('/cart', name: 'cart.')]
class OrderController extends AbstractController
{

    /**
     * Show current Cart
     *
     * @param CartService $cartService
     * @return Response
     */
    #[Route('/', name: 'show_cart')]
    public function showCart(CartService $cartService): Response
    {
        $cart = $cartService->getCartByUserId();

        return $this->render('cart/index.html.twig', [
            'cart' => $cart,
        ]);
    }

    /**
     * Update existing cart item quantity
     *
     * @param CartItem $cartItem
     * @param int $quantity
     * @param CartService $cartService
     * @return Response
     */
    #[Route('/updatecartquantity/{id}/{quantity}', name: 'updatequantity')]
    public function updateCartQuantity(CartItem $cartItem, int $quantity, CartService $cartService): Response
    {
        $cartService->updateCartItemQuantity($cartItem, $quantity);

        return $this->redirect($this->generateUrl('cart.show_cart'));
    }

    /**
     * Remove product from cart
     *
     * @param CartService $cartService
     * @param int $id
     * @return Response
     */
    #[Route('/removeitem/{id}', name: 'removefromcart')]
    public function removeFromCart(CartService $cartService, int $id): Response
    {
        $cartService->removeProductFromCart($id);
        return $this->redirect($this->generateUrl('cart.show_cart'));
    }

}

Product Controller (Shows the product -> After choosing quantity can be inserted inside cart

#[Route('/product', name: 'product.')]
class ProductController extends AbstractController
{

    /**
     * Show Product, and add to cart
     *
     * @param Product $product
     * @param CartService $cartService
     * @param Request $request
     * @return Response
     */
    #[Route('/showproduct/{id}', name: 'showproduct')]
    public function showProduct(Product $product, CartService $cartService, Request $request): Response
    {
        $form = $this->createForm(CartItemType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $item = $form->getData();
            $item->setProduct($product);

            $cartService->addOrUpdateProduct($product, $item);
        }

        return $this->render('product/showproduct.html.twig', [
            'product' => $product,
            'form' => $form->createView()
        ]);
    }
}