I don’t understand how to solve – Warning: Trying to access array offset on value of type null in [duplicate]

Hi guys can you help me with this error:

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 269

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 269

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 270

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 270

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 271

Warning: Trying to access array offset on value of type null in C:xampphtdocsinnovatiowh_localgestioneutilFunction.php on line 271

Thank you in advance

How to read unseen mails in PHP

I wrote the following code to read mails from my mailbox to program. when i give “ALL” in imap_search i get all the mails. but when i give “SEEN” or “UNSEEN” I always get zero results. I used the php-imap library to fetch mails from the inbox of my email.
I get the results correctly when i use “ALL” in the function imap_search but i zero results when i replace ALL with SEEN or UNSEEN.

MY code:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="style.css">

    <script>
        function getEmails() {
            document.getElementById('dataDivID')
                .style.display = "block";
        }
    </script>
</head>

<body>
    <h2>List Emails from inbox of [email protected] using PHP and IMAP</h2>

    <div id="btnContainer">
        <button class="btn active" onclick="getEmails()">
            <i class="fa fa-bars"></i>Click to get mails
        </button>
    </div>
    <br>
    
    <div id="dataDivID" class="form-container" style="display:none;">
        <?php
            
$host = '{mail.cdit.org:993/ssl}INBOX';

            /* Your gmail credentials */
            $user = '[email protected]';
            $password = 'MYPASSWORD';

            /* Establish a IMAP connection */
            $conn = imap_open($host, $user, $password)
                or die('unable to connect mail.cdit.org: ' . imap_last_error());

            /* Search emails from gmail inbox*/
            $mails = imap_search($conn, 'UNSEEN');

            /* loop through each email id mails are available. */
            if ($mails) {

                /* Mail output variable starts*/
                $mailOutput = '';
                $mailOutput.= '<table><tr><th>Subject </th><th> From </th>
                        <th> Date Time </th> <th> Content </th></tr>';

                /* rsort is used to display the latest emails on top */
                rsort($mails);

                /* For each email */
                foreach ($mails as $email_number) {

                    /* Retrieve specific email information*/
                    $headers = imap_fetch_overview($conn, $email_number, 0);
                    //print_r($headers);echo "<br/>";
                    $header = imap_headerinfo($conn, $email_number);
                    //print_r($header);
                    $from = $header->from;
                    
                    foreach ($from as $id => $object) 
                    {
                    $fromname = $object->personal;
                    $fromaddress = $object->mailbox . "@" . $object->host;
                    }

                    /* Returns a particular section of the body*/
                    //$message = imap_fetchbody($conn, $email_number, '1');

                    /* Check the content type */
                    $contentType = $headers[0]->type;

                    /* Fetch the appropriate section based on content type 
                    $message = ($contentType === 0) ? imap_fetchbody($conn, $email_number, '1') : 
                        imap_fetchbody($conn, $email_number, '1.2');*/

                /* Get the email structure */
                /* Retrieve the email structure */
                $structure = imap_fetchstructure($conn, $email_number);

                /* Check if the email has HTML content */
                $htmlMessage = '';$message='';
                if (isset($structure->parts) && is_array($structure->parts)) {
                    foreach ($structure->parts as $part) {
                        if ($part->subtype === 'HTML') {
                            $htmlMessage = getDecodedContent($conn, $email_number, $part);
                            break;
                        }
                    }
                }

                /* If HTML content is empty or unavailable, fetch the plain text version */
                if (empty($htmlMessage)) {
                    $message = getDecodedContent($conn, $email_number, $structure);
                } else {
                    $message = $htmlMessage;
                }


                    /*$subMessage = substr($message, 0, 150);
                    $finalMessage = trim(quoted_printable_decode($subMessage));*/
                    $finalMessage = getActualContent($message);
                    $mailOutput.= '<div class="row">';

                    /* Gmail MAILS header information */                
                    $mailOutput.= '<td><span class="columnClass">' .
                                $headers[0]->subject . '</span></td> ';
                    $mailOutput.= '<td><span class="columnClass">' .
                                $fromaddress . '</span></td>';
                    $mailOutput.= '<td><span class="columnClass">' .
                                $headers[0]->date . '</span></td>';
                    $mailOutput.= '</div>';

                    /* Mail body is returned */
                    $mailOutput.= '<td><span class="column">' .
                    $finalMessage . '</span></td></tr></div>';
                }// End foreach
                $mailOutput.= '</table>';
                echo $mailOutput;
            }//endif

            /* imap connection is closed */
            imap_close($conn);
            
            /**
 * Get the decoded content from a specific part of the email.
 *
 * @param resource $conn The IMAP connection resource.
 * @param int $email_number The email number.
 * @param object $part The specific part of the email structure.
 * @return string The decoded content.
 */
