PHP – PDO inserting empty strings into database [closed]

i’m trying to create an account system for my personal project website. i’m having trouble with the registration; when i insert the values from the form and check the database, there is a row inserted, but it only contains empty values. PDO doesn’t throw any exceptions.

my php code:

<?php
$servername = "redacted";
$dbusername = "redacted";
$dbpassword = "redacted";

try {
    $conn = new PDO("mysql:host=$servername;dbname=default", $dbusername, $dbpassword);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Error: " . $e->getMessage());
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = test_username($_POST["username"]);
    $password = password($_POST["password"]);
}

function test_username($uname) {
    $uname = trim($uname);
    if (!preg_match("/^[a-zA-Z0-9]*$/", $uname)) {
        die("invalid character in username");
    }
}

function password($password) {
    $password = trim($password);
    if (strlen($password) < 8 || strlen($password) > 32 || !preg_match("/^[A-Za-z0-9!@#$%^&*]*$/", $password) || !preg_match("/[A-Z]/", $password) || !preg_match("/[a-z]/", $password) || !preg_match("/[0-9]/", $password) || !preg_match("/[!@#$%^&*]/", $password)) {
        die("password requirements not met");
    }
    $password = password_hash($password, PASSWORD_DEFAULT);
}

try {
    $conn->exec("INSERT INTO users (username, password)
    VALUES ('$username', '$password');");
} catch(PDOException $e) {
    die("Database insert failed:" . $e->getMessage());
}

header("Location: /register-succcess.html");
?>

my form:

<form action="scripts/register.php" method="POST" onsubmit="return validateForm()" name="login">
    <fieldset>
        <legend>register</legend>
        <div>
             <label for="username">username:</label>
             <input type="text" name="username" id="username" required maxlength="32">
             <span id="unameError"></span>
        </div>

        <div>
             <label for="password">password:</label>
             <input type="password" name="password" id="password" required maxlength="32">
             <span id="pwordError"></span>
        </div>

        <button type="submit">register</button>
        <p><a href="login">login</a></p>
    </fieldset>
</form>

inserted database row:

# id, username, password, created_at
'4', '', '', '2024-12-09 09:24:17'

WooCommerce change order status based on shipping method

I need to change the order status from the default ‘processing’ status to ‘priority’ if a customer chooses any 1 of 4 express shipping options.

I’m using the classic checkout.

Here’s what I’ve tried so far but nothing happens when a user places an order.

add_action( 'woocommerce_thankyou', 'shipping_method_update_order_status', 10, 1 );
function shipping_method_update_order_status( $order_id ) {
    if ( ! $order_id ) return;
    
    // Here define your shipping methods Ids
    $shipping_method_0_flat_rate25 = array('flat_rate');
    $shipping_method_0_flat_rate26 = array('flat_rate');
    $shipping_method_0_flat_rate27 = array('flat_rate');
    $shipping_method_0_flat_rate28 = array('flat_rate');

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Shipping object data
    foreach($order->get_shipping_methods() as $shipping_item ){
        // For testing to check the shipping method slug (uncomment the line below):
        // echo '<pre>'. print_r( $shipping_item->get_method_id(), true ) . '</pre>';

        if( in_array( $shipping_item->get_method_id(), $shipping_method_0_flat_rate25 ) && ! $order->has_status('priority_dispatch') ){
            $order->update_status('priority_dispatch'); // Already use internally save() method
            break; // stop the loop
        }
        elseif( in_array( $shipping_item->get_method_id(), $shipping_method_0_flat_rate26 ) && ! $order->has_status('priority_dispatch') ){
            $order->update_status('priority_dispatch'); // Already use internally save() method
            break; // stop the loop
        }
        elseif( in_array( $shipping_item->get_method_id(), $shipping_method_0_flat_rate27 ) && ! $order->has_status('priority_dispatch') ){
            $order->update_status('priority_dispatch'); // Already use internally save() method
            break; // stop the loop
        }
        elseif( in_array( $shipping_item->get_method_id(), $shipping_method_0_flat_rate28 ) && ! $order->has_status('priority_dispatch') ){
            $order->update_status('priority_dispatch'); // Already use internally save() method
            break; // stop the loop
        }
    }
}

Pull data from trade ogre api with php

https://tradeogre.com/api/v1/markets

I am trying to pull the price of ada to add to my website.

This is what I’ve tried:

<?php
$content = file_get_contents('https://tradeogre.com/api/v1/markets');

preg_match('#"ADA-USDT":{"initialprice":"(.*)","price":"(.*)"#', $content, $match);
echo $match[2];

?>

I tried and thought it was going to be easy as i have used this code many times!

I want to deploy laravel intertia wth react.tsx on namecheep server stuck at this point

I know how to deploy a Laravel project, but I don’t know how to handle the React project with Laravel and Inertia. I am using shared hosting on Namecheap. I have deployed the Laravel backend, and the migrations have run successfully, and the tables are connected. The only issue is that the frontend is not loading. This is not an API-based project; I am using Inertia to communicate between React and Laravel Error message Images on frontend

can you please guide me what to do next and how to solve this problem

Note: i have try to install npm in directory but its not work but i have an option of node in my serve see the image bellow
Node Image in namecheep cpanle

Message: “Not Found” (404) when trying to create private repo on github /user/repos

I’m getting error:

{
    "message":"Not Found",
    "documentation_url":"https://docs.github.com/rest",
    "status":"404"
}

when trying to create private repo on my GitHub account. My code in php:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.github.com/MY_USERNAME/repos',
    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_HTTPHEADER => array(
        "Accept: application/vnd.github+json",
        "Authorization: Bearer MY_TOKEN",
        "X-GitHub-Api-Version: 2022-11-28",
        "User-Agent: MY_APP_NAME"
    ),
    CURLOPT_POSTFIELDS => array(
        "name" => "test-repo-123",
        "description" => "This is your first repo!",
        "homepage" => "https://MY_URL",
        "private" => true,
        "is_template" => true
    ),
));

