Hashing an image “expensive”?

I’m considering only allowing unique images to save storage space, and, to do this I will:

  1. Hash image on upload
  2. Check a database of images, to see if there is a hash match.

I have concerns though of hashing uploaded images slowing down the application.

Is this a recommended practice? Or do people tend to allow duplicate image uploads as storage is cheap?

Google Analytics Data API v1 (impressions) data does not match with GA4 Analytics / Ads data

I want to retrieve Google Ads related data (impressions, clicks, cost) from a GA4 Google Analytics property (linked to my Google Ads account) using the new Google Analytics Data API v1. My code works, but it returns very different numbers compared to what I see in Google Analytics or Google Ads. For example for the week of 15-21 May:

My code using GA Data API v1 Google Analytics Google Ads
Impressions 2472 ? 4.17K
Clicks 324 339 353
Cost 92.3 95.7 98.23

As you can see there is a very big difference especially for the number of impressions. (Unfortunately I could not find a way to check this number in Analytics for a large number of campaigns as “Exploration reports” only work for 10 campaigns or so.) I see similar differences for all other weeks.

Please see below my php code retrieving the data from Analytics. What am I doing wrong that I’m not getting the same (impression) numbers as in Google Analytics/Ads?

public function handle()
{

    $downloader = new GNGGA4DataDownloader();
    $results = $downloader->run('2023-05-15', '2023-05-21', config('services.google-analytics.propertyID'));

    $ti = 0;
    $tcl = 0;
    $tco = 0; 

    foreach ($results as $r) {
        $ti += $r->impressions;
        $tcl += $r->clicks;
        $tco += $r->cost;
    }

    dd($results, 'impressions: ' . $ti, 'clicks: ' . $tcl, 'cost: ' . $tco);

}

<?php
namespace AppGNG;

use GoogleAnalyticsDataV1alphaOrderByDimensionOrderBy;
use GoogleAnalyticsDataV1betaBetaAnalyticsDataClient;
use GoogleAnalyticsDataV1betaDateRange;
use GoogleAnalyticsDataV1betaDimension;
use GoogleAnalyticsDataV1betaMetric;
use GoogleAnalyticsDataV1betaOrderBy;
use stdClass;

//This is the current API to download Analytics data from GA4 properties.
class GNGGA4DataDownloader 
{

    private function downloadData($startDate, $endDate, $ga_propertyID) {

        $path = storage_path('app/GA/GNG GA4 API-XXX.json');
        putenv("GOOGLE_APPLICATION_CREDENTIALS=" . $path);

        $client = new BetaAnalyticsDataClient();

        // Make an API call.
        $response = $client->runReport([
            'property' => 'properties/' . $ga_propertyID,
            'dateRanges' => [
                new DateRange([
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                ]),
            ],
            'dimensions' => [
                new Dimension(['name' => 'sessionCampaignName']),
                //new Dimension(['name' => 'sessionGoogleAdsCampaignName']),
                
                new Dimension(['name' => 'year']),
                new Dimension(['name' => 'isoWeek']),
            ],
            'metrics' => [
                new Metric(['name' => 'advertiserAdImpressions']), 
                new Metric(['name' => 'advertiserAdClicks']), 
                new Metric(['name' => 'advertiserAdCost']), 
                
            ],
            'orderBys' => [
                new OrderBy([
                    'dimension' => new OrderByDimensionOrderBy([
                        'dimension_name' => 'sessionCampaignName', 
                        //'dimension_name' => 'sessionGoogleAdsCampaignName', 
                        'order_type' => OrderByDimensionOrderByOrderType::ALPHANUMERIC
                    ]),
                    'desc' => false,
                ]),
            ],
            'keepEmptyRows' => true,  
            
        ]);

        return $response;


    }

