Laravel calculating totals based on hasMany relationship

I have an Affiliate model with a AffiliateSummaryStat statistic model which contains aggregated totals for each hour of the day and linked by affiliate_id. I need to be able to return a single AffiliateSummaryStat but with the sum of each model. How can I achieve this?

Here’s my relationship right now, this is my Affiliate model:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use IlluminateSupportFacadesCache;

class Affiliate extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'affiliates';

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'allow_submission' => 'boolean',
        'is_favourited' => 'boolean',
        'is_default' => 'boolean',
        'is_enabled' => 'boolean',
        'last_used_at' => 'datetime',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'api_key',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'is_deleting',
    ];

    /**
     * Determine if we're editing the model
     */
    public function getIsDeletingAttribute(): bool
    {
        return false;
    }

    /**
     * Get the affiliate summary stats
     */
    public function affiliate_summary_stats()
    {
        return $this->hasMany(AffiliateSummaryStat::class);
    }

    /**
     * Get the commissions for the affiliate
     */
    public function commissions()
    {
        return $this->hasMany(Commission::class);
    }

    /**
     * Get the affiliate products for this model.
     */
    public function products()
    {
        return $this->hasMany(AffiliateProduct::class);
    }

    /**
     * Get the splits for this affiliate
     */
    public function splits()
    {
        return $this->hasMany(AffiliateSplit::class);
    }

    /**
     * Get the applications for this affiliate
     */
    public function applications()
    {
        return $this->hasMany(Application::class);
    }

    /**
     * Get the company that owns the model.
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the user that owns the model.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Bootstrap any application services.
     */
    public static function boot()
    {
        parent::boot();

        // on create
        static::created(function ($model) {
            Cache::tags('affiliates')->flush();
        });

        // on update
        static::updated(function ($model) {
            Cache::tags('affiliates')->flush();
        });
    }
}

And is used in my controller:

$report = Affiliate::with([
    'affiliate_summary_stats'
])->select([
    'id', 'aff_id', 'description', 'last_used_at'
])->get();

MY current output:

{
    "model": [
        {
            "id": 1,
            "aff_id": "aff107",
            "description": "Default system affiliate",
            "last_used_at": null,
            "is_deleting": false,
            "affiliate_summary_stats": [
                {
                    "id": 1,
                    "affiliate_id": 1,
                    "brand": null,
                    "campaign": "B",
                    "total_sessions": 2,
                    "total_submits": 0,
                    "total_leads": 0,
                    "total_accepted": 0,
                    "total_declined": 0,
                    "total_redirected": 0,
                    "logged_at": "2023-03-21T08:00:00.000000Z",
                    "created_at": "2023-03-21T08:47:33.000000Z",
                    "updated_at": "2023-03-21T08:47:33.000000Z",
                    "total_sessions_formatted": "2",
                    "total_submits_formatted": "0",
                    "total_leads_formatted": "0",
                    "total_accepted_formatted": "0",
                    "total_declined_formatted": "0",
                    "total_redirected_formatted": "0",
                    "conversion_rate": 0,
                    "conversion_rate_formatted": "0",
                    "conversion_rate_formatted_with_symbol": "0%"
                },
                {
                    "id": 2,
                    "affiliate_id": 1,
                    "brand": null,
                    "campaign": "A",
                    "total_sessions": 2,
                    "total_submits": 0,
                    "total_leads": 0,
                    "total_accepted": 0,
                    "total_declined": 0,
                    "total_redirected": 0,
                    "logged_at": "2023-03-21T08:00:00.000000Z",
                    "created_at": "2023-03-21T08:47:36.000000Z",
                    "updated_at": "2023-03-21T08:47:36.000000Z",
                    "total_sessions_formatted": "2",
                    "total_submits_formatted": "0",
                    "total_leads_formatted": "0",
                    "total_accepted_formatted": "0",
                    "total_declined_formatted": "0",
                    "total_redirected_formatted": "0",
                    "conversion_rate": 0,
                    "conversion_rate_formatted": "0",
                    "conversion_rate_formatted_with_symbol": "0%"
                },
                {
                    "id": 3,
                    "affiliate_id": 1,
                    "brand": null,
                    "campaign": null,
                    "total_sessions": 3,
                    "total_submits": 3,
                    "total_leads": 3,
                    "total_accepted": 3,
                    "total_declined": 0,
                    "total_redirected": 0,
                    "logged_at": "2023-03-21T08:00:00.000000Z",
                    "created_at": "2023-03-21T08:47:39.000000Z",
                    "updated_at": "2023-03-21T08:56:04.000000Z",
                    "total_sessions_formatted": "3",
                    "total_submits_formatted": "3",
                    "total_leads_formatted": "3",
                    "total_accepted_formatted": "3",
                    "total_declined_formatted": "0",
                    "total_redirected_formatted": "0",
                    "conversion_rate": 100,
                    "conversion_rate_formatted": "100.00",
                    "conversion_rate_formatted_with_symbol": "100.00%"
                },
                {
                    "id": 5,
                    "affiliate_id": 1,
                    "brand": null,
                    "campaign": "A",
                    "total_sessions": 2,
                    "total_submits": 0,
                    "total_leads": 0,
                    "total_accepted": 0,
                    "total_declined": 0,
                    "total_redirected": 0,
                    "logged_at": "2023-03-21T08:00:00.000000Z",
                    "created_at": "2023-03-21T08:47:36.000000Z",
                    "updated_at": "2023-03-21T08:47:36.000000Z",
                    "total_sessions_formatted": "2",
                    "total_submits_formatted": "0",
                    "total_leads_formatted": "0",
                    "total_accepted_formatted": "0",
                    "total_declined_formatted": "0",
                    "total_redirected_formatted": "0",
                    "conversion_rate": 0,
                    "conversion_rate_formatted": "0",
                    "conversion_rate_formatted_with_symbol": "0%"
                }
            ]
        },
        {
            "id": 2,
            "aff_id": "aff4000",
            "description": "Old",
            "last_used_at": null,
            "is_deleting": false,
            "affiliate_summary_stats": []
        }
    ]
}

How to change the date format from 11/01/2011 to 11 Jan 2011? [duplicate]

Currently I am using the date with code toDateString() and it is showing the exact result like in the title, 11/01/2011. I want to change the month, 01 to 11 Jan 2011. I’ve tried to use toLocaleDateString() but when I use that it is throwing an error. How can I fix this ? Below are my code,

    public function toArray($request)
    {
        return array_merge(parent::toArray($request), [
            'timeslots' => $this->whenLoaded(
                'timeslots',
                fn () => $this->timeslots->map(fn (AssetTimeslot $assetTimeslot) => [
                    'id' => $assetTimeslot->id,
                    'name' => $assetTimeslot->name,
                    'date' => $assetTimeslot->pivot->date?->toDateString(),
                    'start_time' => $assetTimeslot->timeslot ? $assetTimeslot->timeslot->start_time : '',
                    'end_time' => $assetTimeslot->timeslot ? $assetTimeslot->timeslot->end_time : '',
                ])->groupBy('date')
            ),
        ]);
    }
}

How do i make the user enter the data from php file, send it to the python file and lastly displaying the results from python in the browser?

I tried this but its not displaying the results

————-….. hardware.php……… —————-


<!DOCTYPE html>
<html>
<head>
    <title>Hardware Reliability</title>
    
</head>
<body>
    <h1>Enter the input data</h1>
    <form action="hardwareResult.php" method="post">
        <label for="x">Enter values of x (separated by commas):</label><br/>
        <input type="text" name="x"><br/>
        <label for="y">Enter values of y (separated by commas):</label><br/>
        <input type="text" name="y"><br/><br/>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