$response = curl_exec($curl);

curl_close($curl);

I had to create GH App, and installed it on my GH Account.

When I cut line:

"User-Agent: MY_APP_NAME"

I get error:

Request forbidden by administrative rules. Please make sure your request has a User-Agent header (https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required). Check https://developer.github.com for other possible causes.

Ofcourse, in constants: MY_USERNAME, MY_TOKEN, MY_APP_NAME, MY_URL I have my sensitive data.

What am I doing wrong?

Thanks
Mike

How do I set a specific CSS stylesheet to load If a specific database id is set? [closed]

I am working on a project in Codeigniter 3.1.9 on PHP 8.2.12.

My question is I have a lot of dynamic data that gets brought into a static view to create multiple pages. The issue I have is that without creating my own PDF Library, or having every page identical, I would need to bring in different print style sheets for each page instance. I could bring in all the different stylesheets at once, so they all load every time a page loads, but that feels a bit clunky and unnecessary.

So, the solution I was hoping for is to have different stylesheets load in dynamically depending on which record is pulled in, with PHP. I already am doing this this with an admin check on the admin elements and styles which works beautifully. However, those instances are loading in stylesheets and elements that are fairly static from fixed views.

Here is the Recipe Controller:

<?php
 
 class Recipe extends BaseController{

  function __construct(){
   parent::__construct();
   
   // Loading in Pagination Library
   $this->load->library('pagination'); 
   
   // Loading in Recipe_model
   $this->load->model('recipe_model');
   
   $uri = $this->uri->uri_string();
   $this->session->set_flashdata('uri', $uri);
  }
    
  function index(){
   $recipe_linkname = $this->uri->rsegment(3);
   if(!$recipe_linkname){
    $recipe_linkname = $this->recipe_model->first_linkname();
   }
   $recipe = $this->recipe_model->read_record($recipe_linkname);
   if(count($recipe) == 0){
    show_404('');
    die();
   }
   $data = array(
    'title' => "Shirley's Recipes:".$recipe['name'], 
    'columns' => array('toc', 'recipe'), 
    'recipe' => $recipe, 
    'updated' => $this->format_date($recipe['updated'])
    );
   $this->load->view('templates/main', $data);
  }
    
  function flipbook(){  
   
   // Requires the user to be "logged in"   
   $this->require_login();  
   
   // Recipe Flipbook Pagination Configuration
   $config['base_url'] = site_url('recipe/flipbook');
   $config['total_rows'] = $this->recipe_model->num_rows();
   $config['uri_segment'] = '3';
   $config['per_page'] = 1;
   $config['num_links'] = 9; // You will see 10 numerical link buttons in paginnation.
   $config['display_pages'] = TRUE;
   $config['full_tag_open'] = '<div id="pagination" class="grid-item3">';
   $config['full_tag_close'] = '</div>'; 

   // Initialize the Pagination Library
   $this->pagination->initialize($config);  
   
   $recipe = $this->recipe_model->read_records($config['per_page'], $this->uri->segment(3))->row_array();
   $data = array(
    'title' => "Shirley's Recipes:".$recipe['name'], 
    'columns' => array('toc', 'admin/page/recipe_flipbook'), 
    'recipe' => $recipe,
    'updated' => $this->format_date($recipe['updated'])
   );   
   $this->load->view('templates/main', $data);
  }
  
  function search(){
   if($this->input->method() === 'post'){           
    $search = $this->input->post('query');  //modify here:        
    $results = $this->recipe_model->search($search);
    $page = $this->uri->segment(3);
    $perPage = 19;    
    $results = $this->recipe_model->search($search, $page, $perPage);
    $data = array(
     'title' => "Shirley's Recipes:Search Results", 
     'columns' => array('toc', 'public/page/search_results'), 
     'recipes' => $results,  // $results is being renamed $recipes. I don't really know why though yet...
     'search' => $search
    );
    $this->load->view('templates/main', $data);
   }
   else{            
    redirect('recipe');
   }
  } 
    
  function add(){
      
   // Requires the user to be "logged in"     
   $this->require_login();

   if($this->input->post('submit')){
    $data = array(
     'id' => $this->input->post('id'),  
     'name' => $this->input->post('name'), 
     'buttontext' => $this->input->post('buttontext'), 
     'linkname' => $this->input->post('linkname'), 
     'time' => $this->input->post('time'),      
     'category' => $this->input->post('category'), 
     'subcategory' => $this->input->post('subcategory'),
     'img' => $this->input->post('img'),
     'keywords' => $this->input->post('keywords'),   
     'ingredients' => $this->input->post('ingredients'), 
     'equipment' => $this->input->post('equipment'), 
     'prepreparation' => $this->input->post('prepreparation'), 
     'directions' => $this->input->post('directions')
    );
    $recipeid = $this->recipe_model->create_record($data);
    redirect('recipe/'.$this->input->post('linkname'));
   }
   else{ // If the IF statement returns false, then  the ELSE statement tells php to do something else.
    $data = array(
     'title' => "Shirley's Recipes:Add New Recipe", 
     'columns' => array('toc', 'admin/edit-page/recipe_edit'), 
     'recipe' => array(
      'id' => '',
      'name' => '', 
      'buttontext' => '', 
      'linkname' => '', 
      'time' => '', 
      'category' => '', 
      'subcategory' => '',    
      'img' => '',
      'keywords' => '',   
      'ingredients' => '', 
      'equipment' => '', 
      'prepreparation' => '', 
      'directions' => ''
     )
    );
    $this->load->view('templates/main', $data);
   }
  }
  
  function edit(){
      
   // Requires the user to be "logged in"     
   $this->require_login();
   
   $id = $this->uri->segment(3);
   if($this->input->post('submit')){
    $data = array(
     'name' => $this->input->post('name'), 
     'buttontext' => $this->input->post('buttontext'), 
     'linkname' => $this->input->post('linkname'), 
     'time' => $this->input->post('time'),    
     'category' => $this->input->post('category'), 
     'subcategory' => $this->input->post('subcategory'),
     'img' => $this->input->post('img'),     
     'keywords' => $this->input->post('keywords'), 
     'ingredients' => $this->input->post('ingredients'), 
     'equipment' => $this->input->post('equipment'), 
     'prepreparation' => $this->input->post('prepreparation'), 
     'directions' => $this->input->post('directions')
    );
    $this->recipe_model->update_record($id, $data);
    redirect('recipe/'.$this->input->post('linkname'));
   }
   else{ // If the IF statement returns false, then  the ELSE statement tells php to do something else.
    $recipe = $this->recipe_model->read_record($id);
    $data = array(
     'title' => "Shirley's Recipes:Edit Recipe : ".$recipe['name'], 
     'columns' => array('toc', 'admin/edit-page/recipe_edit'), 
     'id' => $id, 
     'recipe' => $recipe
    );
    $this->load->view('templates/main', $data);
   }
  }
    
  function delete(){
      
   // Requires the user to be "logged in"     
   $this->require_login();
   
   $this->recipe_model->delete_record($this->uri->segment(3));
   redirect('/');
  } 
 }

 // End of recipe.php

