I get error 40532 when I try to connect to Azure SQL

I am trying to connect to my azure sql database with the script below.
But I get the message error code = 40532
I have added my IP address to my firewall.
I can log in via portal.azure.com and open the Play SQL database.

What am I doing wrong?

<?php
    // Variables to tune the retry logic.
    $connectionTimeoutSeconds = 30;  // Default of 15 seconds is too short over the Internet, sometimes.
    $maxCountTriesConnectAndQuery = 3;  // You can adjust the various retry count values.
    $secondsBetweenRetries = 4;  // Simple retry strategy.
    $errNo = 0;
    $serverName = "sql-xxxx-xxxx-xxxxx.database.windows.net";
    $connectionOptions = array("Database"=>"AdventureWorks",
       "Uid"=>"[email protected]", "PWD"=>"itssecret", "LoginTimeout" => $connectionTimeoutSeconds);
    $conn = null;
    $arrayOfTransientErrors = array('08001', '08002', '08003', '08004', '08007', '08S01');
    for ($cc = 1; $cc <= $maxCountTriesConnectAndQuery; $cc++) {
        // [A.2] Connect, which proceeds to issue a query command.
        $conn = sqlsrv_connect($serverName, $connectionOptions);
        if ($conn === true) {
            echo "Connection was established";
            echo "<br>";

            $tsql = "SELECT Name FROM Production.ProductCategory";
            $stmt = sqlsrv_query($conn, $tsql);
            if ($stmt === false) {
                echo "Error in query execution";
                echo "<br>";
                die(print_r(sqlsrv_errors(), true));
            }
            while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                echo $row['Name'] . "<br/>" ;
            }
            sqlsrv_free_stmt($stmt);
            sqlsrv_close( $conn);
            break;
        } else {
            // [A.4] Check whether the error code is on the list of allowed transients.
            $isTransientError = false;
            $errorCode = '';
            if (($errors = sqlsrv_errors()) != null) {
                foreach ($errors as $error) {
                    $errorCode = $error['code'];
                    $isTransientError = in_array($errorCode, $arrayOfTransientErrors);
                    if ($isTransientError) {
                        break;
                    }
                }
            }
            if (!$isTransientError) {
                // it is a static persistent error...
                echo("Persistent error suffered with error code = $errorCode. Program will terminate.");
                echo "<br>";
                // [A.5] Either the connection attempt or the query command attempt suffered a persistent error condition.
                // Break the loop, let the hopeless program end.
                exit(0);
            }
            // [A.6] It is a transient error from an attempt to issue a query command.
            // So let this method reloop and try again. However, we recommend that the new query
            // attempt should start at the beginning and establish a new connection.
            if ($cc >= $maxCountTriesConnectAndQuery) {
                echo "Transient errors suffered in too many retries - $cc. Program will terminate.";
                echo "<br>";
                exit(0);
            }
            echo("Transient error encountered with error code = $errorCode. Program might retry by itself.");
            echo "<br>";
            echo "$cc attempts so far. Might retry.";
            echo "<br>";
            // A very simple retry strategy, a brief pause before looping.
            sleep(1*$secondsBetweenRetries);
        }
        // [A.3] All has gone well, so let the program end.
    }
?>

I m not sure what ive tried but nothings is working. I think it has to do with rights or something. But I can’t figure it out.

nginx conf on docker same for xampp

I’m following a youtube tutorial on how to setup docker with PHP. I came across this code for nginx configuration.