———-………..hardwareResult.php…………….————


<?php
header('Content-type: text/plain; charset=utf-8');
// get user input
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $x = explode(",", $_POST['x']);
  $y = explode(",", $_POST['y']);
} else {
  // default values
  $x = [12,16,71,99,45,27,80,58,4,50];
  $y = [56,22,37,78,83,55,70,94,12,40];
}

// prepare input data for Python script
$input_data = array(
    'x' => $x,
    'y' => $y
);

// encode input data as JSON string
$input_json = json_encode($input_data);

// call Python script with input data as parameter
$output = shell_exec("python hardware.py '$input_json'");

// parse output from Python script
$output_data = json_decode($output, true);

// check for errors in output
if ($output_data === null) {
  echo "There was an error running the Python script.";
  exit();
}

// display results
echo "<h1>Results</h1>";
echo "<p>Hardware failure rate at t=2000 is: " . $output_data['hardware_failure_rate'] . "</p>";
echo "<p>Hardware mean life is: " . $output_data['hardware_mean_life'] . "</p>";
echo "<p>Hardware reliability at t=2000 is: " . $output_data['hardware_reliability'] . "</p>";

?>

—————-…………hardware.py…………——————–

#!C:UsersVincentAppDataLocalProgramsPythonPython310python.exe


import math
import json
import sys

def hardware_failure_rate(t, beta, eta, failure_time):
    return beta/eta*((t-failure_time)/eta)**(beta-1)

def hardware_mean_life(beta, eta, failure_time):
    return failure_time+eta*(1/beta + 1)

def hardware_reliability(t, beta, eta, failure_time):
    return math.exp(-(t-failure_time)/eta*beta)

if __name__ == "__main__":
    try:
        input_json = sys.argv[1]
        input_data = json.loads(input_json)

        x = input_data['x']
        y = input_data['y']
        xy = []
        for i, val in enumerate(x):
            xy.append(x[i]*y[i])
        x_sqrt = [i**2 for i in x]
        n = len(x)
        w = (n*sum(xy) - sum(x)*sum(y))/(n*sum(x_sqrt) - sum(x)**2)
        b = (sum(y) - w*sum(x))/n

        beta = -w
        eta = math.exp(b/beta)
        failure_time = min(x)

        t = 2000
        hardware_failure_rate = hardware_failure_rate(t, beta, eta, failure_time)
        hardware_mean_life = hardware_mean_life(beta, eta, failure_time)
        hardware_reliability = hardware_reliability(t, beta, eta, failure_time)
        output_data = {'hardware_failure_rate': hardware_failure_rate, 'hardware_mean_life': hardware_mean_life, 'hardware_reliability': hardware_reliability}
        output_json = json.dumps(output_data)
        print(output_json)

    except Exception as e:
        print("Error: {}".format(str(e)))

I need to display the results in the browser but the it keeps displaying “There was an error running the Python script.”

AJAX POST method returning ‘Undefined array key’

I’m working on a simple AJAX call to retrieve API data from the Geonames website, but I keep getting this error:

Warning: Undefined array key “geonames” in
C:xampphtdocstasklibsphpocean.php on line 25
{“status”:{“code”:”200″,”name”:”ok”,”description”:”success”,”returnedIn”:”72
ms”},”data”:null}

As you can see, the status code is returning okay but I can’t access the data in the array and keep getting the null response.

Javascript:

    $('#oeanBtnRun').click(function() {

        $.ajax({
            url: "Oceanlibs/php/ocean.php",
            type: 'POST',
            dataType: 'json',
            data: {
                lat: $('#selLat').val(),
                lng: $('#selLng').val(),
            },
            success: function(result) {

                console.log(JSON.stringify(result));

                if (result.status.name == "ok") {

                    $('#results').html(result['data']);

                }
            
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR, textStatus, errorThrown);
            }
        }); 
    
    });

html:

<tr>
     <td>2. Get Ocean</td>
     <td>
    <label>Latitude: </label><input id="selLat" type="number"></input>
    <label>Longitude: </label><input id="selLng" type="number"></input>
     </td>
     <td><button class="oceanBtnRun">Run</button></td>
</tr>

php:

<?php

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    $url='http://api.geonames.org/neighbourhoodJSON?formatted=true&lat=' . $_REQUEST['lat'] . '&lng=' . $_REQUEST['lng'] .'&username=kerriemcivor92&style=full';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    
    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);    

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];
    

    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 

?>

I’ve tried changing

$output['data'] = $decode['geonames'];

to various forms with zero success.

Any ideas would be greatly appreciated!

Php is showing database passwords publicly [duplicate]

(just for understanding)

I have a very simple php code used to conncet to the database:

<?php
$servername = "localhost";
$username = "USER";
$password = "PASS";
$database = "DATABASE";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

It is working great with no problems, but when I manually stop mysql service from XAMMP control panel, the browser is throwing an error including the credentials:

Fatal error: Uncaught mysqli_sql_exception: No connection could be made because the target machine actively refused it in C:xampphtdocsmirandafiles.php:36 Stack trace: #0 C:xampphtdocsmirandafiles.php(36): mysqli_connect(‘localhost’, ‘USER’, ‘PASS’, ‘DATABASE’) #1 {main} thrown in`

I am trying to understand why PHP is showing my credentials when mysql is stopped.

I have tried modifying if statement like this: (just removing . mysqli_connect_error())

if (!$conn) {
  die("Connection failed: ");
}
echo "Connected successfully";

hoping that php will not reveal my credentials anymore.
I need help to understand why this is happening and the mechanism of work.

Why Auth::user()->is_admin; returns false in Laravel?

This doesn’t work (nothing is displayed):

echo Auth::user()->is_admin;

This, however, works fine (the column value is displayed):

echo DB::table('users')->where('id', Auth::id())->value('is_admin');

When having just echo Auth::user() then this is displayed:
{“id”:19,”name”:”peeter”,”email”:”[email protected]”,”is_admin”:false}

As you can see it returns all the other column values just fine but “is_admin” column value is for some reason “false”, no matter what the column value or type is set in phpmyadmin.

For example this is my full code that I put in web.php to test this:

Route::get('/testing', function(){
    echo Auth::user()->is_admin;
    echo DB::table('users')->where('id', auth::id())->value('is_admin');
});

I expected echo Auth::user()->is_admin; or echo Auth::user() to return the value of the “is_admin” column instead of displaying nothing or FALSE.

PHP8.1 with xDebug – symbol not found in flat namespace ‘_zend_get_parameters_array_ex’

System Information

  • macOS 13.2.1 (22D68) (Intel Processor)
  • php versions installed via homebrew
  • xDebug installed via pecl
  • xDebug Version 3.2.0 (should be supported -> see https://xdebug.org/docs/compat)

Error Description

I am trying to get xDebug running on php 8.1.

While it works fine for php 8.2

PHP 8.2.4 (cli) (built: Mar 16 2023 16:46:52) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.4, Copyright (c) Zend Technologies
    with Xdebug v3.2.0, Copyright (c) 2002-2022, by Derick Rethans
    with Zend OPcache v8.2.4, Copyright (c), by Zend Technologies

I get the following error message when using it with php8.1

Failed loading /usr/local/lib/php/pecl/20220829/xdebug.so:  dlopen(/usr/local/lib/php/pecl/20220829/xdebug.so, 0x0009): symbol not found in flat namespace '_zend_get_parameters_array_ex'
PHP 8.1.17 (cli) (built: Mar 16 2023 13:19:00) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.17, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.17, Copyright (c), by Zend Technologies

The following line has been added to the php.ini.

zend_extension="/usr/local/lib/php/pecl/20220829/xdebug.so"

What I have tried/done

  • Reinstalling xDebug (pecl uninstall and then install)
  • using extension=xdebug.so (Unable to load dynamic library – which works on 8.2)
  • brew update / upgrade

Does someone have any idea what else I could try?

Same login on multiple different Laravel projects

I have many projects as subdomains for maindomain:
(haderegypt.com, doctors.haderegypt.com, treats.haderegypt.com)
i need to share login between them like for instance if i logged on examble.com so i logged on site1.examble.com as well and vice versa

i tried already many method that they published on stackoverflow, laracasts but unfortunately not work for me, i tried this method with all his details:
pic-method

for now i test the method between (haderegypt.com, doctors.haderegypt.com)
but i dont know really what the messing part that made it failed
all project has already get and send data from same database (ecom1_hader) on table (users)
and also both of them use same name of cookie and session and the same app_name and also use same APP_KEY
but after i did all this steps and make config:clear, config:cache i found login on each of them work well but once i open just the another domain both of them make logout for examble now i logged on examble.com once i open site1.examble.com the examble.com make logout by force i dont know why

and these are the content of Files (ENV, session.php, auth.php) of each project

project haderegypt.com (auth.php):

return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => AppUser::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
        'throttle' => 60,
    ],
],