?> 

Here is the Recipe_model.php

<?php

 class Recipe_model extends CI_Model{

  function create_record($data){
   if(isset($data['buttontext']) and $data['buttontext'] == ''){
    $data['buttontext'] = NULL;
   }
   $this->db->insert('recipe', $data);
   return $this->db->insert_id();
  }
  
  function read_records($limit, $offset){
   $this->db->order_by('name', 'asc');
   if(isset($limit) && isset($offset)){
    $this->db->limit($limit, $offset);
   }
   $q = $this->db->get('recipe');
   return $q;
  }
  
  function read_record($key){
   if(is_numeric($key)){
    $this->db->where('id', $key);
   }
   else{
    $this->db->where('linkname', $key);
   }
   $q = $this->db->get('recipe');
   return $q->row_array();
  }
  
  function first_linkname(){
   $this->db->select('linkname, name');
   $this->db->order_by('name', 'asc');
   $this->db->limit(1);
   $q = $this->db->get('recipe');    
   return $q->row()->linkname;
  }
        
  function read_names(){
   $this->db->select('linkname, name');
   $this->db->order_by('name', 'asc');
   $q = $this->db->get('recipe');
   return $q->result();
  }
  
  function read_names_categories(){
   $this->db->select('buttontext, linkname, name, category, subcategory, img, time');
   $this->db->order_by('name', 'asc');
   $q = $this->db->get('recipe');
   return $q->result();  
  }
    
  function search($search, $currentPage = 1, $perPage = 19){ 
  $offset = ($currentPage = 1) * $perPage;
  $terms = explode(' ', $search); 
  $match = " ";       
  foreach($terms as $term){      
   $match .= $term;
  }       
  $querystr = "SELECT id, name, category, subcategory, keywords, MATCH(name, category,  subcategory, keywords) AGAINST('".$match."') as score FROM recipe WHERE  MATCH(name, category, subcategory, keywords) AGAINST('".$match."') ORDER BY name LIMIT 60 OFFSET 0;";
  $q = $this->db->query($querystr);   
  return $q->result();
 }

  function update_record($id, $data){
   if(isset($data['buttontext']) and $data['buttontext'] == ''){
    $data['buttontext'] = NULL;
   }
   $this->db->where('id', $id);
   $this->db->update('recipe', $data);
  }
  
  function delete_record($id){
   $this->db->where('id', $id);
   $this->db->delete('recipe');
  }
  
  function num_rows(){
   return $this->db->get('recipe')->num_rows();
  }
 }

 // End of Recipe_model.php

