setup JWT auth milan parmar [closed]


namespace AppHttpControllers;

use AppModelsAdmin;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesFile;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use TymonJWTAuthFacadesJWTAuth;

class AdminAuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (! $token = auth('admin')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }


    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:admins',
            'password' => 'required|string|min:6',
        ]);

        $admin = Admin::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = JWTAuth::fromUser($admin);

        return response()->json(compact('admin', 'token'), 201);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('admin')->factory()->getTTL() * 60
        ]);
    }

    public function fetch(){
        // Check if the admin is authenticated
        if (! Auth::guard('admin')->check()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        } else {
            // If authenticated, proceed
            $data = Auth::guard('admin')->user(); // Use guard to get the admin data
            return response()->json($data);
        }

    }
}


namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable; // Important!
use IlluminateNotificationsNotifiable;
use TymonJWTAuthContractsJWTSubject; // For JWT support

class Admin extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    // This is needed for JWT
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    }
}

this are the code by help to add the jwt auth into you laravel project

How can I add a replace for a br in a .php-file? [closed]

Here is my .php-file:
index.php:

<html lang="sv-gibraltar">
   <head>
      <title>Eliseshundar.se&reg;</title>
      <meta charset="utf-8">
      <link rel="stylesheet" href="/reset.css">
      <link rel="stylesheet" href="/https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
   <body>
      <?php echo "<table class='table'>";
         echo "t";
         echo "<td class='tableSub'>";
         echo "<br>";
      ?>
      PLEASE REGISTER AN ACCOUNT HERE
      <!-- Here I have entered a simple registration form, without credentials. -->
      <script src="Array.js"></script>
...

And here is the JS-file:
Array.js:)

// Squeeky clean files go everywhere!
this.HTMLTableCaptionElement
// Here I have selected, a null table
this.table = "";
this.table.trimEnd.querySelector('.tableSub');
this.table.querySelector('')

Below tableSub I want to select <br>, but I want to replace it with randomColors of cats from a generator I have created.

Error message in php $_SESSION is couldn’t be reached after it is generated in another page [closed]

i am executing this private method by call in another part of class. the session is started already at the top of script(source of problem is not related with session_start()).
This is where I generate the error message :

private function isValidOthers($parentId, $title, $keywords, $description, $status, $slug)
{     
    if (empty($parentId) || empty($title) || empty($keywords) || 
        empty($description) || empty($status) || empty($slug)) 
    {
        $_SESSION["error"] = "All inputs are necessary. Please fill all fields.";
        header("Location:admin/category_add.php");
        exit;
    }
}

And this is where i want to handle the error message (admin/category_add.php) :

<?php
session_start();

var_dump($_SESSION);


if (isset($_SESSION["error"])) {
    echo "

        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: '" . $_SESSION['error'] . "',
            timer: 3000,
            showConfirmButton: false
        });
    ";

unset($_SESSION['error']);
}

if I uncomment the line var_dump($_SESSION) i can reach the error message as i expect. but i want to handle my error message without reaching $_SESSION.

I think i misunderstood one simple point, is there anyone to help?

Get list of private Dailymotion videos

I want to get list of private Dailymotion videos.

I am able to receive an access token with a private key. But then when I send Get request to retrieve the list of videos, I see the following “400 Bad Request: malformed Host header”.

<?php
            //Perform authentication
            // Specify the URL and data
$url = "https://partner.api.dailymotion.com/oauth/v1/token";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Host: partner.api.dailymotion.com",
   "Content-Type: application/x-www-form-urlencoded",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = "grant_type=client_credentials&client_id=xxx&client_secret=xxx&scope=manage_videos";

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$resp = curl_exec($curl);
curl_close($curl);
$data = json_decode($resp, true);
$access_token = $data['access_token'];
$url = "https://partner.api.dailymotion.com/user/userid/videos?fields=id&limit=30&private=true";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
    "Host: partner.api.dailymotion.com/rest",
);

$auth = "Authorization: Bearer " . $access_token;
$headers[1] = $auth;
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$resp = curl_exec($curl);
curl_close($curl);
//var_dump($resp);
?>

When I omit host in headers I get 404 Not Found.

    $headers = array(

);

$auth = "Authorization: Bearer " . $access_token;
$headers[0] = $auth;

I also tried to use the following url. I get 404 Not Found.

$url = "https://partner.api.dailymotion.com/videos?fields=id&private=true&owners=userid;

Laravel can’t get redis key value in For loop

I have a problem with Laravel when getting a Redis value in loop

public function testLoop()
{
    for($i = 0; $i < 3; $i++) {

        Redis::set('key_'.$i, 'value_'.$i);
        Log::info(Redis::get('key_'.$i));
    }
   
    return true;
}

