Can’t add new user using form in myth-auth

I’m tryna add new user by form. I use myth-auth for auth but it seems the data doesn’t added yet the view return in table user. Here my save method:

public function save()
    {
        $this->_user_model->withGroup($this->request->getVar('role'))->insert([
            'nama_lengkap' => $this->request->getVar('nama_lengkap'),
            'email' => $this->request->getVar('email'),
            // 'password_hash' => password_hash($this->request->getVar('password'), PASSWORD_BCRYPT),
            'password_hash' => Password::hash("123456"),
            'prodi' => $this->request->getVar('prodi'),
            'no_hp' => $this->request->getVar('no_hp'),
        ]);

        session()->setFlashdata('success', 'Berhasil Menambahkan User!');
        return $this->response->redirect(site_url('manage_users'));
        // return redirect()->to(site_url('manage_users'));
    }

I want the user have some default psw so when the user login they can change the psw later. I look at myth-auth documentation and some tutorial. It says that this will work, but it doesn’t. Maybe I miss something? Thank you.

I’ve tried some other way like insert it with builder. but it didn’t work either. I want the user to have some default psw so when the user login they can change the psw later. I look at myth-auth documentation and some tutorial. It says that this method will work, but it doesn’t. Maybe I miss something? Thank you.

Restrict User Access plugin different home page for each user level

I’m using Restrict User Access – Membership & Content Protection wantset different home pages based user access level.

Plugin Github page

want to set specific home pages by user level with this code but its not working.

add_filter( 'login_redirect', function( $redirect_to, $request, $user ) {

if( ! is_wp_error( $user ) && ' roleid1 ' == get_user_meta( $user->ID, '_ca_level', true ) ) {
    return home_url( 'home_page1' );
} else if( ! is_wp_error( $user ) && 'roleid2' == get_user_meta( $user->ID, '_ca_level', true ) ) {
    return home_url( 'home_page2' );
} else if( ! is_wp_error( $user ) && 'roleid3' == get_user_meta( $user->ID, '_ca_level', true ) ) {
    return home_url( 'home_page3' );
} else {
    return $redirect_to;
}

}, 10, 3 );

Find value in multidimensional array based on key

I have an array with multiple array, and in each array one of the fields is another array, see below. I need to find the value for “First name”, in the array that has an ‘item_id’ of value 177. How can I do that?

array(1) { 
[0]=> array(4) 
{ 
["product_id"]=> int(62) 
["item_id"]=> int(177) 
["quantity"]=> int(1) 
["options"]=> array(5) { 
[0]=> array(4) { 
["field_id"]=> string(13) "655259ef26f01" 
["label"]=> string(11) "First name:" 
["value"]=> string(4) "test" ["type"]=> string(4) "text" } 
[1]=> array(4) { ["field_id"]=> string(13) "65525a47553c3" 
["label"]=> string(10) "Last name:" 
["value"]=> string(4) "test" ["type"]=> string(4) "text" } 
[2]=> array(4) { 
["field_id"]=> string(13) "65525a658669b" 
["label"]=> string(15) "E-mail address:" 
["value"]=> string(17) "[email protected]" 
["type"]=> string(5) "email" } 
[3]=> array(4) { ["field_id"]=> string(13) "65525a964be34" 
["label"]=> string(27) "Language for questionnaire:" 
["value"]=> string(6) "German" 
["type"]=> string(6) "select" }
} } 

[1]=> array(4) { 
["product_id"]=> int(62) 
["item_id"]=> int(182) 
["quantity"]=> int(1) 
["options"]=> array(7) { 
[0]=> array(4) { 
["field_id"]=> string(13) "655259ef26f01" 
["label"]=> string(11) "First name:" 
["value"]=> string(4) "test" 
["type"]=> string(4) "text" 
} 
[1]=> array(4) { 
["field_id"]=> string(13) "65525a47553c3" 
["label"]=> string(10) "Last name:" 
["value"]=> string(4) "test" 
["type"]=> string(4) "text" 
} 
[2]=> array(4) { 
["field_id"]=> string(13) "65525a658669b" 
["label"]=> string(15) "E-mail address:" 
["value"]=> string(17) "[email protected]" 
["type"]=> string(5) "email" 
} 
[3]=> array(4) { 
["field_id"]=> string(13) "65525a7bb053f" 
["label"]=> string(46) "Send copy of the report to this email address:" 
["value"]=> string(17) "[email protected]" 
["type"]=> string(5) "email" 
} 
[4]=> array(4) { 
["field_id"]=> string(13) "65525a964be34" 
["label"]=> string(27) "Language for questionnaire:" 
["value"]=> string(7) "Chinese" ["type"]=> string(6) "select" }
} } }