?>

Here is the static recipe.php View

<link rel="stylesheet" type="text/css" href="/assets/css/public/page/recipe.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/assets/css/public/page/print/printrecipe.css" media="print" />

<div id="sitecontent" class="grid-item2 grid-container">
<!-- Loads ADMIN items or CSS Stylesheets needed when logged in as ADMIN. -->
 <?php
  if($admin){
   echo '<link rel="stylesheet" type="text/css" href="/assets/css/admin/core/admin.css" />';
   echo '<link rel="stylesheet" type="text/css" href="/assets/css/admin/core/wmd.css" />';
   echo '<link rel="stylesheet" type="text/css" href="/assets/css/admin/page/recipeadmin.css" />';
   echo '<script type="text/javascript" src="/assets/js/wmd.min.js"></script><br>';
   echo '<script type="text/javascript" src="/assets/js/showdown.js"></script><br>';
   echo '<script type="text/javascript" src="/assets/js/confirmdelete.js"></script>';
   $this->load->view('admin/nav/notesnav');
  }
 ?>
 <div id="contents" class="<?php if($admin){echo 'grid-item2';} ?> grid-item1 grid-container scrollbar">
  <div id="spiral" class="grid-item1">
   <img class="spiral" src="/assets/img/lines/spiral1trans.png"/> 
  </div>
  <div id="recipe" class="grid-item2 grid-container">
  <div id="title" class="grid-item1">
   <?=$recipe['name']; ?>
   <br>
   <?=$recipe['time']; ?>
  </div>
  <div id="image" class="grid-item2">
   <?=$recipe['img']; ?>
  </div>
  <div id="ingredients" class="grid-item3">
   <h2>Ingredients:</h2>
   <?php 
    if(isset($recipe['ingredients']) && $recipe['ingredients'] != ''){
     echo $this->mkdn->translate($recipe['ingredients']);
    }
    else{
     echo '<br><br><br><br><br><br><br><br><br><br><br>';
    }
   ?>
  </div>
  <div id="equipment" class="grid-item4">
   <h2>Equipment:</h2>
    <?php 
     if(isset($recipe['equipment']) && $recipe['equipment'] != ''){
      echo $this->mkdn->translate($recipe['equipment']);
     }
     else{
      echo '<br><br><br><br><br><br><br><br><br><br><br>';
     }
    ?>
   </div>
   <div id="prepreparation" class="grid-item5">
    <h2>Pre-Preparation:</h2>
    <?php 
     if(isset($recipe['prepreparation']) && $recipe['prepreparation'] != ''){
      echo $this->mkdn->translate($recipe['prepreparation']);
     }
     else{
      echo '<br><br><br><br><br><br><br><br><br><br><br>';
     }
    ?>
   </div>
   <div id="directions" class="grid-item6">
    <h2>Directions:</h2>
    <?php 
     if(isset($recipe['directions']) && $recipe['directions'] != ''){
      echo $this->mkdn->translate($recipe['directions']);
     }
     else{
      echo '<br><br><br><br><br><br><br><br><br><br><br>';
     }
    ?>
   </div>   
  </div>
 </div> 
 <?php
  if(isset($updated)){
   echo '<div id="updated" class="grid-item2">Updated '.$updated.'</div>';
  }
   if($admin){
    echo '<div id="optionbuttons" class="grid-item noprint">';
    echo anchor('recipe/edit/'.$recipe['id'], img(array('src'=>'assets/img/icons/edit.png', 'alt'=>'Edit', 'title'=>'Edit')));
    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    echo '<a href="javascript:confirmdelete('Delete recipe?',''.base_url().'recipe/delete/'.$recipe['id'].'')">'.img(array('src'=>'assets/img/icons/delete.png', 'alt'=>'Delete', 'title'=>'Delete')).'</a>';
    echo '</div>';
   }
  ?>