    private function extractResults($response) {

        $results = array();

        foreach ($response->getRows() as $row) {

            $d = new stdClass();

            $d->campaignCode = $row->getDimensionValues()[0]->getValue();
            $d->isoYear = $row->getDimensionValues()[1]->getValue();
            $d->isoWeek = $row->getDimensionValues()[2]->getValue();
            $d->impressions = $row->getMetricValues()[0]->getValue();
            $d->clicks = $row->getMetricValues()[1]->getValue();
            $d->cost = $row->getMetricValues()[2]->getValue();
         
            array_push($results, $d);

        }

        return $results;

    }
    
    function run($startDate, $endDate, $gaPropertyID) {

        $response = $this->downloadData($startDate, $endDate, $gaPropertyID);

        $results = $this->extractResults($response);

        return $results;

    }

}    

 

PHP error “Failed to open stream: Permission denied”

I am not a programmer unfortunately, and I was extensively browsing to find a solution to my problem – without success. I hope you might help me.
I want to create a webpage locally using Windows, Joomla4, XAMPP & PHP8. The installation worked fine and I installed a component to add content (JoomShaper SP PageBuilder Lite, SPPB). However, an article that includes SPPB-content cannot be displayed. This is the error from Apache Error Log:

require_once(E:xampphtdocscomponentscom_sppagebuilderparser./../helpers/helper.php): Failed to open stream: Permission denied in E:xampphtdocscomponentscom_sppagebuilderparseraddon-parser.php on line 20, referer: http://localhost/administrator/index.php?option=com_menus&view=items&menutype=mainmenu

I tried the following without success so far:

  1. changing access rights of the helper.php and addon-parser.php files and all parent directories to 775
  2. include ini_set('include_path', '.;E:xamppphpPEAR'); in the helper.php

I do not know what else to do or where the problem is located then.

Thanks for any help, greatly appreciated!
Bernd

Error validation does not appear CodeIgniter 4

I have a problem with the validation error for CodeIgniter 4, when i click the button, the error message doesn’t appear at all, is there something wrong? Please help, I appreciate it
Below is the code:

Controller

public function Daftar()
    {
        // Jika tervalidasi
        if ($this->validate([
            'nim' => [
                'label' => 'NIM',
                'rules' => 'required|is_unique[tbl_anggota.nim]',
                'errors' => [
                    'required' => '{field} Masih Kosong!',
                    'is_unique' => '{field} NIM Sudah Terdaftar!',
                ]
            ],
            'nama' => [
                'label' => 'Nama',
                'rules' => 'required',
                'errors' => [
                    'required' => '{field} Masih Kosong!',
                ]
            ],
            'password' => [
                'label' => 'Password',
                'rules' => 'required',
                'errors' => [
                    'required' => '{field} Masih Kosong!',
                ]
            ],
            'ulangi_password' => [
                'label' => 'Ulangi Password',
                'rules' => 'required|matches[password]',
                'errors' => [
                    'required' => '{field} Masih Kosong!',
                    'matches' => '{field} Password Tidak Sama!',
                ]
            ],
        ])) {
        }  else {
             // Jika tidak tervalidasi
            session()->getFlashdata('errors', ConfigServices::validation()->getErrors());
            return redirect()->to(base_url('Auth/Login'))->withInput('validation', ConfigServices::validation());
        }
    }

View

<?php
            // Notifikasi Error
            $errors = session()->getFlashdata('errors');
            if (!empty($errors)) { ?>
                <div class="alert alert-danger" role="alert">
                    <h4>Periksa Entry Form</h4>
                    <ul>
                        <?php foreach ($errors as $key => $error) { ?>
                            <li><?= esc($error) ?></li>
                        <?php } ?>
                    </ul>
                </div>
            <?php } ?>

Thank you so much!!

I’ve tried look it up but still it’s not working

I cant work out how to display Sql query results on my page

Very new to SQL/PHP.
I have a query statement with the following which shows all those records in Category that are equal to 1 to 12.