server {
    listen 80;
    server_name localhost;
    root /app/public;
    index index.php;

    location ~ .php$ {
       fastcgi_pass   app:9000;
       fastcgi_index  index.php;
       fastcgi_param REQUEST_METHOD $request_method;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
}

I’m wondering how can I setup this configuration to work the same way with xampp.

For example now. if I go to localhost/un-known-text it redirects back to index.php which is not the default behaviour of xampp.

Any help would be appreciated.

Database Migration Failed in laravel

Schema::create(‘jobs’, function (Blueprint $table) {
$table->id();

        $table->string('title');
        $table->text('description');
        $table->unsignedInteger('salary');
        $table->string('location');
        $table->string('category');
        $table->enum('experience', ['entry', 'intermediate', 'senior']);
        $table->timestamps();
    });

I’ve tried to seed the database with a factory using php artisan migrate:refresh –seed but i get this error:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘jobs’ already exists (Connection: mysql, SQL: create table jobs (id bigint unsigned not null auto_increment primary key, title varchar(255) not null, description text not null, salary int unsigned not null, location varchar(255) not null, category varchar(255) not null, experience enum(‘entry’, ‘intermediate’, ‘senior’) not null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate ‘utf8mb4_unicode_ci’)

cant send confirmation to reboot ont zte

$expect_script = <<<EOD
#!/usr/bin/expect -f
exp_internal 1
log_user 1  ;# Enable logging of user interaction
set timeout 20

# Start Telnet session
spawn telnet $telnet_host

# Handle initial banners or messages
expect {
    "User Access Verification" { exp_continue }
    "Username:" { send "$telnet_usernamer" }
}

# Expect password prompt and send password
expect "Password:"
send "$telnet_passwordr"

# Expect the command prompt after successful login
expect "#"

# Send each command from the array except 'reboot'
foreach command [split "$command_interface" "n"] {
    if { [string match "*reboot*" "$command"] } {
        # If the command is 'reboot', handle it separately
        send "$commandr"
        expect {
            "Confirm to reboot.*" {
                send "yesr"
                expect "#"
            }
            timeout { puts "Timed out waiting for reboot confirmation prompt."; exit 2 }
        }
    } else {
        # For all other commands
        send "$commandr"
        expect {
            "#" { 
                set output $expect_out(buffer)
            }
            timeout {
                puts "Timed out waiting for command prompt."
                exit 1
            }
        }
    }
}

# Send exit command to close the Telnet session
send "exitr"

# Wait for session to end
expect eof

# Output the entire buffer captured
puts "$output"
EOD;

$commands = [
        "config t",
        "pon-onu",
        "pon-onu-mng gpon-onu_1/14/8:45",
        "reboot"
           ];

this shoud be running like this ,sampling from terminal

OL01-NGN-SMG-ERLGOD#config t
%Info 20272: Enter configuration commands, one per line. End with CTRL/Z.
OL01-NGN-SMG-ERLGOD(config)#pon-onu-mng gpon-onu_1/14/8:45
OL01-NGN-SMG-ERLGOD(gpon-onu-mng 1/14/8:45)#reboot
Confirm to reboot? [yes/no]:yes

but somehow the confrimation yes can not be put and resulted

Username: 
ossapp01
Password: 
OL01-NGN-SMG-ERLGOD#config t
%Info 20272: Enter configuration commands, one per line. End with CTRL/Z.
OL01-NGN-SMG-ERLGOD(config)#pon-onu
%Error 20203: Incomplete command.
OL01-NGN-SMG-ERLGOD(config)#pon-onu-mng gpon-onu_1/14/8:45
OL01-NGN-SMG-ERLGOD(gpon-onu-mng 1/14/8:45)#reboot
Confirm to reboot? [yes/no]:Timed out waiting for reboot confirmation prompt.

help me modify the expect script to achieve this, thankyou in advance

Ajax Request Returns Html Response

I have come across this question before but I haven’t found a helpful answer whatsoever. What I want to know is why an ajax call to a codeigniter controller is returning an HTML response even when the controller function is not returning nothing explicitly.

So I have the following jquery ajax code:


$('#lgaStateField').change(function(){
var state = $(this).val();
            
if(state != 0){
    $('#lgaField').attr('disabled', false);
    $(processOngoing).css('display', 'block');

    $.ajax({
    url: "<?=base_url('adverts-report/fetch-lgas')?>",
    type: 'post',
    data: {stateId : state},
    success: function(r){
            //console.log(r);return false;
       // const resLgas = JSON.parse(r);
      // $('#lgaField').empty().append('<option value="0">Select Lga</option>');

     // for(var i = 0; i < resLgas.length; i++){
        $('#lgaField').append('<option value="' + resLgas[i].id + '">' + resLgas[i].name + '</option>');
    // }

    $(processOngoing).css('display','none');
    },
    error: function(err){
            console.log(err);
        $(processOngoing).css('display','none');
    }
      })
    }
})

And the following is a snippet of the endpoint that supposed to return a response but is currently empty:

public function fetch_lgas(){
        
    }

Yet when i check the Network section of my developer tab, there is an html response that is more or less the content of the current view.

livesmart server video php file not working on local

  • I have windows 10. I am using Laragon having Apache, php, mysql etc. I have Node js, npm, maria DB etc installed as well.

  • I am trying to setup “livesmart server video” from https://codecanyon.net/item/livesmart-allin-one-bundle/48456060 on my local.

  • I hit this https://localhost/livesmart_server_video/public/install/, filled relevant information. As per success message, I executed bash script and also updated conf file of virtual host.

  • http://localhost:9002/ location worked fine, but when I click on “start new meeting” then http://localhost:9002/server/script.php gives 404 error so pages with Node.js working fine, but it is not routing PHP requests through Apache

  • If I directly replace server/script.php with https://localhost/livesmart_server_video/public/server/script.php in publicjsbundle.js, publicdashfooter.php then URL works but in response, I get error “Response body is not available to scripts (Reason: CORS Missing Allow Origin)”

  • Can you please suggest what could be a solution? How Apache and Node.js work simultaneously? Apache for PHP files and Node.js for JS files

Installing Wikimedia on mac

Please be patient with me, as I dont understand the “tech language” and my knowledge on tech and programming is on a minimum. Yesterday was actually the first time I used Terminal on my mac.

What do I want?
I would like to download wikimedia, so that I can create wikipages for my fictional world.

What have I done?
I followed this guide:
https://ipv6.rs/tutorial/macOS/Mediawiki/

  1. I installed the Apache
  2. I installed the Php
  3. I installed Mysql
  4. I downloaded the MediaWiki
  5. I changed the name of the mediawiki map to “mediawiki”
  6. I draged the mediawiki-map to “/Library/WebServer/Documents/”

What is my problem?
When I go to “http://localhost/mediawiki/” (which the guide tells me to do), I get the following:
“Forbidden
You don’t have permission to access this resource.”

Good to know
When I enter my local ip-adress, I get this:
“It works!”

I hope somebody can help me understand this, and I’m sorry once again for my low level of understanding here

Re arrange multidimentional array

I have an multi dimensional array i am trying to group the array based on the duplicate value.

So, I’m trying to group them by key but i am not getting to group the array based on the key values.

Below is the original array

[
        {
            "league_id": 2,
            "league_name": "BBBB",
            "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
            "order_number": 1,
            "member_username": "A"
        },
        {
            "league_id": 2,
            "league_name": "BBBB",
            "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
            "order_number": 2,
            "member_username": "B"
        },
        {
            "league_id": 1,
            "league_name": "AAAA",
            "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1724177635.png",
            "order_number": 1,
            "member_username": "C"
        },
        {
            "league_id": 1,
            "league_name": "AAAA",
            "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1724177635.png",
            "order_number": 2,
            "member_username": "D"
        },
    ]

I want to rearrange this array as output array below:

[
    {
        "league_id": 2,
        "league_name": "BBBB",
        "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
        "users": [{
            "order_number": 1,
            "member_username": "A"
        }, {
            "order_number": 2,
            "member_username": "B"
        }]
    },
    {
        "league_id": 1,
        "league_name": "AAAA",
        "league_image": "https://d2ayu7u0r0spqb.cloudfront.net/dev/league-images/1722361078.png",
        "users": [{
            "order_number": 1,
            "member_username": "C"
        }, {
            "order_number": 2,
            "member_username": "D"
        }]
    }
]

Any idea? How to do this.

Thanks

Check for a specific relation in Laravel Many-To.Many relationship

I have an application with a User model and a Group model as well as a Many-To-Many relationship defined between both models.

I now would like to check if a user is member of a specific group.

I know that this works

$u = User::find(1);
$g = $u->groups->where('name', 'Administrators')->get();

Then I have the group in $g if the user belongs to it. But I am not interested in the group, I just would like to know if the user belongs to it. Of course, I could work with it, but is seems not to be the best solution. Another approach would be the following:

$u = User::find(1);
$g = $u->groups->where('name', 'Administrators')->count();

This seems a little bit more elegant to me. $g == 0 if the user is not a member, $g == 1 if the user is. But my feeling is that Laravel offers a better solution… There are so many shortcuts in Laravel. I’d be surpried if there wasn’t another method tailored for this specific need. But which? (There are so many cases, where there is a belongsTo, has, in or similar method, which would be also useful here.)

I already checked the following links in the Laravel documentation, but they do not mention this use case. Is it so special? Or am I just looking in a completely wrong direction?

https://laravel.com/docs/10.x/eloquent-relationships#querying-relationship-existence

and

https://laravel.com/docs/10.x/eloquent-relationships#many-to-many

Why does my CSRF token validation fail when deleting multiple entries in PHP?

I’m encountering an issue with CSRF token validation in my PHP application. Specifically, when I try to delete multiple entries using the same CSRF token, I receive a “CSRF attack detected” error message. I believe this issue is related to the CSRF token being used multiple times within the same session without being regenerated.

  <?php
session_start();

// Generate a new CSRF token if one doesn't exist
if (!isset($_SESSION['auth_token'])) {
    $_SESSION['auth_token'] = bin2hex(random_bytes(20));
}

// Handle delete request
if (isset($_POST["delete_entry"])) {
    // Validate CSRF token
    if (!isset($_POST['auth_token']) || !isset($_SESSION['auth_token']) || $_SESSION['auth_token'] !== $_POST['auth_token'] || !isset($_POST['target_id'])) {
        // If the CSRF token is invalid or missing
        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-bug"></i>
                CSRF attack detected. Please reload the page and try again.<button type="button" class="btn-close"
                data-bs-dismiss="alert" aria-label="Close"></button>
              </div>';
        
        // Regenerate CSRF token to prevent any further attempts with the same token
        $_SESSION['auth_token'] = bin2hex(random_bytes(20));
        exit();
    } else {
        // Proceed with delete operation if the CSRF token is valid
        $target_id = htmlspecialchars(strip_tags($antiXss->xss_clean($_POST['target_id'])));
        $stmt = $con->prepare("SELECT * FROM jentress_erp WHERE jnum = ? and company=?");
        $stmt->bind_param("ss", $target_id, $_SESSION["company"]);

        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $_id = $row["id"];
                $_path = $row["position"]; 
                
                $stmt1 = $con->prepare("SELECT * FROM entress_erp_part2 WHERE contact_id = ?");
                if ($stmt1 === false) {
                    die('Prepare failed: ' . htmlspecialchars($con->error));
                }
                $stmt1->bind_param("i", $_id);
                $stmt1->execute();
                $result = $stmt1->get_result();
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $_account = htmlspecialchars($antiXss->xss_clean($row['s_account']), ENT_QUOTES, 'UTF-8');
                        $_acc_serial_token = htmlspecialchars($antiXss->xss_clean($row['acc_serial_token']), ENT_QUOTES, 'UTF-8');
                        $_debtor = htmlspecialchars($antiXss->xss_clean($row['s_debtor']), ENT_QUOTES, 'UTF-8');
                        $_creditor = htmlspecialchars($antiXss->xss_clean($row['s_creditor']), ENT_QUOTES, 'UTF-8');

                        $stmtu = $con->prepare("SELECT * FROM categories WHERE acc_serial =? AND acc_name=? AND company=?");
                        $stmtu->bind_param("sss", $_acc_serial_token, $_account, $_SESSION["company"]);
                        $stmtu->execute();
                        $resultu = $stmtu->get_result();
                        if ($resultu->num_rows > 0) {
                            $rowu = $resultu->fetch_assoc();
                            $balance = $rowu['ac_balanced'];
                            $new_balance = $balance - $_debtor + $_creditor;

                            $stmtu2 = $con->prepare("UPDATE categories SET ac_balanced=? WHERE acc_serial=? AND acc_name=? AND company=?");
                            $stmtu2->bind_param('ssss', $new_balance, $_acc_serial_token, $_account, $_SESSION["company"]);

                            if ($stmtu2->execute()) {
                                $stmt5 = $con->prepare("DELETE FROM jentress_erp WHERE id = ? AND company=?");
                                $stmt5->bind_param("is", $_id, $_SESSION["company"]);
                                if ($stmt5->execute()) {
                                    if (isset($_path) && file_exists($_path)) {
                                        unlink($_path);
                                    }
                                    echo '<script>$(document).ready(function(){toastr.success("Entry successfully deleted");}) </script>';
                                } else {
                                    echo '<script>$(document).ready(function(){toastr.error("Error occurred while deleting the entry");}) </script>';
                                }
                            } else {
                                echo '<script>$(document).ready(function(){toastr.error("Error occurred while updating the balance");}) </script>';
                            }
                        } else {
                            echo '<script>$(document).ready(function(){toastr.error("No data found");}) </script>';
                        }
                    }
                } else {
                    echo '<script>$(document).ready(function(){toastr.error("Entry number error");}) </script>';
                }
            }
        } else {
            echo '<script>$(document).ready(function(){toastr.error("No data found for this number");}) </script>';
        }

        // After successful deletion, generate a new token
        $_SESSION['auth_token'] = bin2hex(random_bytes(20));
    }
}
?>