</div> 

<?php
  if($admin){
   echo '';   
  }
?>

Could I accomplish this with an IF statement and how would I set it up?

I tried setting the stylesheets to load individually, however with the if statement I wrote they both loaded anyway.

My if statement looked something like this:

<?php
 if($recipe['linkname'] = 'gallonsizesweettea'){
  echo '<link rel="stylesheet" type="text/css" href="/assets/css/public/page/print/recipes/printgallonsizesweettea.css" media="print" />';
 }
 if($recipe['linkname'] = 'applecobbler'){
  echo '<link rel="stylesheet" type="text/css" href="/assets/css/public/page/print/recipes/printapplecobbler.css" media="print" />';
 }
?>

What am I missing here? Thanks in advance for any help anyone could offer!

Why the error message “Call to a member function execute()” is not suppressed in try-catch? [duplicate]

I have the code:

try {
    $db = new PDO("sqlite:filename.db");
    $q = $db->prepare("SELECT p1 FROM T1;");
    $q->execute(); // Fatal error: Uncaught Error: Call to a member function execute() on bool
} catch (PDOException $e) {
    // Process any database errors in one place
}

The file “filename.db” does not exist at the moment.

I would like to process all DB errors in one place, but for some reason the message “Fatal error: Uncaught Error: Call to a member function execute() on bool” is not suppressed, but displayed on the page.

Tell me, please, why? Can I solve my problem: “process any database errors in one place”?

Laravel Fortify add Page befor two-factor-challenge

i want to add a page between two-factor-challenge. The user should get redirected to a setup page (This works) but when i choose the option i want, i get redirectet to my login page and not to the two-factor-challenge page. That is definted in the FortifyServiceProvider

I got a Middleware that checks if the user is logged in, when not redirect to the two-factor-challenge page.