/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/

'password_timeout' => 10800,

];

project haderegypt.com (session.php):

use IlluminateSupportStr;

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "dynamodb", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => env('SESSION_LIFETIME', 12000),

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => env('SESSION_CONNECTION', null),

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/

'store' => env('SESSION_STORE', null),

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

// 'cookie' => env(
//     'SESSION_COOKIE',
//     Str::slug(env('APP_NAME', 'HaderEgypt'), '_').'_session'
// ),
'cookie' => 'HaderEgypt_cookie',
// 'cookie' => env('SESSION_COOKIE', 'session_sharing_application_session'),

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

'domain' => env('SESSION_DOMAIN', null),
// 'domain' => env('SESSION_DOMAIN', 'haderegypt.com'),
// 'domain' => '.haderegypt.com',

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => env('SESSION_SECURE_COOKIE'),

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/

'http_only' => true,

/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/

// 'same_site' => 'https://haderegypt.com',
'same_site' => 'lax',

];

project haderegypt.com (ENV):

APP_NAME=HaderEgypt
APP_ENV=local
APP_KEY=base64:z00Bai5cRhY++I3h4ad4w8REeU1YhOlSzXWo93P2UO8=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ecom1_hader
DB_USERNAME=ecom1_user_test
DB_PASSWORD=fisjsja9QA212

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=30000

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mail.haderegypt.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=DSOKDIOs929sA92
MAIL_ENCRYPTION=ssl
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

project doctors.haderegypt.com (auth.php):

<?php

return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => AppUser::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
        'throttle' => 60,
    ],
],

/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/

'password_timeout' => 10800,

];

Blockquote

project doctors.haderegypt.com (session.php):

<?php

use IlluminateSupportStr;

return [

/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
|            "memcached", "redis", "dynamodb", "array"
|
*/

'driver' => env('SESSION_DRIVER', 'file'),

/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/

'lifetime' => env('SESSION_LIFETIME', 12000),

'expire_on_close' => false,

/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/

'encrypt' => false,

/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/

'files' => storage_path('framework/sessions'),

/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/

'connection' => env('SESSION_CONNECTION', null),

/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/

'table' => 'sessions',

/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/

'store' => env('SESSION_STORE', null),

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => [2, 100],

/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/

// 'cookie' => env(
//     'SESSION_COOKIE',
//     Str::slug(env('APP_NAME', 'HaderEgypt'), '_').'_session'
// ),
'cookie' => 'HaderEgypt_cookie',
// 'cookie' => env('SESSION_COOKIE', 'session_sharing_application_session'),

/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/

'path' => '/',

/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/

// 'domain' => env('SESSION_DOMAIN', null),
// 'domain' => env('SESSION_DOMAIN', 'haderegypt.com'),
'domain' => '.haderegypt.com',

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => env('SESSION_SECURE_COOKIE'),

/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/

'http_only' => true,

/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/

// 'same_site' => 'https://haderegypt.com',
'same_site' => 'lax',

];