function getDecodedContent($conn, $email_number, $part) {
    $encoding = $part->encoding;
    $content = '';

    if ($part->type === 0) {
        $content = imap_fetchbody($conn, $email_number, $part->partNumber, FT_PEEK);
    } elseif ($part->type === 1 || $part->type === 2 || $part->type === 3) {
        $content = imap_fetchbody($conn, $email_number, $part->partNumber);
    }

    switch ($encoding) {
        case 1: // BASE64
            $content = base64_decode($content);
            break;
        case 2: // QUOTED-PRINTABLE
            $content = quoted_printable_decode($content);
            break;
        case 3: // 8BIT
        case 4: // 7BIT
        case 5: // BINARY
        default:
            break;
    }

    return $content;
}

function getActualContent($content)
{

$startMarker = 'base64';
$endMarker = '--b1';

$startPos = strpos($content, $startMarker);
if ($startPos !== false) {
    $startPos = strpos($content, PHP_EOL, $startPos) + strlen(PHP_EOL);
    $endPos = strpos($content, $endMarker, $startPos);
    if ($endPos !== false) {
        $substring = substr($content, $startPos, $endPos - $startPos);
        //echo $substring;
    }
}

return base64_decode($substring);

}


?>
    </div>
</body>

</html>

Please give me the correct code to get results of read/unread mails.

PHP Limit words breaks div in string

I use the following php function to limit word length:

function limit_words($phrase, $max_words) {
   $phrase_array = explode(' ',$phrase);

   if(count($phrase_array) > $max_words && $max_words > 0)
      $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';

   return $phrase;
}

No say I have a string that contains a div or span class e.g.

$string = 'I went to the shop to buy a <span class="highlight">lollipop</span>';

echo limit_words($string,10);

results in:

I went to the shop to buy a <span class="highlight">lollipop

and it’s missing the last div closer </span>

This some times results in messing up my content futher down, is there away to ensure it doesnt cut of the closer tag before it limits the string?

Many thanks

swagger-php response array of objects using attributes

Just learning to use attributes to describe function parameters and responses. I’m trying to describe a response object that returns an array of objects, but so far not a lot of luck using an array, this is what I have now, it returns an object, I would like it to be an array of objects:

#[OAResponse(
    response: 201,
    description: "Get the list",
    content: new OAJsonContent(
        properties: [
            new OAProperty(
                property: "property name 1",
                type: "string",
                example: "value 1"
            ),
            new OAProperty(
                property: "property name 2",
                type: "string",
                example: "value 2"
            )
        ],
        type: 'object'
    )
)]

Any guidance would be greatly appreciated!

Laravel where with whereNotIn not working

I am having trouble using where() and whereNotIn() clauses together in my SQL query. When I use the where clause alone, I receive my data correctly as shown in this screenshot:

Where close alone

However, when I add the whereNotIn clause (which works alone without the where clause), as shown in this screenshot:

where-close-whith-whereNotIn

I receive no data, even though I am supposed to receive some. Both of these conditions work alone, but not together.

Here is a detailed result of my query when the where() clause or whereNotIn() clause works alone:
bad-result

Does anyone have any idea why this might be happening? Thank you in advance for your help.

No API key provided

I try to connect and create account on stripe side and got error : No API key provided. Set your API key when constructing the StripeClient instance, or provide it on a per-request basis using the api_key key in the $opts argument.

My controller

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateDatabaseDatabaseManager;
use IlluminateHttpRequest;
use StripeStripeClient;
use IlluminateSupportStr;
use StripeExceptionApiErrorException;
use StripeStripe;

class SellerController extends Controller
{
    protected StripeClient $stripeClient;
    protected DatabaseManager $databaseManager;

    public function __construct(StripeClient $stripeClient, DatabaseManager $databaseManager)
    {
        $this->stripeClient = $stripeClient;
        $this->databaseManager = $databaseManager;
    }