$dbHOST = 'mydbpath';
    $dbNAME = 'mydbName';
    $dbUSER = 'admin';
    $dbPASS = '12345678';
    $pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection

    $stmt = $pdo->prepare("SELECT * FROM category WHERE cat_id >= 1 AND cat_id <= 12");
    //you should never use *, just call each field name you are going to use

    $stmt->execute(); // run the statement
    $arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array

    print_r($arr); // print all array items, unformatted
    ?>

I have tested in a program called db Forge Query Builder and I get the results I require from the SLQ query.

The part I can’t work out is what to put on my page to see the array results, at the moment I have the following which returns no results, where am I going wrong?

<?php echo print_r($arr[cat_name]);  ?>

WordPress – str_replace() not working with the_category(‘, ‘)

In WordPress, this works fine to retrieve my article category

the_category(', ');

It returns

<a href="/ghost-stories/" rel="category tag">Ghost Stories</a>

But its not working with str_replace

echo str_replace("ghost-stories", "blog", the_category(', '));

I want it to return

<a href="/blog/" rel="category tag">Ghost Stories</a>

It’s not making any change

Laravel Sanctum: Shifting user credentials – after some time the user logged in is now another user

When we do some user testing on our web app after some testing the user logged in shifts from the original to another one the other user does not have access to.

We checked the authentication part and our lead developer said this:

  • “The issue is not on the authentication part as it follows Laravel standard as per documentation”
  • “Session Handling – this no longer apply since the authentication is token-based”

Our tech stack is – Laravel Sanctum, Token-based authentication

getting port 443 after 127226 ms: Couldn’t connect to server

I am integrating the third party api but getting port 443 after 127226 ms: Couldn’t connect to server

GuzzleHttpExceptionConnectException
cURL error 28: Failed to connect to xxxxx.xx port 443 after 127226 ms: Couldn't connect to server (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://xxxxxxxxx/api/v1/service/recharge/recharge/getoperator

this is the full error message i get. I tried contacting the server provider they told me to white list the api ip. I did. but not working. it works fine in the POSTMAN.

How can I make a select and insert query thread safe without unique indexes?

I need to check if a row exists, and if it does – update some column, and if not, create a new record.

But the queries I am using are not thread safe, as I do not have unique indexes on that table because I can create new rows with same values based on the last_update value:

$row = DB::table('some_table')
    ->where('last_update', '>=', now()->subMinutes(5))
    ->where('user_id', '=', $user_id)
    ->where('comment_type', '=', $comment_type)
    ->first();

if ($row === null) {
     // record not found, create new
     DB::table('some_table')->insert([
        'user_id' => $user_id,        
        'comment_type' => $user_id,     
        'created_at' => $user_id,     
        'last_update' => $user_id,     
    ]);
} else {
     // record found, update existing
     DB::table('some_table')
          ->where('id', '=', $row->id)
          ->update(['last_update' => now()]);     
}

Is there a way to make it more thread safe?

Edit: What I mean by safe is that, in the above code, there might be a situation where 2 threads reach the code and almost the same time, both of them getting null value for $row and then they will continue to insert a new row, ending up with two records

Apktool on PHP exec() failed to execute completely

Im trying to decompile and recompile an APK using apktool by executing it using exec() function in PHP. im able to decompile it using this code:

exec('cd apk && export PATH=$PATH:/opt/homebrew/bin && apktool d appname.apk', $output, $result_code);

I have to do some directory change and PATH changes in order to use the apktool but the decompilation went fine and i can see all the output files and folder.

When it comes to recompiling the apk, the apktool kinda stop halfway and no output files were produced. this is the code

exec('export PATH=$PATH:/opt/homebrew/bin && cd uploads && apktool b appname.apk', $output, $result_code);
echo "<pre>";
var_dump($output);
echo "</pre>";

this is the output of var_dump:

array(4) {
  [0]=>
  string(22) "I: Using Apktool 2.7.0"
  [1]=>
  string(42) "I: Checking whether sources has changed..."
  [2]=>
  string(44) "I: Checking whether resources has changed..."
  [3]=>
  string(24) "I: Building resources..."
}