project doctors.haderegypt.com (ENV):

APP_NAME=HaderEgypt
APP_ENV=local
APP_KEY=base64:z00Bai5cRhY++I3h4ad4w8REeU1YhOlSzXWo93P2UO8=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ecom1_hader_clinics
DB_USERNAME=ecom1_user_test
DB_PASSWORD=fisjsja9QA212

DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=ecom1_hader
DB_USERNAME_2=ecom1_user_test
DB_PASSWORD_2=fisjsja9QA212

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=30000

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mail.haderegypt.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=DSOKDIOs929sA92
MAIL_ENCRYPTION=ssl
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

can anyone check what the wrong in my script please

Debugging with Docker PhpStorm and Xdebug – missing .env variables

I am using .env file and docker-compose together with: php:8.2.3-fpm image.
In order for ENV variables to be visible in the PHP script, I’ve had to add: clear_env=no to php-fpm.conf file.

Everything works nicely, however the issue I am having is that when I set up Xdebug from PhpStorm to debug PHP script (using remote SSH interpreter to my Docker FPM container) I can’t see the .env variables.

When I SSH into the container and try to print out the ENV variable, e.g.: php -r 'print getenv("POSTGRES_PASS");' it’s printed correctly. It’s only an issue when running an Xdebug session from the PhpStorm.

When Xdebug session is initiated through browser (XDEBUG_SESSION_START=PHPSTORM) then env variables are available correctly.

I am wondering if there is any PhpStorm or XDebug cli setting which explicitly cleans/ignores environmental variables.
They’re clearly available inside of the container.

Any hints very much appreciated !
Thanks

Undefined variable and bugs [duplicate]

We host our databse on webhost and this happened, we are new to prograaming. We didint know how to fix it. Help is appreciated, thank you so much

Notice: Undefined variable: _SESSION in /storage/ssd3/269/20473269/public_html/E-Request/student/main_header/header.php on line 6

Warning: Cannot modify header information – headers already sent by (output started at /storage/ssd3/269/20473269/public_html/E-Request/student/index.php:1) in /storage/ssd3/269/20473269/public_html/E-Request/student/main_header/header.php on line 7

<?php
    
  include('../init/model/class_model.php');
       session_start();
    if(!(trim($_SESSION['student_id']))){
        header('location:../index.php');
    }

?>

Please dtermine what causes it and how to fix it.

Too many if else in php

I made a program to change data from database tables, each table I named S1_code, S2_code, S3_code etc. in this code i use too much ifelse it makes it look bad

What should I do to make my code better

My if elseif code :

include 'connection.php';

$username = $_SESSION['username'];
$status = $_POST['status'];
$subjct_id = $_POST['subjct_id'];
$code = $_POST['code'];

$i = 1;

// s1
if ($subjct_id == 1) {
    mysqli_query(
        $conn,
        "UPDATE tb_lesson 
        SET s1 = '$status', s1_code = '$code' 
        WHERE username = '$username'"
    );

    // s2
} elseif ($subjct_id == 2) {
    mysqli_query(
        $conn,
        "UPDATE tb_lesson 
        SET s2 = '$status', s2_code = '$code' 
        WHERE username = '$username'"
    );

    // s3
} elseif ($subjct_id == 3) {
    mysqli_query(
        $conn,
        "UPDATE tb_lesson 
        SET s3 = '$status', s3_code = '$code' 
        WHERE username = '$username'"
    );

}
// and many more
(...)

CSRF token mismatch error due to Laravel Sanctum not being able to set CSRF cookie in front end app