    public function showProfile($id){
        $seller = User::find($id);

        if(is_null($seller)){
            abort(404);
        }

        return view('seller', [
            'seller' => $seller,
            'balande' => null
        ]);
    }

    public function redirectToStripe($id){
        $seller = User::find($id);

        if(is_null($seller)){
            abort(404);
        } 
        
        if(!$seller->completed_stripe_onboarding){

            $token = Str::random();
            $this->databaseManager->table('stripe_state_tokens')->insert([
                'created_at' => now(),
                'updated_at' => now(),
                'seller_id' => $seller->id,
                'token' => $token
            ]);

            // account id

            if (is_null($seller->stripe_connect_id)) {
    
                // Create account
                $account = $this->stripeClient->accounts->create([
                    'country' => 'FR',
                    'type'    => 'express',
                    'email'   => $seller->email,
                                   
                ]);

                $seller->update(['stripe_connect_id' => $account->id]);
                $seller->fresh();
            }
            $onboardLink =$this->stripeClient->accountLinks->create([
                'account' => $seller->stripe_connect_id,
                'refresh_url' => route('redirect.stripe', ['id' =>$seller->id]),
                'return_utl' => route('save.stripe', ['token' => $token]),
                'type' => 'acccount_onboarding'
            ]);

            return redirect($onboardLink->url);
        }

        $loginLink = $this->stripeClient->accounts->createloginLink($seller->stripe_connect_id);
        return redirect($loginLink->url);
    }

    public function saveStripeAccount($token){
        $stripeToken = $this->databaseManager->table('stripe_state_tokens')
        ->where('token', '=', $token)
        ->first();

        if(is_null($stripeToken)){
            abort(404);
        }

        $seller = User::find($stripeToken->seller_id);

        $seller->update([
            'completed_stripe_unboarding' => true
        ]);

        return redirect()->route('seller.profile', ['id' => $seller->id]);
    }
}

services.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Mailgun, Postmark, AWS and more. This file provides the de facto
    | location for this type of information, allowing packages to have
    | a conventional file to locate the various service credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
        'scheme' => 'https',
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],
    'stripe' => [
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],
];

appserviceprovider

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;
use Carbon;
use StripeStripeCLient;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(StripeClient::class, function(){
            return new StripeClient(config('stripe.secret'));
           });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
       $this->app->singleton(StripeClient::class, function(){
        return new StripeClient(config('stripe.secret'));
       });
    }
}

How to fix this error ? i suppose i have to inject to modify somethings about StripeClient no?

MYSQL Update by condition in Code Igniter

This is the MySQL version Syntax:

UPDATE table1 
    JOIN (
            SELECT mId, COUNT(*) c 
            FROM table1 
            GROUP BY mId 
            HAVING c < 2
        ) t1 
USING (mId)
    SET shared=0 ;

This means that if a value of mId only appears once in the mId column, then set shared = 0.

How to rewrite it in PHP code igniter?

Method which allows only letters and whitespaces

Trying to create a method which allows only letters and whitespaces and deny everything that contains numbers and special symbols.

so here is the code

class Users{
    public $names = array();
    public function add($name){
    
    foreach($this->names as $key){
        if (preg_match("/[A-Za-z ]/", $key)) {
            array_push($this->names,$key);
            
        }else{
            unset($key);
        }
        }
    }
}

    $users = new Users();
    $users->add('Ja1ne');
    $users->add('Sara');
    $users->add('Chloe');
    $users->add(['Marty', '!Taylor', 'D3ndy']);
    var_dump($users);

it should output array with:Sara,Chloe,Marty

wordpress plugin ajax 400 Bad Request

I am developing a wordpress-plugin to add pages as favorites. Therefore i wrote a function to delete favorites from the database. The code worked perfectly in the past. I dont know what i might have changed to make it stop working. When i try to delete a favorite the server throws a 400 Bad request exception. The same problem occurres with the ajax-call to load the favorites… I would be grateful if someone could help me with this problem.

script.js:

function deleteFavorite(page_id){
    console.log("test");
    jQuery(document).ready(function($) {
        var data = {
            'action': 'fav_delete',
            'page_id': page_id
        };
        jQuery.post(fav_ajax_object.ajax_url, data, function(response) {
            if(response!=0)
                alert(response);
        });
    });
}

delete.php:

<?php
add_action( 'wp_ajax_fav_delete', 'fav_delete' );
add_action( 'wp_ajax_nopriv_fav_delete', 'fav_delete' );