From the var_dump output, i can see that the process didn’t finish and got terminated halfway. expected output is something like this:

I: Using Apktool 2.7.0
I: Checking whether sources has changed...
I: Smaling smali folder into classes.dex...
I: Checking whether resources has changed...
I: Building resources...
I: Building apk file...
I: Copying unknown files/dir...
I: Built apk into: appname/dist/appname.apk

Im using PHP 7.4.9 on macOS Monterey. I think it might not have anything to do with permission and owner since i could decompile and during the decompilation the apktool able to generate files and folders. but i could be wrong though. Please help

PHP 8.1 / Magenot 2.4.4 / Deprecated Functionality Error

please help me to understand this error:

Deprecated Functionality: Optional parameter $data declared before required parameter $registry is implicitly treated as a required parameter in Autocomplete.php on line 31

Here is this snipet of code:

public function __construct(Context $context, array $data = [], Registry $registry)

I tried to solve it like this:

public function __construct(Context $context, array $data = [], Registry $registry = [])

but got error:

Fatal error: Cannot use array as default value for parameter $registry

Undefined variable $categories

I have a problem with my code, I’m very new to this, so I’m having trouble finding the problem.

I want my categories to be displayed, so I can select one and assign it to the keyword, the site tells me that my categories are not defined


public function store(Request $request)
{

    $motsCles = Mot_Cles::all();
    $categories = Categories::all(); 

    
    $request->validate([
        'mot' => 'required|string|max:255',
    ]);


    
    $motCle = Mot_cles::create([
        'mot' => $request->input('mot'),
    ]);

    $category = Categories::find($request->category);
    $motCle->categories()->attach($category);



    return view('Mots_Cles', compact('categories'));
    return view('Mots_Cles', compact('motsCles'));


    event(new Registered($motCle));
    return redirect(RouteServiceProvider::HOME);
}

I tried to define the categories but everything seems to be fine, I wonder if it has something to do with the routes

Laravel/QuickAdminPanel: “the separation symbol could not be found” message when i try to confirm my email address

I activated the email confirmation in my Laravel project, when i receive the email and click the button the site return me an exception.
The code line interested is in the User Class:

<?php

namespace AppModels;

use CarbonCarbon;
use DateTimeInterface;
use Hash;
use IlluminateAuthNotificationsResetPassword;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentSoftDeletes;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use SoftDeletes, Notifiable, HasFactory;

    public $table = 'users';

    protected $hidden = [
        'remember_token',
        'password',
    ];

    protected $dates = [
        'email_verified_at',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    protected $fillable = [
        'name',
        'email',
        'email_verified_at',
        'password',
        'remember_token',
        'created_at',
        'updated_at',
        'deleted_at',
        'firstname',
        'lastname',
        'address',
        'postcode',
        'place',
        'company',
        'phone',
        'mobile',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getIsAdminAttribute()
    {
        return $this->roles()->where('id', 1)->exists();
    }


    public function getEmailVerifiedAtAttribute($value)
    {
        return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('panel.date_format') . ' ' . config('panel.time_format')) : null;
    }

    public function setEmailVerifiedAtAttribute($value)
    {
        $this->attributes['email_verified_at'] = $value ? Carbon::createFromFormat(config('panel.date_format') . ' ' . config('panel.time_format'), $value)->format('Y-m-d H:i:s') : null;
    }

    public function setPasswordAttribute($input)
    {
        if ($input) {
            $this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
        }
    }

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPassword($token));
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

laravel exception

The problem is in the line 68:

public function setEmailVerifiedAtAttribute($value)
{
        $this->attributes['email_verified_at'] = $value ? Carbon::createFromFormat(config('panel.date_format') . ' ' . config('panel.time_format'), $value)->format('Y-m-d H:i:s') : null;
}

I try to change the timezone in the app.php but the problem still remain.
In the DB the user is registred, and can access to the website, but the field “email_verified_at” is null.