When trying to delete multiple entries in a single request or making successive delete requests within the same session, the CSRF token validation fails. The error message indicates a potential CSRF attack. This suggests that the CSRF token is being reused or is not being updated properly, causing subsequent requests to fail the CSRF check.
**What I Need Help With:
**
. Understanding why the CSRF token validation is failing when attempting to delete multiple entries.
. Suggestions on how to properly handle CSRF tokens in such scenarios to ensure that multiple deletions can be performed in a single session without issues.
. Best practices for CSRF token management in PHP applications to avoid similar issues.
Thank you!

<!-- Modal -->
                <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" 
                 data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header bg-info">
                        <h1 class="modal-title fs-5" id="staticBackdropLabel">Are you sure to delete the entry?</h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body">
                      <form method="POST" action="">
                        <div class="mb-3">
                        <input type="hidden" name="auth_token" value="<?php echo htmlspecialchars(strip_tags($antiXss->xss_clean($_SESSION['auth_token']))); ?>" required>
                          <input type="hidden" name="target_id" class="form-control" id="recipient-name">
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="submit" name="delete_entry" class="btn btn-danger"><i class="fa-solid fa-trash"></i> delete </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fa-solid fa-ban"></i> cancel</button>
                      </div>
                    </div>
                    </form>
                  </div>
                </div>