function fav_delete() {

    if(isset($_POST['page_id'])){
        $eppn = get_eppn();
        $page_id= $_POST['page_id'];

        global $wpdb;
        $table = 'wp_favoriten';

        $where = array('page_id' => $page_id, 'eppn' => $eppn);
        $format = array('%d','%s'); 
        $wpdb->delete($table,$where,$format); 

        echo $wpdb->print_error();
    }
        
}
?>

main.php:


include( plugin_dir_path( __FILE__ ) . 'include/delete.php');

function favPlugin_enqueue_scripts() {
    wp_enqueue_script( 'fav_script', plugins_url( 'js/script.js', __FILE__ ), array('jquery'));
    wp_localize_script( 'fav_script', 'fav_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' )));

}

It’s the first time i’m using ajax so i’m hoping it’s an easy to fix error that i am just not smart enough to identify on my own 🙂
Also please excuse my bad english, since it’s not my native language

Encryption data with php

I’m wondering how to approach the topic of data encryption. Maybe some of you have already faced something like this and can give me some advice.
I would like to keep data on two different servers for security.

The premise is:
script 1 [server 1] queries script 2 [server 2] for data. Part of the data will be stored on server 1, and part on server 2. Only after combining the data from both servers, it will be possible to read the correct data.
I am wondering how to secure this script so that if someone breaks into server 1, they will not read the data, because they will not have access to server 2.

Anyone got any ideas? Thanks!

Removing odd symbols from web scraped text

There is content that is web scraped and stored in a JSON string retrieved using the script

$response = response($jsonData)->header('Content-Type', 'application/json');

I then use the following scripts to extract the JSON content and decode the string

    $jsonData = $response->getContent();
    $decodedData = json_decode($jsonData);

The problem is the text is the string has odd text like u2019 and u2018 which seem to be replacing some punctuation marks. What are these and how can I remove them?

Joomla / ESHOP Question – how i correctly pull the sub total, vat, shipping and total value from the order totals table?

i am developing a payment gateway for Joomdonations ESHOP plugin (Joomla) which is all going well, im trying to post Sub Totals,Tax and Total to the gateway.

the sub total, shipping rate, vat and total are all stored in the ordertotals table as row values under name associated with the order_id.

im trying to get my script to call the values of specific order_ids and posting them as hidden inputs

ive tried adding a mysql query todo this but im failing miserably

this is the script I’ve put together for this can you advise on how i correctly pull the sub total, vat, shipping and total value from the order totals table?

//-------------------------------------------------------------------------------------------------------------------//
//-----------------------------This section sends the transaction  information to Monek-----------------------------//
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query  ->select('value')
        ->from('#__eshop_ordertotals')
        ->where('order_id ="' . $this->order_id . '"')
        ->where('name ="' . ('sub_total') . '"');
         $db->setQuery($query);
    $this->value = $db->loadResult();
    $this->setData('products_price', $this->value);

Laravel make:migration generating the created table again and again without creating a new one

I am trying to generate a model with migration file together in Laravel. But it’s saying like I already generated this table and can’t declare it again. The problem is the table that the error referring is wallets table which i already created long long ago and I didn’t include anything that relate to wallets tabel while creating model and migration file with command. It has nothing to do with my current command but why it said like I’ve already create wallets table while I’m generating super_admins_tabel?

I use this command
php artisan make:model SuperAdmin -m
And I got this error
SymfonyComponentErrorHandlerErrorFatalError Cannot declare class CreateWalletsTable, because the name is already in use

The model was created but the migration wasn’t.
I also tried generating migration file alone but it also gave me the same error. Why?

RBAC PHP by Bitwise Operators

I want to deploy rbac solution in my app. I found solution to use bitwise operators and it’s work but I have two problems.

  1. In global meaning permission “write” is upper than “read” and obviously permission “write” sholud contain permission “read”?
  2. For example I have page where I have form and inputs and I want to user access only read so I sholud use conditional “if else” ? If yes, that I have to two reapet the same code. One of conditional has to block form and inputs?
$read = 1;
$write = 2;
$deleteUsers = 4; 
    
$user = $read;

$employee = $read | $write;

$admin = $read | $write | $deleteUsers;


function checkPermission($person, $permission)
{       
    if($person & $permission) {
        return true;
    }
}
    
if(checkPermission($admin, $deleteUsers))
{
    echo "Access granted";
}