I have tried several things, one of them this:

$fname = $customs['item_id'][$itemID]['options']['field_id']['655259ef26f01']['value'];

Disabling Request Logs Discrepancy in Laravel API

For each request that happens on my Laravel API, this line is logged in the Laravel Docker container of my Sail dev environment:

2023-11-18 08:51:13 ................................................... ~ 0s

In production, I also see a log for every request in my Laravel container, but with a slightly other format:

2023-11-17T12:34:58.790851089Z 172.18.0.12 -  17/Nov/2023:12:34:58 +0000 "GET /index.php" 200

I’m trying to disable these logs, but I’m unsure where to make the necessary changes. Any guidance on where to look or how to disable these logs would be greatly appreciated. Thank you!

TorannGeoIPGeoIP::__construct(): Argument #2 ($cache) must be of type IlluminateCacheCacheManager,

I’m in Laravel v10 and I wanted to show the ip address of client with geo location in details.

So I installed the package torann/geoip:

composer require torann/geoip

Then:

php artisan vendor:publish --provider="TorannGeoIPGeoIPServiceProvider" --tag=config

And after that created a middleware named GeoIPMiddleware which goes here:

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use TorannGeoIPGeoIP;

class GeoIPMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $config = config('geoip');

        $geoip = new GeoIP($config, $request);

        $request->attributes->add([
            'geoip' => $geoip->getLocation(), // Add location data to the request attributes
        ]);

        return $next($request);
    }
}

And also registered it at kernel.php:

protected $middleware = [
        // AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        AppHttpMiddlewareGeoIPMiddleware::class,
        ...
    ];

And here is the route:

Route::get('/ip/{ip}', [IPDetailsController::class, 'showIPDetails']);

But when I test it like this, I get an error:

http://localhost:8000/ip/32.2.185.118

Error:

TorannGeoIPGeoIP::__construct(): Argument #2 ($cache) must be of type IlluminateCacheCacheManager, IlluminateHttpRequest given, called in D:rootappHttpMiddlewareGeoIPMiddleware.php on line 15

According to the line of the middleware:

$geoip = new GeoIP($config, $request);

So what’s going wrong here? How can I solve this issue?

Note that I have also registered at ipapi website and created a key for myself and placed that in .env file like this: IPAPI_KEY=MY_KEY