I have deployed two apps using https://fly.io/;

  • Laravel (v9) API backend
  • VueJS front end

Both apps are loading fine in the web browser.

The front end uses Laravel’s Sanctum library for authentication.

In the backend codebase, I have the following env values in the fly.toml file:

SANCTUM_STATEFUL_DOMAINS = ‘my-app.fly.dev’

SESSION_DOMAIN = ‘fly.dev’

However in the front end, the call to the endpoint /sanctum/csrf-cookie is failing to set the CSRF cookie needed for subsequent calls to the API. Upon inspecting the browser request header to set the cookies, the following error is given:

This attempt to set a cookie via a set-cookie header was blocked
because its domain attribute was invalid with regards to the current
host URL.

Having tried various different combinations of values for SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN, I am no closer to resolving the issue.

I have it working without issues in my local development environment with the following values:

  • SANCTUM_STATEFUL_DOMAINS=localhost:5173
  • SESSION_DOMAIN=localhost

Appreciate it if anyone can share some guidance on this.

Uploading a directory using phpseclib3

I’m trying to use phpseclib3 to upload a directory and its contents to a remote server. Perhaps its just not possible, but I’ve tried to do the following:

$sftp = new SFTP('ip');
$sftp->login('username', 'password');
$sftp->put('directory/*', 'directory/*', SFTP::SOURCE_LOCAL_FILE);

I’ve also tried without the / and with it, but without the *. Is there a way to easily upload the directory without needing to do it manually? i.e. creating a directory on remote server then looping through local directory uploading each file individually.

I have installed xdebug but it does not debug in vs code shows and nothing in call stack

i have tried many ways to solve this problem but nothing works here is my php.ini file code

[XDebug]
xdebug.mode=debug
xdebug.remote_enable=on
xdebug.start_with_request=yes
xdebug.client_host=host.docker.internal
xdebug.discover_client_host = true
zend_extension = "C:xamppphpextphp_xdebug.dll"

and i have also tried
xdebug.profiler_enable=on

but both have this problem when i run php -v in CMD

Xdebug: [Config] The setting ‘xdebug.remote_enable’ has been renamed, see the upgrading guide at https://xdebug.org/docs/upgrade_guide#changed-xdebug.remote_enable (See: https://xdebug.org/docs/errors#CFG-C-CHANGED)

here is my launch.json file

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Built-in web server",
            "type": "php",
            "request": "launch",
            "runtimeArgs": [
                "-dxdebug.mode=debug",
                "-dxdebug.start_with_request=yes",
                "-S",
                "localhost:0"
            ],
            "program": "C:\xampp\htdocs\todoxampp\todo_db.php",
            "cwd": "${workspaceRoot}",
            "port": 9003,
            "serverReadyAction": {
                "pattern": "Development Server \(http://localhost:([0-9]+)\) started",
                "uriFormat": "http://localhost:%s",
                "action": "openExternally"
            }
        },
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003
        },
        {
            "name": "Listen for Xdebug 2 (Legacy)",
            "type": "php",
            "request": "launch",
            "port": 9000
        },
        {
            "name": "Launch currently open script with Xdebug 2 (Legacy)",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 0,
            "runtimeArgs": [
                "-dxdebug.remote_enable=yes",
                "-dxdebug.remote_autostart=yes"
            ],
            "env": {
                "XDEBUG_CONFIG": "remote_port=${port}"
            }
        },
        {
            "name": "Xdebug Cloud",
            "type": "php",
            "request": "launch",
            "xdebugCloudToken": ""
        },
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceFolder}"
        }
    ],
    "pathMappings": {
        "/var/www/html": "${workspaceFolder}/www",
        "/app": "${workspaceFolder}/app"
    }
}
 

i also upgraded my php and apache version i am using XAMPP
Thank you in advance!

i followed the step by step instructions of installing Xdebug and watched Youtube tutorials but nothing seems to work my variable, watch and call stack are empty and code does not debug