Laravel successfully set the key but any error while trying to get key

here is the logs, it only gets first

[2024-10-21 09:05:13] local.INFO: value_0
[2024-10-21 09:05:13] local.ERROR: Error while reading line from the server. [tcp://docker.for.mac.localhost:6379] {“userId”:569,”exception”:”[object] (PredisConnectionConnectionException(code: 0): Error while reading line from the server. [tcp://docker.for.mac.localhost:6379] at /var/www/html/vendor/predis/predis/src/Connection/AbstractConnection.php:144)
[stacktrace]

and here is the redis key

enter image description here

I’m tried both predis and phpredis but both have same issue

I have set redis timeout to 0

127.0.0.1:6379> config get timeout
1) "timeout"
2) "0"

I’ve also set read_write_timeout in config/database.php to 0

'read_write_timeout' => 0,

value from redis-cli

enter image description here

redis-cli monitor (stuck at key_1)

enter image description here

Optional route params

I have to setup a multi-language application with Laravel 11, this is the first time that I use multi-language feature in laravel, I will not use any package, I will set it manually, so I prepared the web.php file like this :

Route::group(['middleware' => ['setLocale']], function () {
    Route::get('/products/{slug}', [ProductController::class, 'fetchProduct']);
});
Route::group(['middleware' => ['setLocale'], 'prefix' => '{locale?}', 'where' => ['locale' => 'en|fr|de|jp']], function () {
    Route::get('/', LandingController::class);
    Route::get('/products/{slug}', [ProductController::class, 'fetchProduct']);
});

When I access to ‘/products/fr/exemple-product’ it works but when I tried to acces to the default route like this : ‘/products/exemple-product’ it deosn’t work and handle an error:
Too few arguments to function App\Http\Controllers\Front\ProductController::fetchProduct(), 1 passed in C:\...\ControllerDispatcher.php on line 46 and exactly 2 expected

this is the definiion of the fetchProduct method :