And this is also my config/geoip.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for when a location is not found
    | for the IP provided.
    |
    */

    'log_failures' => true,

    /*
    |--------------------------------------------------------------------------
    | Include Currency in Results
    |--------------------------------------------------------------------------
    |
    | When enabled the system will do it's best in deciding the user's currency
    | by matching their ISO code to a preset list of currencies.
    |
    */

    'include_currency' => true,

    /*
    |--------------------------------------------------------------------------
    | Default Service
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default storage driver that should be used
    | by the framework.
    |
    | Supported: "maxmind_database", "maxmind_api", "ipapi"
    |
    */

    'service' => 'ipapi',

    /*
    |--------------------------------------------------------------------------
    | Storage Specific Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many storage drivers as you wish.
    |
    */

    'services' => [

        'maxmind_database' => [
            'class' => TorannGeoIPServicesMaxMindDatabase::class,
            'database_path' => storage_path('app/geoip.mmdb'),
            'update_url' => sprintf('https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=%s&suffix=tar.gz', env('MAXMIND_LICENSE_KEY')),
            'locales' => ['en'],
        ],

        'maxmind_api' => [
            'class' => TorannGeoIPServicesMaxMindWebService::class,
            'user_id' => env('MAXMIND_USER_ID'),
            'license_key' => env('MAXMIND_LICENSE_KEY'),
            'locales' => ['en'],
        ],

        'ipapi' => [
            'class' => TorannGeoIPServicesIPApi::class,
            'secure' => true,
            'key' => env('IPAPI_KEY'),
            'continent_path' => storage_path('app/continents.json'),
            'lang' => 'en',
        ],

        'ipgeolocation' => [
            'class' => TorannGeoIPServicesIPGeoLocation::class,
            'secure' => true,
            'key' => env('IPGEOLOCATION_KEY'),
            'continent_path' => storage_path('app/continents.json'),
            'lang' => 'en',
        ],

        'ipdata' => [
            'class'  => TorannGeoIPServicesIPData::class,
            'key'    => env('IPDATA_API_KEY'),
            'secure' => true,
        ],

        'ipfinder' => [
            'class'  => TorannGeoIPServicesIPFinder::class,
            'key'    => env('IPFINDER_API_KEY'),
            'secure' => true,
            'locales' => ['en'],
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Default Cache Driver
    |--------------------------------------------------------------------------
    |
    | Here you may specify the type of caching that should be used
    | by the package.
    |
    | Options:
    |
    |  all  - All location are cached
    |  some - Cache only the requesting user
    |  none - Disable cached
    |
    */

    'cache' => 'all',

    /*
    |--------------------------------------------------------------------------
    | Cache Tags
    |--------------------------------------------------------------------------
    |
    | Cache tags are not supported when using the file or database cache
    | drivers in Laravel. This is done so that only locations can be cleared.
    |
    */

    'cache_tags' => ['torann-geoip-location'],

    /*
    |--------------------------------------------------------------------------
    | Cache Expiration
    |--------------------------------------------------------------------------
    |
    | Define how long cached location are valid.
    |
    */

    'cache_expires' => 30,

    /*
    |--------------------------------------------------------------------------
    | Default Location
    |--------------------------------------------------------------------------
    |
    | Return when a location is not found.
    |
    */

    'default_location' => [
        'ip' => '127.0.0.0',
        'iso_code' => 'US',
        'country' => 'United States',
        'city' => 'New Haven',
        'state' => 'CT',
        'state_name' => 'Connecticut',
        'postal_code' => '06510',
        'lat' => 41.31,
        'lon' => -72.92,
        'timezone' => 'America/New_York',
        'continent' => 'NA',
        'default' => true,
        'currency' => 'USD',
    ],

];

wp-admin login issue with redirect and reauth=1

when i try to access my wp admin dashboard it redirect me to login.php page and it shows blank white screen.
the redirect url is
https://www.ahmedglassworks.com/wp-login.php?redirect_to=https%3A%2F%2Fwww.ahmedglassworks.com%2Fwp-admin%2F&reauth=1

i tried deleting the plugins and recreated the .htaccess file and forced site to shift to default theme and i cleared the cookies and also tried in incognito mood but nothing worked.
although wordpress is logged on my phone previously and it is still working on it but i can’t login or open my dashboard when i try to login on my laptop and any other tab in my phone and it do not work on client device.

How to upload video to bunyy.net using API PHP

I’m trying to upload video to my library on bunny cdn using API but I can’t find how to upload it.
In thier docs you I can’t find how to upload the video only create a title for the video but no upload the video its self.

Here is the API request from the docs

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

$client = new GuzzleHttpClient();

$response = $client->request('PUT', 'https://video.bunnycdn.com/library/libraryId/videos/videoId', [
  'headers' => [
    'accept' => 'application/json',
  ],
]);

echo $response->getBody();

I have found here that you have to create a video first and this ok but the part of uploading the video content is not the same.
You can see they add a link to the docs but its not the same same as in the image as there is a upload video button in the image but in the docs there isn’t
The image from bunny support webste

I cannot save a specific datetime value in mysql database

when i try to update an item i get this error :

IlluminateDatabaseQueryException
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: ‘2023-03-26 02:36:24’ for column ‘posted_at’ at row 1 (SQL: update table_name set posted_at = 2023-03-26 02:36:24, table_name.updated_at = 2023-11-16 10:14:52 where id = 934579)

Column type is timestamp and it’s casted as datetime, never had this issue before, only this value is crashing.

I tried nothing because its a normal datetime string.

php says session not set while it has been set

i have a php script to login, i set a session to store username value in it, when login is successful then it redirects me to another page that is the main page of the site. in this page every time i try to run my code, it returns session is not set. someone help me?
here is my code – login page :

<?php
session_start();
unset($_SESSION['username']);
//error_reporting(0);
$username = filter_var($_POST['username']);
$password = filter_var($_POST['password']);

$login = new Login();
if(isset($_POST['submit'])){
    
    if($login->login($username, $password)){
        $_SESSION['username'] = $_POST['username'];
        header("Location: kartablContent/index.php");
        echo "
             <div class='alert alert-success alert-dismissible fade show'>
    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
    <strong>عملیات موفق</strong> در حال ورود به حساب کاربری ...
  </div>
        ";

        
    }else{
        echo "
                   <div class='alert alert-danger alert-dismissible fade show'>
    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
    <strong>عملیات ناموفق</strong> نام کاربری یا رمز عبور اشتباه است
  </div>
        ";
    }
}


?>

here is my main page code:

<?php
session_start();
if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    echo "Welcome, $username!";
} else {
    echo "Session variable not set.";
}
?>