IAB TCF integration in wordpress cookie consent plugin not working

I am creating a wordpress plugin for GDPR Cookie consent. I am trying to integrate IAB TCF in my plugin. I have already created a banner for displaying on the website. I am getting vendor and purpose list using GVL, i am then taking consent from user and generating the TC STring. Now I wanted tt overify it on a validator. I installed cmp validator 2.2 chrom extension. Now the extension is getting details about cmp, i.e the cmp is getting initialized but even on giving consent, i am not able to see consents in the validator console.

This is the code for banner on front-end-

import { CmpApi } from "@iabtechlabtcf/cmpapi";
import { TCModel, TCString, GVL } from "@iabtechlabtcf/core";
import * as cmpstub from "@iabtechlabtcf/stub";
const cmpId = 1000;
const cmpVersion = 1500;

cmpstub();

GVL.baseUrl = "https://923b74fe37.nxcli.io/rgh/";


const gvl = new GVL();
console.log("GVL", gvl);

window.__tcfapi = function (command, version, callback, parameter = "") {
  console.log(
    `__tcfapi called with command: ${command}, version: ${version}, parameter: ${parameter}`
  );
  if (command === undefined) {
    console.trace("Undefined command triggered here");
  }

  if (command === "getTCData" && version === 2) {
    getTCData(callback, parameter);
  } else {
    callback({}, false); // Default response for unsupported commands
  }
};