public function fetchProduct($locale = null, $slug) {dd($slug');}

even if I setted $locale to null but it deos’t work, can you please tell me what is the problem?

Why does empty($object->arrayProperty) result in true while array elements are set and filled? [duplicate]

Without any other changes the following three lines in the same spot result in (for me) incomprehensible results. The first result in my head does not match to what the other lines return:

var_dump(empty($this->table)); //results in "bool(true)"
var_dump($this->table); //results in an array of 75 elements
var_dump(empty($this->table[0])); //results in "bool(false)"

First of all:

  • My question is NOT what to do, to make my code work. Many other topics explain this very good and I don’t want duplication here.

  • My question is NOT why PHP has an error here. As PHP is what it is and it is the behaviour that it is.

  • As !isset() for non-false elements is an equivalent to empty() in this case it obviously has same results. I could have interchanged “…does empty($array) result in true…” inside the title with “…why does an array not exist…”. I decided for more specific wording.

I search for the explanation that leads to this (at least for me) confusing result. I have a guess that it might be a mechanic related to __get() or ob_get_clean() but I have no real clue how these work internally.

The Environment:

  1. I have a method inside an object that extracts an array out of a csv-file. (changed names)
   $object = new Class();
   
   empty($object->method()); //results in false - as I would expect as an array with 75 elements is returned
  1. I wrap this together with other variables of different types into a params-array.
   $params =['table' => $object->method(),...];
   
   empty($params['table']); //still results in false here
  1. Via a View object I pass the params-array to a view
   return (new View('transactions/show',$params))->render();

For the passing inside the View object I use the __get magic method

   public function __get(string $name) {
      return $this->params[$name] ?? null;
   }

The render function includes the view with output buffering

   public function render() {
       ob_start();
       include VIEW_PATH . DIRECTORY_SEPARATOR . $this->view . '.php';
       return ob_get_clean();
   }
  1. Inside the view (‘transactions/show’) I am able to access the params by $this->variable and as mentioned above the array is accessible and working fine but the result “true” of the empty($this->table) confuses me.

All my testing lead me to the point that step 3. is responsible for the results I experience inside step 4.

To show a reproducible version hereafter complete files:

Controller class:

<?php

declare(strict_types=1);

namespace AppController;

use AppModelDemoClass;
use AppView;

class Demo {
    public function index() {
        $object = new DemoClass();

        empty($object->demoMethod()); //results in false - as I would expect as an array with 75 elements is returned

        $params =['table' => $object->demoMethod()];

        empty($params['table']); //still results in false here

        return (new View('demo/show',$params))->render();
    }
}

The Model class (here only simulating to get an array of arrays from a source (csv, Database, whereever)

<?php

declare(strict_types=1);

namespace AppModel;

class DemoClass {
    public function demoMethod() {
        $array = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
        ];
        return $array;
    }
}

the View class (only the needed excerpt):

<?php

declare(strict_types=1);

namespace App;

use FrameworkExceptionViewNotFoundException;

class View {

    public function __construct(protected string $view, protected array $params =[]) {
    }

    public static function make(string $view, array $params =[]): static {
        return new static($view, $params);
    }
    
    public function render(): string {
        $viewPath = VIEW_PATH . DIRECTORY_SEPARATOR . $this->view . static::PHP_TYPE;
        
        if(!file_exists($viewPath)) {
            throw new ViewNotFoundException();
        }
        ob_start();
        include $viewPath;
        return (string) ob_get_clean();
    }
    
    public function __get(string $name) {
        return $this->params[$name] ?? null;
    }

    public function __toString():string {
        return $this->render();
    }
}

The view/html – kept it short without HTML header (it makes no difference here)

<?= var_dump(empty($this->table)); //results in "bool(true)" ?>
</br>

<?= var_dump($this->table); //results in an array of 75 elements ?>
</br>

<?= var_dump(empty($this->table[0])); //results in "bool(false)" ?>
</br>

with calling the Demo->index() (e.g. via Router) the result is:

bool(true)

array(3) { 
    [0]=> array(3) { 
        [0]=> int(1) 
        [1]=> int(2) 
        [2]=> int(3) 
    } 
    [1]=> array(3) { 
        [0]=> int(4) 
        [1]=> int(5) 
        [2]=> int(6) 
    } 
    [2]=> array(3) { 
        [0]=> int(7) 
        [1]=> int(8) 
        [2]=> int(9) 
    } 
}

bool(false)

Laragon Virtual Host doesn’t work for Laravel App

I know this question maybe duplicate, but from any answers and questions that I have looked at, no one of them can solve my problem. I use Laragon for my Laravel App project and i want to open the project by using the virtual host. I think I have changed the version of PHP on my Laragon but I doubt about that. After several months not using the Laragon, when I open the Virtual Host, the browser said

enter image description here

whaI have tried many methods, such as:

  1. Reinstall laragon, add new php version, etc
  2. Checking the Read-only setting of hosts file in Windows/System32/driver/etc/…
  3. Turn off the firewall
  4. Check the httpd.conf, but all is clear
  5. Check the auto.test.test.conf, and all is clear
    And many checking file, but no one solved my problem.
    Any suggestion and solution for this problem please? Thank you

Why is stdout not a tty?

Why is stdout not a tty, even though stderr is? Please let me know if you need more context, added this line to pass stackoverflow’s validation.

$ php -r 'var_dump(exec("test -t 1 && echo y"));'
string(0) ""
$ php -r 'var_dump(system("test -t 1 && echo y"));'
string(0) ""
$ php -r 'var_dump(passthru("test -t 1 && echo y"));'
NULL
$ php -r 'var_dump(exec("test -t 2 && echo y"));'
string(1) "y"
$ php -r 'var_dump(system("test -t 2 && echo y"));'
y
string(1) "y"
$ php -r 'var_dump(passthru("test -t 2 && echo y"));'
y
NULL
$ php -v
PHP 8.2.20 (cli) (built: Jul  4 2024 02:23:40) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.20, Copyright (c) Zend Technologies
$ uname -rsm
FreeBSD 13.3-RELEASE-p1 amd64

How do I pass a hidden text field as well as changle the form action

I have a script that will take a page name and change the form action, which will then take me to that page. However, I also want the ID for the page content to be passed to it. I assumed that a hidden field would work. I get the page, but there is no content.

<script language="javascript">
<!-- Script courtesy of http://www.web-source.net - Your Guide to Professional Web Site Design and Development
function goto(form) { var index=form.select.selectedIndex
if (form.select.options[index].value != "0") {
location=form.select.options[index].value;}}
//-->
</script>
<form name="form1">
<input type="hidden" name="id" id="id" value="<?php echo $row['id'];?>">
<select name="select" onchange="goto(this.form)">
<option value="">-------Choose a Selection-------
<option value="view.php">View
<option value="download.php">Download
</select>
</form>

I then capture the ID on the receiving page with.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $app_id = $_POST['id'];
}

UTF8 encoding issue with code igniter 2, PHP 7.4, oracle 11

what are the settings that i need to fix in php.ini, apache to show utf8 encoded text stored in oracle db to be displayed properly in a web page?

things i have done:

  • default charset settings to utf8
  • added explicit encoding in oci_connect

sample code:

<?php
function remove_utf8_bom($text)
{
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}
?>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
</head>
<?php
echo getenv('NLS_LANG');
echo '<br/>';
putenv("NLS_LANG=AMERICAN_AMERICA.UTF8");
echo getenv('NLS_LANG');
echo '<br/>';


header('Content-Type: text/html; charset=UTF-8');

$conn = oci_connect('xxx', 'xxx', 'xxx', 'AL32UTF8');

if (!$conn) {
    $e = oci_error();
    echo "Connection failed: " . $e['message'];
    exit;
}
// Set the NLS_LANG for the session
oci_execute(oci_parse($conn, "ALTER SESSION SET NLS_LANGUAGE='AMERICAN'"));
oci_execute(oci_parse($conn, "ALTER SESSION SET NLS_TERRITORY='AMERICA'"));
//oci_execute(oci_parse($conn, "ALTER SESSION SET NLS_CHARACTERSET='AL32UTF8'"));

oci_set_client_info($conn, "NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
//mb_internal_encoding('UTF-8');


$query = 'SELECT * FROM FMS_BERUJU';
$stid = oci_parse($conn, $query);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    //var_dump($row);
    $item = $row['FB_OFFICE_HEAD_NEP'];
    //$item = str_replace(0xFEFF, "", $item, 1);
    $item = remove_utf8_bom($item);
    echo 'Office Head Nepali: '.htmlspecialchars($item, ENT_QUOTES, 'UTF-8') ."<br>n";
    echo 'Office Head Nepali: '.mb_convert_encoding($item, 'UTF-8', 'auto') ."<br>n";
    echo 'Office Head Nepali: '.$row['FB_OFFICE_HEAD_NEP']."<br>n";
    echo 'Office Head Nepali: '.$item."<br>n";
    echo 'Office ID: '.$row['FB_OFFICE_ID']."<br>n";
    echo 'Office Fiscal Year: '.$row['FB_FISCAL_YEAR']."<br>n";
    echo "<br>n";
    echo "<br>n";
}

oci_free_statement($stid);
oci_close($conn);

output:

शà¥à¤°à¥€ कृषà¥à¤£ सिंह बसà¥à¤¨à¥‡à¤¤ / शà¥à¤°à¥€ सागर जà¥à¤žà¤µà¤¾à¤²à¥€

mbstring config in php.ini
enter image description here

How to upload a file to a /upload folder in PHP?

<?php
if($_SERVER["REQUEST_METHOD"] == "GET"){
    $file = $_GET["fname"];
}else{
    if(isset($_POST["content"]) && isset($_POST["file"])){
          $folder = "/uploads/";
          $file = $_POST["file"];
          $content = $_POST["content"];
          if(file_exists($file)){
               echo "<h1>That file already exists on the server</h1>";
          }else{
               file_put_contents(basename($folder, $file), $content);

          }
          
     }else{
     echo "<h1>Request has failed to be sent</h1>";
    }

}

I used file_put_contents because I thought I could just put the file there and so on.

I tried playing around with my code

wordpress show specific html for descktop and another html for mobile

In wordpress I have a header.php that inside it I coded desktop and mobile HTML together. the problem is that for each device the other html are loaded and I just make them display none by media query. that makes performance and SEO problems as I know.

I want to just load the html of desktop in desktop and mobile in mobile. I used wp_is_mobile() before but as you know this function doesn’t works when you enable cache.

this is a example of what is my header.php look like:

<!DOCTYPE html>
<html lang="fa" dir="rtl">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <?php if (function_exists('wp_body_open')) {
        wp_body_open();
    } else {
        do_action('wp_body_open');
    } ?>
    <header>
        <div id="main-menu" class="<?php print_custom_header_classes(); ?>">
            <!------------------------------ mobile menu ------------------------------>
            <div class="mobile-nav">
                        <div class="navbar-toggler transparent-highlight">
                            <span class="nav-icon"></span>
                        </div>
                        <div class="header-brand header-brand--mobile">
                            <a class="header-brand__link transparent-highlight" href="<?php echo site_url(); ?>">
                                <img src="<?php echo get_template_directory_uri(); ?>/assets/images/logo.webp" alt="" width="100" height="80" class="header-brand__link--logo">
                            </a>
                        </div>
            </div>
            <div class="main-menu__wrapper main-menu__wrapper--mobile">
                    <?php wp_nav_menu(
                        array(
                            'theme_location' => 'siteMenu',
                            'container' => true,
                            'menu_class' => 'main-menu__list',
                            'li_class' => 'main-menu__item',
                            'a_class' => 'main-menu__link'
                        )
                    ); ?>
            </div>
            <!------------------------------ desktop menu ------------------------------>
            <div class="container">
                <div class="main-menu__wrapper">
                      <!---------- desktop content goes here I did not add in order not to write additional code ---------->
                </div>
            </div>
    </header>

another option is add by js but this approach is not good for SEO and also mybe load not as fast as html when defering. Is there any other options that I can use? Any helpful approach and efforts are appreciated.