public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        // Benutzer nicht eingeloggt? Weiterleitung zum Login
        if (!$user) {
            return redirect()->route('login');
        }

        // 2FA nicht aktiviert? Weiterleitung zum nächsten Schritt
        if (!$user->two_factor_enabled) {
            return $next($request);
        }

        // Weiterleitung zur Two-Factor-Challenge
        return redirect()->route('two-factor.challenge');
    }
Route::get('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'create'])
    ->name('two-factor.challenge');
 public function setup2FAMethode(Request $request)
    {
        $request->validate([
            'totp_methode' => 'in:totp,sms,email',
        ]);

        if ($request->session()->get('two_factor_authenticated')) {
            return redirect()->route('dashboard');
        }

        switch ($request->input('totp_methode')) {
            case 'sms':
                // Logik für SMS
                return redirect()->route('two-factor.challenge');
            case 'totp':
                // Redirect auf die Two-Factor-Challenge-Seite
                return redirect()->route('two-factor.challenge');
            case 'email':
                // Logik für E-Mail
                return redirect()->route('two-factor.challenge');
            default:
                return redirect()->route('setup');
        }
    }

I tried to add a set a own route to the two-factor.challenge but than fortify doesnt triggeres the two-factor.login with the tokken. The Store function.

Highlight partial document with Codemirror

I’m using code mirror to display and highlight code extracts.
The following php extract is well highlighted because it has the php open tag at the beginning:

<?php
if (true) {

The following php extract is not well highlighted because it hasn’t the tag.

if (true) {

Which config would allow me this?
For now, I tried to play with the config without success:

import {basicSetup, EditorView} from "codemirror"
import {php} from "@codemirror/lang-php"
import {languages} from "@codemirror/language-data"

// The Markdown parser will dynamically load parsers
// for code blocks, using @codemirror/language-data to
// look up the appropriate dynamic import.
let view = new EditorView({
  doc: "if (true) {",
  plain: true,
  mode: {
    name: "php",
    startOpen: true
  },
  extensions: [
    basicSetup,
    php()
  ],
  parent: document.body
})

You can try it in this sandbox along with if (true) {.

Bonus: I’m using react-codemirror

Typo3 Backend Debugging (Extbase)

I try to debug some things from a backend module (ActionController / Repository classes) using
TYPO3CMSExtbaseUtilityDebuggerUtility::var_dump(). Unfortunately this has no effect. I remember that normally there was a panel in the backend showing the data, but in my case this doesn’t appear. I enabled the debug preset in the configuration. Does anyone have suggestions?

Thanks
Sebastian

Pdo: alter table ıf not exısts [duplicate]

I want to say do nothing if there is a column in the table, otherwise add the column, but I couldn’t do it.
I want to do this with PHP and PDO.

This works. But it doesn’t check if the column exists in the table.

$sorgu = $baglanti->prepare("ALTER TABLE gecici ADD Email1 varchar(255)");
$sorgu->execute();

This does not work.

$sorgu = $baglanti->prepare("ALTER TABLE gecici ADD COLUMN IF NOT EXISTS Email1 varchar(255)");
$sorgu->execute();

Thanks in advance for your help.

Social login with google/facebook via Laravel API

Hello Dev

I appreciate your time & intention.
Recently, i am trying to implement social login with laravel API.
I have implemented the Social login for web. And it’s working perfectly.
Facing problem to implement the same feature for React Native application via API.
I have created a public API Route for the social login via API.

Ex: https://example.com/api/social-login/{provider}/callback
Method : POST
Req Body : access_token (This token getting from login via Gmail account at React Native App)

After getting this access token i am passing as Req Body to the API.

Here is Code snippet :

public function handleProviderCallback(Request $request, $provider){
   try{
       $accessToken    = $request->access_token
       $socialProvider = $socialProvider = Socialite::driver($provider)->stateless()->userFromToken($accessToken);
       // Rest of code here

   }
   catch(Throwable $e){
      dd(
         $e->getMessage(),$e->getFile(),$e->getLine()
      );
   }

}

And Getting below error:

{“message”:”Client error: GET https://www.googleapis.com/oauth2/v3/userinfo?prettyPrint=false resulted in a 401 Unauthorized response:{“error”:”invalid_request”,”error_description”: “Invalid Credentials”}

Can anyone assist?

Trouble customizing walker_nav_menu for BS5 navbar

I have tumbled around in the rabbit hole, try’d different solutions for my BS5 main navbar with a WordPress Theme.

Have build a extended walker_nav_menu class for wp_nav_menu(), where playing around with start_el or end_lvl functions.

My end_lvl function seems not to get fired or something, as you see in the code below. There should be added an extra element to the list, containing languagebare for switching between 2 languages.

Can you tell me what I’m doing wrong?

Code in functions.php

class BS5_MainMenu extends Walker_Nav_Menu
{

  public function start_el(&$output, $data_object, $depth = 0, $args = null, $current_object_id = 0)
  {
    $item = $data_object; // use more descriptive name for use within this method.

    $frontpageID = get_option('page_on_front');

    if ($item->post_parent != 0 || $item->ID == $frontpageID) {
      return;
    }

    $itemUrl = get_permalink($item);

    $children = $this->getChildren($item->ID);

    $_liCssClass = "nav-item";
    $_aCssClass = "nav-link";

    if (count($children)) {
      $_liCssClass .= " dropdown";
      $_aCssClass .= " dropdown-toggle";
    }

    $output .= '<li class="' .  $_liCssClass . '">';

    if (!empty($itemUrl) && $itemUrl != '#') {
      $output .= '<a href="' . $itemUrl . '" class="' . $_aCssClass . '" role="button" data-bs-toggle="dropdown" aria-expanded="false">';
    } else {
      $output .= '<span>';
    }

    $output .= $item->post_title;

    if (!empty($itemUrl) && $itemUrl != '#') {
      $output .= '</a>';
    } else {
      $output .= '</span>';
    }

    $output .= $this->renderChildrenDropdownHtml($item->ID);
  }

  public function end_lvl(&$output, $depth = 0, $args = null)
  {
    $otherLanguage = $this->get_other_languages()[0];

    $output .= '<li class="nav-item mx-4">';
    $output .= '<a class="nav-link nav-translate" href="' . $otherLanguage->permalink . '">' . $otherLanguage->res_label . ' <span>' . $otherLanguage->displaylanguage . '</span></a>';
    $output .= '</li></ul>';
  }

  private function get_other_languages()
  {
    $_all = get_available_languages();
    $_other = array();
    $_current = get_locale();

    foreach ($_all as $result) {
      if ($_current == $result) {
        continue;
      }

      $_lang_of_result = explode("_", $result)[0];

      $_obj = new stdClass();
      $_obj->displaylanguage = Locale::getDisplayLanguage($_lang_of_result, $_lang_of_result);
      $_obj->permalink = get_msls_permalink($result);
      $_obj->flagurl = get_msls_flag_url($result);
      $_obj->res_label = $_lang_of_result == "da" ? "Skift til" : "Switch to";

      $_other[] = $_obj;
    }

    return $_other;
  }

  private function renderChildrenDropdownHtml($post_id)
  {
    if (!$post_id) {
      return false;
    }

    $children = $this->getChildren($post_id);
    if (!count($children)) {
      return false;
    }

    $html = '<ul class="dropdown-menu">';

    foreach ($children as $child) {
      $html .= '<li><a class="dropdown-item" href="' . get_permalink($child) . '">' . $child->post_title . '</a></li>';
    }

    $html .= '</ul>';
    return $html;
  }

  private function getChildren($post_id)
  {
    if (!$post_id) {
      return false;
    }

    $args = array(
      'post_parent' => $post_id,
      'post_type' => 'any',
      'numberposts' => -1,
      'post_status' => 'any'
    );
    return get_children($args);
  }
}

In my parts/header.php

<nav class="navbar navbar-main navbar-expand-lg highlighted" data-bs-theme="dark">
    <div class="container-fluid">
      <a class="navbar-brand" href="/index.html">
        <img src="<?php echo esc_url(get_template_directory_uri() . '/img/logo.svg'); ?>" height="70" />
      </a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navbar"
        aria-controls="main-navbar" aria-expanded="false" aria-label="Visning af navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="main-navbar">
        <?php

        wp_nav_menu([
          'theme_location' => 'MainMenu',
          'menu_class' => 'navbar-nav ms-auto mb-2 mb-lg-0',
          'container' => 'ul',
          'walker' => new BS5_MainMenu()
        ]);

        ?>
      </div>
    </div>
  </nav>

I have tried different things, found on Google