window.__tcfapi.queue = window.__tcfapi.queue || [];
window.__tcfapi.loaded = true;

const tcModel = new TCModel(gvl);
var encodedString = "default tc string...";

function getTCData(callback, parameter) {
  console.log("getTCData function called");

  const sampleTCData = {
    tcString: tcModel.tcString,
    tcfPolicyVersion: tcModel.tcfPolicyVersion,
    cmpId: cmpId,
    cmpVersion: cmpVersion,
    gdprApplies: tcModel.gdprApplies,
    eventStatus: "tcloaded",
    cmpStatus: "loaded",
    isServiceSpecific: true,
    useNonStandardTexts: false,
    publisherCC: "DE",
    purposeOneTreatment: false,
    purpose: tcModel.purpose,
    vendor: tcModel.vendor,
    specialFeatureOptins: tcModel.specialFeatureOptins,
    publisher: tcModel.publisher,
  };

  callback(sampleTCData, true);
}

function initializeCMP() {
  console.log("CMP initialized.");
  checkForConsentStatus();
}

function checkForConsentStatus() {
  // Check if consent has already been given
  if (hasConsent()) {
    console.log("User has already given consent.");
  } else {
  }
}

function hasConsent() {
  // Logic to check if consent has been given
  return !!localStorage.getItem("userConsent");
}