so every time i get session variable not set and it drives me crazzzyyyyyy…..

i tried every way but did not get a suitable result

How can i access uploaded files in lumen?

I tried lot of methods available on google but nothing work. I searched on google from past few days but still no success. I am trying to upload images using lumen API and it works fine. But i am not able to access those images because images are in storage folder. I also tried commands like ln -s /var/www/storage/app /var/www/public/storage but these commands run only once and i have to run those commands manually everytime that i do not want to do. Please help me to fix this.

 if ($request->hasFile('thumbnail')) {
                $file = $request->file('thumbnail');
                $allowedfileExtension = ['png', 'jpg', 'jpeg'];

                $extension = $file->getClientOriginalExtension();

                $check = in_array($extension, $allowedfileExtension);
                if ($check) {
                    $name = time() . '.' . $file->getClientOriginalExtension();
                    $file->storeAs('images', $name);
                    $thumbnailUrl = url('storage/images/' . $name);

                    $listing->thumbnail = $thumbnailUrl;
                } else {
                    return response()->json(['message' => 'Please upload correct format of image', 'status' => 400], 400);
                }
            }

Any solution appreciated!

Laravel routing to a js script on my server and load that to page

I would like to route a request that looks like this:
https://sub.domain.nl/tracking/MM-123/tracker.js

To my javascript in this directory:
Resources/js/Scrips/tracking/tracker.js

However, it looks like the server/laravel is looking for this script:
https://sub.domain.nl/tracking/MM-123/tracker.js

In the /public folder.

However, I want it load it just like a normal view / page from the server.

My web.php router:

Route::group([], function () {
  Route::get('/tracking/{script}/tracker.js', [TrackingScriptController::class, 'index'])->name('tracking');
});

My TrackingScriptController.php:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesResponse;
use IlluminateSupportFacadesFile;