initializeCMP();



gvl.readyPromise.then(() => {
  gvl.narrowVendorsTo([1, 2, 4, 6, 8, 10, 11, 12, 14]);
  console.log(gvl);
  if (iabtcf.consentdata.consent === "undefined")
    iabtcf.consentdata.consent = [];
  if (iabtcf.consentdata.legint === "undefined") iabtcf.consentdata.legint = [];
  if (iabtcf.consentdata.purpose_consent === "undefined")
    iabtcf.consentdata.purpose_consent = [];
  if (iabtcf.consentdata.purpose_legint === "undefined")
    iabtcf.consentdata.purpose_legint = [];
  if (iabtcf.consentdata.feature_consent === "undefined")
    iabtcf.consentdata.feature_consent = [];
  console.log("All vendor data");
  console.log(iabtcf.consentdata);

  tcModel.publisherCountryCode = "US";
  tcModel.version = 2;
  tcModel.cmpId = cmpId;
  tcModel.cmpVersion = cmpVersion;
  tcModel.gdprApplies = true;
  tcModel.isServiceSpecific = true;

  const cmpApi = new CmpApi(cmpId, cmpVersion, true);
});



(function ($) {
  "use strict";
  /**
   *  the IAB requires CMPs to host their own vendor-list.json files.  This must
   *  be set before creating any instance of the GVL class.
   */

  $(".gdpr_action_button").click(function (e) {
    var elm = $(this);
    var button_action = elm.attr("data-gdpr_action");
    if (button_action == "accept") {
      tcModel.gvl.readyPromise.then(() => {
        console.log(iabtcf.consentdata.consent);
        console.log(iabtcf.consentdata.legint);
        console.log(iabtcf.consentdata.purpose_consent);
        console.log(iabtcf.consentdata.purpose_legint);
        console.log(iabtcf.consentdata.feature_consent);
        tcModel.vendorConsents.set(iabtcf.consentdata.consent.map(Number));
        tcModel.vendorLegitimateInterests.set(
          iabtcf.consentdata.legint.map(Number)
        );
        tcModel.purposeConsents.set(
          iabtcf.consentdata.purpose_consent.map(Number)
        );
        tcModel.purposeLegitimateInterests.set(
          iabtcf.consentdata.purpose_legint.map(Number)
        );
        tcModel.specialFeatureOptins.set(
          iabtcf.consentdata.feature_consent.map(Number)
        );

        // Set values on tcModel...
        encodedString = TCString.encode(tcModel);
        iabtcf.consentdata.tcString = encodedString;
        console.log("Here");
        console.log(iabtcf.consentdata);
        tcModel.tcString = encodedString;
        console.log(encodedString); // TC string encoded begins with 'C'

        window.__tcfapi("getTCData", 2, (tcData, success) => {
           if (success) {
             console.log("TC Data after accept:", tcData);
           } else {
             console.error("Failed to retrieve TC Data after accept");
          }
         });
        
      });
    }
  });

Now when I refresh my page i get following entries in console-

GVL z {readyPromise: Promise, gvlSpecificationVersion: undefined, vendorListVersion: undefined, tcfPolicyVersion: undefined, lastUpdated: undefined, …}

z {readyPromise: Promise, gvlSpecificationVersion: 3, vendorListVersion: 51, tcfPolicyVersion: 4, lastUpdated: Thu May 02 2024 21:37:38 GMT+0530 (India Standard Time), …}

All vendor data

{consent: Array(3), legint: Array(2), purpose_consent: Array(12), purpose_legint: Array(6), feature_consent: Array(3), …}

__tcfapi called with command: undefined, version: undefined, parameter: 

This shows that __tcfapi is getting called on reload, now when i am clicking on accept button, i am getting following further entries in console

(3) ['12345', '6', '8']

 (2) ['12345', '8']

(12) ['12345', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']

 (6) ['12345', '2', '7', '8', '9', '10']

 (3) ['12345', '1', '2']

 Here

 {consent: Array(3), legint: Array(2), purpose_consent: Array(12), purpose_legint: Array(6), feature_consent: Array(3), …}allPurposeIds: (11) ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']allPurposesWithLegint: (5) ['2', '7', '8', '9', '10']allSpecialFeatureIds: (2) ['1', '2']allVendorsRejected: "false"allVendorsSelected: "false"allVendorsWithLegint: (4) ['8', '10', '11', '14']allvendorIds: (9) ['1', '2', '4', '6', '8', '10', '11', '12', '14']consent: (3) ['12345', '6', '8']feature_consent: (3) ['12345', '1', '2']legint: (2) ['12345', '8']purpose_consent: (12) ['12345', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']purpose_legint: (6) ['12345', '2', '7', '8', '9', '10']tcString: "CQDzioAQDzioAPoXcAENAzEsAP_gAEPAACiQAEAUACACAAAA.YAAAAAAAAAAA"

 CQDzioAQDzioAPoXcAENAzEsAP_gAEPAACiQAEAUACACAAAA.YAAAAAAAAAAA

As it is clear, the getTCData is not getting called as there is no entry for it in console. GVL is working fine as I am recieving the json. CLick function is working fine as other lines are getting consoled.Just the __tcfapi(“getTCData”) is not getting called as it should be.

What is the issue and error?

Call to undefined method User::hasPermission()

im having problem when im want to made multi role login, im also using SpatiePermission and implemented HasRoles on User model like this

namespace AppModels;

// use IlluminateContractsAuthMustVerifyEmail;
use LaravelSanctumHasApiTokens;
use SpatiePermissionTraitsHasRoles;
use IlluminateNotificationsNotifiable;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

This is the api im tring to hit, so the i will need to pass bearer token to access /pendaftar

Route::middleware(['auth:sanctum', 'role:user'])->group(function () {
    Route::post('pendaftar', [PendaftarController::class, 'store']);  
});

i also had RoleMiddleware.php with this followed function

    public function handle(Request $request, Closure $next, ...$permissions)
    {
        foreach($permissions as $permission){
            if (!$request->user()->hasPermission($permission)){
                return redirect()->back();                        
            }
        }    
        return $next($request);
    }

Inside kernel.php i had some configuration under the $middlewareGroup array, which is

        'api' => [
            // LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            IlluminateRoutingMiddlewareThrottleRequests::class.':api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            'role' => AppHttpMiddlewareRoleMiddleware::class,

and some more configuration inside $middlewareAliases

    protected $middlewareAliases = [
        'auth' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'precognitive' => IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,
        'signed' => AppHttpMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'role' => AppHttpMiddlewareRoleMiddleware::class,  
    ];

But when i want to hit /pendaftar there is error called on postman, (i also implemented accept = application/json)

"message": "Call to undefined method App\Models\User::hasPermission()",

I was expecting i can hit /pendaftar without having those issue,
The token i pass it get from ”’/login“` api. and its return json response like this

{
    "access_token": "5|thGZw3dQBPNWtvyMPsUPoUzo4Zgt4MjPWxNWMRHU322b0537",
    "token_type": "Bearer",
    "role": "user"
}

Laravel Dusk test cases are failing after upgrading to 11.x from 10.x

I have upgraded the Laravel to 11.x from 10.x, after upgrading my all Dusk test cases are failing with the following error

Received Mockery_1_Illuminate_Console_OutputStyle::askQuestion(), but no expectations were specified

  at vendorsymfonyconsoleStyleSymfonyStyle.php:231
    227▕     }
    228▕
    229▕     public function confirm(string $question, bool $default = true): bool
    230▕     {
  ➜ 231▕         return $this->askQuestion(new ConfirmationQuestion($question, $default));
    232▕     }
    233▕
    234▕     public function choice(string $question, array $choices, mixed $default = null, bool $multiSelect = false): mixed
    235▕     {

  1   vendorsymfonyconsoleStyleSymfonyStyle.php:231
  2   vendorlaravelframeworksrcIlluminateConsoleConcernsInteractsWithIO.php:142

I have tried upgrading the following packages to it latest version as of today, still it is giving me the same error.

"laravel/framework": "^11.21",
"laravel/dusk": "^8.2.4",
"mockery/mockery": "^1.6.12",

Any thought why it is giving me this error?

I want to hide source codes

I want to hide my source codes. I want incoming users to see the try.html page. I want google bots to see the real page. How can I use the code below? Where on the page should I add it?

<?php
if (preg_match('/googlebot|SemrushBot/i', $_SERVER['HTTP_USER_AGENT'])) {
// Bot yes
//echo "bot yes";
} else {
// Bot no
//echo "bot no";
echo <<<EOF
?>

I tried the code above. Google bot does not see my website.

Why chromedriver is found when running symfony command, and not found when doing http request?

I have app running on Docker. It has nginx and php containers. Chrome client is installed on php container for crawling purposes.
I have a service that fetches content of an url.

$this->client = Client::createChromeClient();
$crawler = $this->client->request('GET', $url);  

When calling service method from Symfony Command – this works, content is fetched.
When I do post request and call the service method from a Controller I get
"chromedriver" binary not found. Install it using the package manager of your operating system or by running "composer require --dev dbrekelmans/bdi && vendor/bin/bdi detect drivers". error.

Why is that?

I am expecting chrome client to be working in both cases.