class TrackingScriptController extends Controller
{
    public function index($script)
    {
        // Construct the path to the script file
        $filePath = resource_path("js/Scripts/Tracking/tracker.js");

        // Check if the file exists
        if (!File::exists($filePath)) {
            // You can return a 404 or some other error if the file is not found
            abort(404, 'Script not found');
        }

        // Read the contents of the file
        $scriptContents = File::get($filePath);

        // Return the contents with the correct Content-Type header
        return Response::make($scriptContents, 200, ['Content-Type' => 'application/javascript']);
    }
}

?>

But the browser keeps giving 404 page not found, in console:

Failed to load resource: the server responded with a status of 404 () tracker.js

So it looks like my laravel app is trying to look for this .js file inside of the public app. When I remove .js from the URL like this:
https://sub.domain.nl/tracking/MM-123/tracker

And my web.php to this:

Route::group([], function () {
  Route::get('/tracking/{script}/tracker.', [TrackingScriptController::class, 'index'])->name('tracking');
});

It works fine.

I’m using Laravel (Breeze starter kit) + Inertia + Vue.

Does anyone have an idea how to fix this? I have no idea unfortunately after trying a lot of different things.

How to prevent coupling between our code and third party libraries?

Imagine we want to use the following library like this:

use GrahamCampbellGitHubGitHubManager;

class Foo
{
    private GitHubManager $github;

    public function __construct(GitHubManager $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->issues()->show('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Does it makes sense to create an interface like:

interface GitHubManagerInterface
{
    public function showIssues(): array;
}

Then implement it and bind the implementation to the interface and use it in my code like the following?

class Foo
{
    private GitHubManagerInterface $github;

    public function __construct(GitHubManagerInterface $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->showIssues('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Or there is a better way to prevent coupling? Or it’s over engineering? 🙂

I’m having trouble with the passthru() function when redirecting stderr to stdout

Could you help me with this strange passthru() behavior?

This code writes the “Division by zero” error to test.log:

passthru('php -r "echo 1/0;" 2>logs/test.log >> logs/test.log');

But this code doesn’t. It writes the error to console:

passthru('php -r "echo 1/0;" 2>&1 >> logs/test.log');

I was expecting that the stderr is redirected also to stdout.
Is this a known issue with passthru?

I’m running this in a CLI script.

How to use Open ai Assistants key in PHP

<?php
require 'vendor/autoload.php';

use GuzzleHttpClient;

function startQuiz() {
    $client = new Client();
    $apiKey = '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'; // Replace with your actual API key

    try {
`so this is my code now how can add my assistans key`
        $response = $client->request('POST', 'https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'model' => 'gpt-4-1106-preview', // Your specific GPT-3.5-turbo model
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
                    ['role' => 'user', 'content' => 'start quiz Francals Highway Code multiple choose']
                ]
            ]
        ]);

        $body = $response->getBody();
        $content = json_decode($body);
        echo $content->choices[0]->message->content;
    } catch (Exception $e) {
        echo 'Error in starting the quiz: ',  $e->getMessage(), "n";
    }
}

startQuiz();

Too many MongoDB connections issue in PHP web services

We have written web services/ callbacks in Laravel/Lumen for Azure graph APIs. Our web services are hosted in AWS ASG with Apache and PHP-FPM on the server. Minimum pool in ASG is 4 and max is set at 10. For database we are using MongoDB that also hosted in AWS parallel to Lumen APIs. We are using jenssegers/mongodb package in Lumen for database connection/queries. We are receiving huge number of requests from Azure per second. Our project is related to email/mail boxes so traffic/requests are coming continuously upto ~60K/sec.

The problem is our MongoDB connections are increasing rapidly reaching upto 40K. How to manage these connections? As MongoDB connection limit is 50K and we are also expecting increase in traffic from Azure in future with product expansion.

Earlier PHP-FPM was setup with dynamic PM, we have now changed it to ondemand PM with following configs

pm = ondemand
pm.max_children = 100  
pm.process_idle_timeout = 20s;  
pm.min_spare_servers = 10  
pm.max_spare_servers = 20  
pm.start_servers = 10;

This has decrease connection count but not significantly (around ~5K).