Export database to Excel

I wanna export data from database to excel, the data are very large, it’s contain almost 1 million record. What is the fastest way to export the data? The website is native-php

I have tried with PhpSpreedshet but it takes a very long time and even times out

Radio button attribute “checked” not working

This is a truly bizarre issue.

When submitting a PHP form, I keep getting the “undefined array key” error. This is happening because the radio button, although you can visually see it is checked, the input / value is not being passed during form submission.

I’ve tried:

  • forcing the button to be checked with Jquery
  • forcing the attribute “checked” on click with Jquery
  • MANUALLY marking the radio as checked by adding it to the HTML input <input type="radio" value="something" checked="checked">

I triple checked to make sure the input name matches what PHP is expecting, and also looked in the console under the Network tab and viewed the payload. No matter what I try, the radio input, even when marked checked visually and semantically, it is not being passed along with the rest of the form data.

Here is the form code in it’s entirety (using Twig for template engine):

<form id="bibleStudyQuiz" method="post" action="{{ base_url }}study/quiz_results/">
  {% for i in 1..total_records %}
  <input id="answer-{{ i }}" name="answer-{{ i }}" type="hidden" value="{{ results[i-1]['answer']|replace({'&#039;': "'"})|raw }}">
  <input id="questionText-{{ i }}" name="questionText-{{ i }}" type="hidden" value="{{ results[i-1]['question'] }}">
  {% endfor %}
  <input type="hidden" name="totalrecords" value="{{ total_records }}">
  {% for key,question in results %}
  <div class="aiia-wizard-step" id="quizQuestionnaire" data-id="1">
    <h5 class="card-title">{{ question.question }}</h5>
    <div class="step-content">
      <p class="card-text">
      <div class="row mb-2" style="text-align: left;">
        <div class="col-sm-2"></div>
        <div class="col-sm-4">
          <div class="form-check">
            <input name="question{{ key+1 }}" class="form-check-input" type="radio" value="{{ question.opt1 }}" id="{{ question.opt1 }}">
            <label class="form-check-label" for="{{ question.opt1 }}"> {{ question.opt1 }} </label>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="form-check">
            <input name="question{{ key+1 }}" class="form-check-input" type="radio" value="{{ question.opt2 }}" id="{{ question.opt2 }}">
            <label class="form-check-label" for="{{ question.opt2 }}"> {{ question.opt2 }} </label>
          </div>
        </div>
        <div class="col-sm-2"></div>
      </div>
      <div class="row" style="text-align: left;">
        <div class="col-sm-2"></div>
        <div class="col-sm-4">
          <div class="form-check">
            <input name="question{{ key+1 }}" class="form-check-input" type="radio" value="{{ question.opt3 }}" id="{{ question.opt3 }}">
            <label class="form-check-label" for="{{ question.opt3 }}"> {{ question.opt3 }} </label>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="form-check">
            <input name="question{{ key+1 }}" class="form-check-input" type="radio" value="{{ question.opt4 }}" id="{{ question.opt4 }}">
            <label class="form-check-label" for="{{ question.opt4 }}"> {{ question.opt4 }} </label>
          </div>
        </div>
        <div class="col-sm-2"></div>
      </div>
      </p>
    </div>
  </div>
  {% endfor %}
</form>

Here’s the PHP code that processes the form:

public function quiz_results()
{
    if ( empty( $_POST ) )
    {
        $this->redirect( 'study/quiz/' );
        exit;
    }

    $max             = $_POST['totalrecords'];
    $question        = [];
    $correct_answers = 0;

    for ( $i = 1; $i <= $max; $i++ )
    {
        // Gather questions and answers to pass to twig
        $question[$i]['text']          = $_POST["questionText-$i"];
        $question[$i]['answergiven']   = $_POST["question{$i}"];
        $question[$i]['correctanswer'] = $_POST["answer-{$i}"];

        // Grade the responses
        if ( $question[$i]['answergiven'] == $question[$i]['correctanswer'] )
        {
            $correct_answers = $correct_answers + 1;
        }

    }

    $percent = ( $correct_answers / $_POST['totalrecords'] ) * 100;

    $this->template->render( "studyquiz-results.html.twig",
        [
            'question'        => $question,
            'correct_answers' => $correct_answers,
            'total_records'   => $_POST['totalrecords'],
            'percent'         => (int) $percent,
        ]
    );

}

Thank you in advance for any help!

Issue with encoding values in PHP, Converts values and shows … instead of a ellipsis [closed]

I have an issue with encoding in my system.

I am using htmlentites($string) to encode or convert data on all accented characters but in doing so I am having issues with certain characters like for example let us take an input as

$input1 = "(contact poulie tendeuse, contrôle rotation limiteur…)"

After applying htmlentites($input1) I get

output: (contact poulie tendeuse, contrôle rotation limiteur&#8230;)

Now I have used htmlentites and have also seen other solutions where it is said to use htmlentites($input, ENT_NOQOUTES, 'UTF-8')
but none of these have worked and when I use this I get an empty string as output.

My main expectation is it shouldn’t show values like &#8230; on the page. I am also unable to decode it back to its original character.

I want to understand why is that so and how to overcome such a situation as this text is rare in my inputs and I would not want to make a big change for such inputs.

Is there a fix for “Option “–coverage” is ambiguous.” in PestPHP in Bitbucket pipelines?

Running the custom test in the following configuration results in the message
Option "--coverage" is ambiguous. followed by failure in the pipeline.

image:
  name: php:8.3-cli-bookworm
definitions:
  services:
    mysql:
      image: mysql/mysql-server:8.0
      variables:
        MYSQL_DATABASE: "testing"
        MYSQL_RANDOM_ROOT_PASSWORD: "yes"
        MYSQL_USER: "test_user"
        MYSQL_PASSWORD: "test_user_password"
  caches:
    composer:
      key:
        files:
          - composer.json
          - composer.lock
      path: vendor
  steps:
    - step: &composer-install
        name: Install dependencies
        caches:
          - composer
        script:
          - apt-get update && apt-get install -yq wget git zip unzip libfreetype6-dev libjpeg62-turbo-dev libpng-dev
          - docker-php-ext-configure gd --with-freetype --with-jpeg
          - docker-php-ext-install -j$(nproc) gd
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install --no-progress
    - step: &phpstan
        name: PHPStan
        caches:
          - composer
        script:
          - vendor/bin/phpstan analyze -c phpstan.neon --memory-limit=1G
    - step: &pint
        name: Pint
        caches:
          - composer
        script:
          - vendor/bin/pint
    - step: &code_coverage
        name: Pest Code Coverage
        caches:
          - composer
        script:
          - apt-get update && apt-get install -yq zlib1g-dev libicu-dev g++
          - pecl install xdebug
          - docker-php-ext-configure intl
          - docker-php-ext-enable xdebug
          - docker-php-ext-install -j$(nproc) intl pdo_mysql
          - echo "xdebug.mode=debug,coverage" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
          - echo "xdebug.remote_autostart=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
          - echo 'memory_limit = 512M' >> /usr/local/etc/php/conf.d/docker-php-memlimit.ini
          - echo 'DB_USERNAME=test_user' >> .env
          - echo 'DB_PASSWORD=test_user_password' >> .env
          - echo 'APP_URL=http://localhost' >> .env
          - echo 'APP_KEY=' >> .env
          - php artisan key:generate
          - php artisan passport:keys
          - vendor/bin/pest --coverage --min=100
        services:
          - mysql
pipelines:
   custom:
    test:
      - step: *composer-install
      - parallel:
          steps:
            - step: *phpstan
            - step: *code_coverage
            - step: *pint

I have found the following issues related to this:

But I’m afraid following the suggestions in that thread had no effect for me.

I’ve tried adding - export COMPOSER_ALLOW_SUPERUSER=1 and - composer config allow-plugins.pestphp/pest-plugin before - composer install --no-progress.

Running these commands in a local docker container set up like this works like a charm:

# pipeline_test.Dockerfile

# syntax = docker/dockerfile:1.2
FROM php:8.3-cli-bookworm

WORKDIR /app
COPY . /app
docker run --network=host --name mysql  
-e MYSQL_DATABASE='testing' 
-e MYSQL_RANDOM_ROOT_PASSWORD='yes' 
-e MYSQL_USER='test_user' 
-e MYSQL_PASSWORD='test_user_password' 
-d mysql/mysql-server:8.0

docker build --memory=1g --memory-swap=1g -t pipeline_test/pipeline_test:latest -f pipeline_test.Dockerfile . &&
docker run -it --network=host --memory=4g --memory-swap=4g --memory-swappiness=0 --cpus=4 --entrypoint=/bin/bash pipeline_test/pipeline_test:latest

I think my problem is due to a composer update which prevents scripts from being installed by the root user or the sudo command. Does anyone know how to rewrite my pipeline to work with the new composer version?

When searching words in another web page I need $regex be dynamic and use row data before saved in sql server

Here is my code for generating a HTML table:

echo  "<td  data-label='word_match'> <input type='text' name='word_match' value 
   ='".$row['word_match']."' /></td>";

echo  "<td  data-label='source_link'> <input type='text' 
         name='source_link' value ='".$row['source_link']."' /></td>";

I use this code to search for words from a web page:

$data = file_get_contents($row['source_link']);

$regex = '/ Galaxy/';   <<----- here is my problem i want use $row['word_match'] instead of galaxy(for example)
  
 preg_match($regex,$data,$match);
 var_dump($match);
 echo $match[1];

WordPress create-block WP_Block_Type_Registry::register was called incorrectly. Block type names must contain a namespace prefix

I am currently getting into WordPress and I did most of the developer recources and they work just fine in isolation. My current problem is the block creator. When I try to use my @wordpress/create-block plugin with npx wp-env start it works just fine and can be used but when I try to get any block to work in another local development I get the message from the title.

I tried setting up a new enviornment using ddev (https://ddev.readthedocs.io/en/latest/users/quickstart/#wordpress) then I switched to Local as I have seen a lot of people use it during my search for an answer but that resulted in the exact same situation. When looking up solutions for this error I figured out that there have been like 3 or 4 different reasons for this error but none of theme seem to still apply or be relevant to my usecase. The tutorial (and other video recources) suggest that it should be as simple as haveing a local working setup for wordpress navigate to the plugins folder and use npx @wordpress/create-block@latest and then walk through the steps in the terminal (Or set some flags alternatively). This then creates a plugin that can be activated which is nice and dandy. The php script in that plugin is confirmed to run as expected (Except the block register function) but then there is no block showing up in the block editor (and it does seem to work as simple as that in all the other recources)

I am running the WP version 6.5.4 and everything else (from php to node) is all on the latest version aswell.

Did anyone else have this issue? Help would be greatly appreciated as I am at my wills end. Or a direction where to look for the next step? Since it is working in the isolation of wp-env the function itself seems to work. I echoed the content of the given path in case it might get confused after the build task but that also displays the correct json.

Use a basic wp setup and try to create a new block using npx @wordpress/create-block@latest

for some reason i cant add code tho this question as it wont allow me to format it correctly(?) but all the code is the basic generated code so if anyone got some time to test and maybe reproduce it it would be very much appreciated…

Enable user login with phone number stored in user_meta – WordPress

In my wordpress, I want to add one functionality is:

  • User can login by their Phone number which is stored in ‘pcplugin-phone’ user meta key.
  • I’ve tried ‘authenticate’ filter hook but it’s not working.
  • For login page styling I am using Loginpress
  • Also I’ve putted php code in by creating a plugin of it.
  • Error which I am getting: Invalid username, email address or incorrect password.

Can someone help to fix?

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

// Hook into the authenticate filter to modify the login process
add_filter( 'authenticate', 'phone_number_login_authenticate', 30, 3 );

    function phone_number_login_authenticate( $user, $username, $password ) {
        // Check if the username is actually a phone number
        if ( is_numeric( $username ) ) {
            // Get the user by phone number
            $user = get_user_by_meta_data( 'pcplugin-phone', $username );
    
            // If user is found and password is correct, return the user object
            if ( $user && wp_check_password( $password, $user->user_pass, $user->ID ) ) {
                return $user;
            } else {
                return new WP_Error( 'invalid_login', __( '<strong>ERROR</strong>: Invalid phone number or password.', 'phone-number-login' ) );
            }
        }
    
        return $user;
    }
    
    // Function to get user by meta data
    function get_user_by_meta_data( $meta_key, $meta_value ) {
        global $wpdb;
    
        // Query to get the user ID by meta key and meta value
        $user_id = $wpdb->get_var( $wpdb->prepare(
            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = %s",
            $meta_key,
            $meta_value
        ) );
    
        // If user ID is found, return the user object
        if ( $user_id ) {
            return get_user_by( 'ID', $user_id );
        }
    
        // If no user is found, return false
        return false;
    }

Login Form:

<form name="loginform" id="loginform" action="https://example.com/wp-login.php" method="post">
            <p>
                <label for="user_login">Username or Email Address</label>
                <input type="text" name="log" id="user_login" class="input" value="" size="20" autocapitalize="off" autocomplete="username" required="required">
            </p>

            <div class="user-pass-wrap">
                <label for="user_pass">Password</label>
                <div class="wp-pwd">
                    <div class="user-pass-fields"><input type="password" name="pwd" id="user_pass" class="input password-input" value="" size="20" autocomplete="current-password" spellcheck="false" required="required"><div class="loginpress-caps-lock">Caps Lock is on</div></div>
                    <button type="button" class="button button-secondary wp-hide-pw hide-if-no-js" data-toggle="0" aria-label="Show password">
                        <span class="dashicons dashicons-visibility" aria-hidden="true"></span>
                    </button>
                </div>
            </div>
                        <p class="forgetmenot"><input name="rememberme" type="checkbox" id="rememberme" value="forever"> <label for="rememberme">Remember Me</label></p>
            <p class="submit">
                <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In">
                                    <input type="hidden" name="redirect_to" value="https://example.com/wp-admin/">
                                    <input type="hidden" name="testcookie" value="1">
            </p>
        </form>

Unable to decrypt JWE payload

I am trying to sign and encrypt my payload. When the other party tries to decrypt my data it returns “AES/GCM/NoPadding decryption failed: Tag mismatch!” error. Can you anyone help me to figure out the problem? Thanks in advance

I am using https://web-token.spomky-labs.com/ JWT framework 3.3 version

My Code:

public static function encryptPayload($payload)
    {
        $payload = json_encode($payload);
        $selfPrivateKey = self::getSelfPrivateKey();
        $publicKey = self::getPublicKey();

      //  -----   Build JWS Object    -----   Begin   -----
        // Init JWS algorithm
        $jwsAlgorithmManager = new AlgorithmManager([new RS256()]);
        // Build JWS object and sign the message by merchant's private key
        $jwsBuilder = new JWSBuilder($jwsAlgorithmManager);
        $jws = $jwsBuilder
            ->create()
            ->withPayload($payload)
            ->addSignature($selfPrivateKey, [
                'alg' => 'RS256',
                'kid' => 0002,
            ])
            ->build();
            $jwsSerializer = new JwsCompactSerializer();
            $jwsString = $jwsSerializer->serialize($jws, 0);
            //  -----   Build JWS Object    -----    END    -----
    
            //  -----   Build JWE Object    -----   Begin   -----
            // Init JWE algorithm
            $jweKeyEncryptionAlgorithmManager = new AlgorithmManager([
                new RSAOAEP256(),
            ]);
            // Init JWE encryption algorithm
            $jweContentEncryptionAlgorithmManager = new AlgorithmManager([
                new A128GCM(),
            ]);
            $compressionMethodManager = new CompressionMethodManager([
                new Deflate(),
            ]);
            // Build JWE object and encrypt the message by public key
            $jweBuilder = new JWEBuilder(
                $jweKeyEncryptionAlgorithmManager,
                $jweContentEncryptionAlgorithmManager,
                $compressionMethodManager
            );
            $jwe = $jweBuilder
                ->create()
                ->withPayload($jwsString)
                ->withSharedProtectedHeader([
                    'alg' => 'RSA-OAEP-256',
                    'enc' => 'A128GCM',
                    'kid' => '0005',
                ])
                ->addRecipient($publicKey)
                ->build();

            $jweSerializer = new JweCompactSerializer();
            $jweString = $jweSerializer->serialize($jwe, 0);
            //  -----   Build JWE Object    -----    END    -----
           // $this->logger->info("Encrypted String: $jweString");
            return $jweString;
    }

Activate auto-scroll when text exceeds screen width

I’m creating a plugin for wordpress using only php and css (for now at least) where it generates a topbar with a number of messages choosed by the user, i need to know how i can generate an ‘if’ statement that activates autoscroll only when text’s lenght of 1 or more messages or the sum of all texts’ lenght exceeds the screen’s width

Not tried much since i’m new to programming and i couldn’t find much online about this specific situation

HTML Form not submitting – PHP [closed]

For my website I have a contact form but when I try to submit the form, nothing happens.
I checked other answers on this webiste but I can’t seem to find the issue. The button does something, because when I try to submit with the fields not populated properly, I get the warning messages.

My Form:

<section class="contact-section">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <h2 class="contact-title">Get in Touch</h2>
            </div>
            <div class="col-lg-8">
                <form class="form-contact contact_form" action="contact_process.php" method="post" id="contactForm" novalidate="novalidate">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <textarea class="form-control w-100" name="message" id="message" cols="30" rows="9" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Bericht'" placeholder="Bericht"></textarea>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control valid" name="name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Uw naam'" placeholder="Uw naam">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <input class="form-control valid" name="email" id="email" type="email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'" placeholder="Email">
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-group">
                                <input class="form-control" name="subject" id="subject" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Onderwerp'" placeholder="Onderwerp">
                            </div>
                        </div>
                    </div>
                    <div class="form-group mt-3">
                        <button type="submit" class="button button-contactForm boxed-btn">Verzenden</button>
                    </div>
                </form>
            </div>
            <div class="col-lg-3 offset-lg-1">
                <div class="media contact-info">
                    <span class="contact-info__icon"><i class="ti-home"></i></span>
                    <div class="media-body">
                        <h3>Lier, Belgie.</h3>
                        <p>Frederik Peltzerstraat 88 bus 101, 2500 Lier</p>
                    </div>
                </div>
                <div class="media contact-info">
                    <span class="contact-info__icon"><i class="ti-tablet"></i></span>
                    <div class="media-body">
                        <h3>+32 (0) 494 67 64 92</h3>
                    </div>
                </div>
                <div class="media contact-info">
                    <span class="contact-info__icon"><i class="ti-email"></i></span>
                    <div class="media-body">
                        <h3>[email protected]</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

And my PHP file:

<?php

$to = "[email protected]";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$subject = $_REQUEST['subject'];
$number = $_REQUEST['number'];
$cmessage = $_REQUEST['message'];

$headers = "From: $from";
$headers = "From: " . $from . "rn";
$headers .= "Reply-To: ". $from . "rn";
$headers .= "MIME-Version: 1.0rn";
$headers .= "Content-Type: text/html; charset=ISO-8859-1rn";

$subject = "You have a message from your Bitmap Photography.";

$logo = 'img/logo.png';
$link = '#';

$body = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>Express Mail</title></head><body>";
$body .= "<table style='width: 100%;'>";
$body .= "<thead style='text-align: center;'><tr><td style='border:none;' colspan='2'>";
$body .= "<a href='{$link}'><img src='{$logo}' alt=''></a><br><br>";
$body .= "</td></tr></thead><tbody><tr>";
$body .= "<td style='border:none;'><strong>Name:</strong> {$name}</td>";
$body .= "<td style='border:none;'><strong>Email:</strong> {$from}</td>";
$body .= "</tr>";
$body .= "<tr><td style='border:none;'><strong>Subject:</strong> {$csubject}</td></tr>";
$body .= "<tr><td></td></tr>";
$body .= "<tr><td colspan='2' style='border:none;'>{$cmessage}</td></tr>";
$body .= "</tbody></table>";
$body .= "</body></html>";

$send = mail($to, $subject, $body, $headers);

?>

If anybody could help that would be greatly appreciated!

Key provided is shorter than 256 bits in PHPOpenSourceSaver JWTAuth

I’m working on a Laravel project and trying to implement JWT authentication using the php-open-source-saver/jwt-auth package and I’m having an issue when attempting to generate a token.

my JWT_ALGO=HS256

The error message I’m receiving is:

PHPOpenSourceSaverJWTAuthExceptionsJWTException:
Could not create token: Key provided is shorter than 256 bits, only 224 bits provided

below is the code


  try {
            $notActivated = $this->auth->login($credentials);

            if ($notActivated === trans('user::users.account not validated')) {
                return response()->json(
                    [
                        'success' => false,
                        'message' => trans('user::users.account not validated'),
                    ],
                    403
                );
            }
            if (!$token = auth('api')->attempt($credentials)) {
                // attempt to verify the credentials and create a token for the user
                return response()->json(
                    [
                        'success' => false,
                        'message' => trans('invalid credentials'),
                    ],
                    401
                );
            }
        }

below is the stack trace for reference:


PHPOpenSourceSaverJWTAuthExceptionsJWTException {#969
#message: "Could not create token: Key provided is shorter than 256 bits, only 224 bits provided"
#code: 0
#file: "Project/vendor/php-open-source-saver/jwt-auth/src/Providers/JWT/Lcobucci.php"
#line: 143
-previous: LcobucciJWTSignerInvalidKeyProvided {#968
#message: "Key provided is shorter than 256 bits, only 224 bits provided"
#code: 0
#file: "Project/vendor/lcobucci/jwt/src/Signer/InvalidKeyProvided.php"
#line: 39
trace: {
Project/vendor/lcobucci/jwt/src/Signer/InvalidKeyProvided.php:39 {
LcobucciJWTSignerInvalidKeyProvided::tooShort(int $expectedLength, int $actualLength): self …
› {
› return new self('Key provided is shorter than ' . $expectedLength . ' bits, only ' . $actualLength . ' bits provided');
}
Project/vendor/lcobucci/jwt/src/Signer/Hmac.php:20 {
LcobucciJWTSignerHmac->sign(string $payload, Key $key): string …
› if ($actualKeyLength < $expectedKeyLength) {
› throw InvalidKeyProvided::tooShort($expectedKeyLength, $actualKeyLength);
› }
}
Project/vendor/lcobucci/jwt/src/Token/Builder.php:119 {
LcobucciJWTTokenBuilder->getToken(Signer $signer, Key $key): Plain …
›
› $signature = $signer->sign($encodedHeaders . '.' . $encodedClaims, $key);
› $encodedSignature = $this->encoder->base64UrlEncode($signature);
}
Project/vendor/php-open-source-saver/jwt-auth/src/Providers/JWT/Lcobucci.php:141 {
PHPOpenSourceSaverJWTAuthProvidersJWTLcobucci->encode(array $payload) …
›
› return $this->builder->getToken($this->config->signer(), $this->config->signingKey())->toString();
› } catch (Exception $e) {
}
Project/vendor/php-open-source-saver/jwt-auth/src/Manager.php:85 {
PHPOpenSourceSaverJWTAuthManager->encode(Payload $payload) …
› {
› $token = $this->provider->encode($payload->get());
›
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWT.php:74 {
PHPOpenSourceSaverJWTAuthJWT->fromSubject(JWTSubject $subject) …
›
› return $this->manager->encode($payload)->get();
› }
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWT.php:84 {
PHPOpenSourceSaverJWTAuthJWT->fromUser(JWTSubject $user) …
› {
› return $this->fromSubject($user);
› }
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWTGuard.php:164 {
PHPOpenSourceSaverJWTAuthJWTGuard->login(JWTSubject $user) …
› {
› $token = $this->jwt->fromUser($user);
› $this->setToken($token)->setUser($user);
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWTGuard.php:149 {
PHPOpenSourceSaverJWTAuthJWTGuard->attempt(array $credentials = [], $login = true) …
› if ($this->hasValidCredentials($user, $credentials)) {
› return $login ? $this->login($user) : true;
› }
}
Project/Modules/User/Http/Controllers/Api/AuthController.php:85 {
ModulesUserHttpControllersApiAuthController->postLogin(ApiLoginRequest $request): JsonResponse …
› }
› if (!$token = auth('api')->attempt($credentials)) {
› // attempt to verify the credentials and create a token for the user
}

Things I have tried:

  • Cleared Cache
  • Cleared the JWT keys
  • Regenerated the JWT keys using jwt:generate-certs
  • Generated a new key manually

This same code works perfectly in another project with same app key and I tried copying the working version to this project, but I’m still getting the same error.
I’m unable to figure out why the key is shorter than the required 256 bits when i generate one. Has anyone faced a similar issue or could point me in the right direction to resolve this?

Any help would be greatly appreciated!

Avada Theme throwing PHP Fatal Errors in actual Version with PHP 8.X

using Avada Theme 7.11.9, WordPress 6.5.4, TranslatePress, all together with PHP 7.4.

As soon as we upgrade to PHP 8.X we got hundreds of PHP Fatal Errrors thrown by the Avada Theme, no child theme, everything up to date:

[07-Jun-2024 20:17:00 UTC] PHP Fatal error:  Uncaught ArgumentCountError: 3 arguments are required, 2 given in /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/metaboxes/tabs/tab_page.php:69
Stack trace:
#0 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/metaboxes/tabs/tab_page.php(69): sprintf()
#1 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/metaboxes/metaboxes.php(271): avada_page_options_tab_page()
#2 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/class-fusion-dynamic-css-from-options.php(160): PyreThemeFrameworkMetaboxes->get_options()
#3 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/class-fusion-dynamic-css-from-options.php(126): Fusion_Dynamic_CSS_From_Options->init()
#4 /home/abc/domains/abc.solutions/public_html/wp-includes/class-wp-hook.php(324): Fusion_Dynamic_CSS_From_Options->dynamic_css_array_filter_po()
#5 /home/abc/domains/abc.solutions/public_html/wp-includes/plugin.php(205): WP_Hook->apply_filters()
#6 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/lib/inc/class-fusion-dynamic-css-helpers.php(390): apply_filters()
#7 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/lib/inc/class-fusion-dynamic-css.php(306): Fusion_Dynamic_CSS_Helpers->get_dynamic_css()
#8 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/lib/inc/class-fusion-dynamic-css-helpers.php(260): Fusion_Dynamic_CSS->generate_final_css()
#9 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/lib/inc/class-fusion-dynamic-css.php(361): Fusion_Dynamic_CSS_Helpers->dynamic_css_cached()
#10 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/lib/inc/class-fusion-dynamic-css-inline.php(109): Fusion_Dynamic_CSS->make_css()
#11 /home/abc/domains/abc.solutions/public_html/wp-includes/class-wp-hook.php(324): Fusion_Dynamic_CSS_Inline->add_inline_css_wp_head()
#12 /home/abc/domains/abc.solutions/public_html/wp-includes/class-wp-hook.php(348): WP_Hook->apply_filters()
#13 /home/abc/domains/abc.solutions/public_html/wp-includes/plugin.php(517): WP_Hook->do_action()
#14 /home/abc/domains/abc.solutions/public_html/wp-includes/general-template.php(3050): do_action()
#15 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/header.php(21): wp_head()
#16 /home/abc/domains/abc.solutions/public_html/wp-includes/template.php(810): require_once('/home/abc/domai...')
#17 /home/abc/domains/abc.solutions/public_html/wp-includes/template.php(745): load_template()
#18 /home/abc/domains/abc.solutions/public_html/wp-includes/general-template.php(48): locate_template()
#19 /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada-Child-Theme/100-width.php(15): get_header()
#20 /home/abc/domains/abc.solutions/public_html/wp-includes/template-loader.php(106): include('/home/abc/domai...')
#21 /home/abc/domains/abc.solutions/public_html/wp-blog-header.php(19): require_once('/home/abc/domai...')
#22 /home/abc/domains/abc.solutions/public_html/index.php(17): require('/home/abc/domai...')
#23 {main}
  thrown in /home/abc/domains/abc.solutions/public_html/wp-content/themes/Avada/includes/metaboxes/tabs/tab_page.php on line 69

We enabled WP Debugging and got the errors mentioned above.

Split Text into Four Part From Textarea input of a news article

I am developing a news article web page where i want to separate the long text of a news story in to four part and save them into MSQL DB in four separate column.

This is just to achieve flexibility when presenting it to the readers in such a way that i can place some important information in the middle of the content after some paragraph (less after two or three paragraph). important info such as related news, advert and the like. This is a common practice on many news website.

So far i have tried the code below which rises another issued for me:

  function split_words_into_parts( string $words, int $parts = 5 ) {

  $words_array  = explode( ' ', $words );
  $words_cnt    = count( $words_array );
  $per_part   = max( round( $words_cnt / $parts ), 1 );

  $result     = [];

  /*---  Splitting the full array  ---*/
  for( $i = 0; $i < $parts; $i++ ) {
      $result[] = array_slice( $words_array, $i * $per_part, $per_part );
  }

  $part1 = implode(" ", $result[0]);
  $part2 = implode(" ", $result[1]);
  $part3 = implode(" ", $result[2]);
  $part4 = implode(" ", $result[3]);
  $part5 = implode(" ", $result[4]);

  if($words_cnt <= 1000) {
    return [$part1.' '.$part2.' '.$part3, $part4.' '.$part5, '', ''];
  }
  
  if($words_cnt > 1000 AND $words_cnt < 2500) {
    return [$part1.' '.$part2, $part3.' '.$part4, $part5, ''];
  }
  
  if($words_cnt >= 2500) {
    return [$part1.' '.$part2, $part3, $part4, $part5];
  }
}

In the code, the text were separated into 5 but its return four array element where the first element contains two part of the separated text because i want the first part to be much than the rest.

The issue with the above code is that it separate base on number of text, which means a full paragraph conveying a particular message in the story might be spilt into different part and an advert will be place in between them making the paragraph confusing and hard to understand in-fact inconvenient reader.

please what I want is splitting the text base on paragraph but still maintaining the raw text from the textarea because i am using php pasedown library

thank you for your anticipated consideration

NGINX IMAP proxy and real IP of client

There is such a configuration for nginx/1.24.0 (–with-http_realip_module) as an example of an IMAP proxy protocol. But there is a problem with getting the real IP address of the client in the nginx logs (80_access.log). And there is a problem with getting the real IP address of the client in index.php in the variable $_SERVER[“REMOTE_ADDR”].

user www;
worker_processes auto;
pid /var/run/nginx.pid;
worker_rlimit_nofile 20480;

events {
    use kqueue;
    worker_connections 10240;
    multi_accept on;
}

http {
    include /usr/local/etc/nginx/mime.types;
    default_type application/octet-stream;

    server_tokens off;

    log_format main '$remote_addr - $remote_user [$time_local] $status "$request" $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/nginx-access.log main;
    error_log /var/log/nginx/nginx-error.log warn;

    keepalive_timeout 30;
    keepalive_requests 200;

    server {
        listen 80;
        server_name imap.example.com;

        server_name_in_redirect on;

        access_log /var/log/nginx/gatewaymail.net/imap/80_access.log common;
        error_log /var/log/nginx/gatewaymail.net/imap/80_errors.log warn;

        root /usr/local/www/nginx/imap;
        index index.php;

        location / {
        }

        location = /favicon.ico {
            log_not_found off;
        }

        location ~ .php$ {
            try_files $uri = 404;

            fastcgi_pass unix:/var/run/imap-php8.3-fpm.sock;

            fastcgi_send_timeout 300;
            fastcgi_read_timeout 300;

            include fastcgi_params;
            fastcgi_split_path_info ^(.+?.php)(/.*)?$;

            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name;

            fastcgi_buffer_size 1024k;
            fastcgi_buffers 4 1024k;
            fastcgi_busy_buffers_size 1024k;
            fastcgi_temp_file_write_size 1024k;

            set $path_info $fastcgi_path_info;
            fastcgi_param PATH_INFO $path_info;

            fastcgi_param SERVER_ADMIN [email protected];
            fastcgi_param SERVER_SIGNATURE nginx/$nginx_version;
            fastcgi_index index.php;
        }

    }

}

mail {

    proxy_pass_error_message  on;

    server {
        auth_http imap.example.com/index.php;
        listen 143;
        protocol imap;

        error_log /var/log/nginx/gatewaymail.net/imap/imap_proxy_errors.log warn;

    }
}

In the logs, I always see the internal or external IP of my own server depending on the configuration.

If:

server_name imap.example.com
auth_http imap.example.com/index.php

I see the external IP of my server.

If:

server_name imap;
auth_http imap/index.php;

I see the internal IP of my server.

I tried different configurations:

https://docs.nginx.com/nginx/admin-guide/load-balancer/using-proxy-protocol/

nginx mail proxy behind haproxy – get clients real ip address

real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;

nothing helped.

I ask for help from the experts.

How to make a Ringless voicemails with Twilio and PHP

I am trying to leave a ringless voicemail using Twilio and PHP by first making a first call followed by a second call while immediately dropping the first so that the second goes directly into voicemail but this does not appear to work.

All the two calls are received, one after the other instead of the second going to the voicemail. What corrections can I make:
function drop_voicemails() {
require DIR . ‘/vendor/autoload.php’;

// Your Account SID and Auth Token from console.twilio.com
$sid = "";
$token = "";
$client = new TwilioRestClient($sid, $token);
$phone_no = ''; // Replace with the actual phone number to call
$from_no = ''; // Replace with your Twilio number

// First call to trigger voicemail
$call = $client->calls->create(
    $phone_no, // To
    $from_no, // From
    array(
        "method" => "GET",
        "statusCallback" => "https://example.com/voicemail.php?to_phone_no=" . $phone_no,
        "statusCallbackEvent" => ["completed"],
        "statusCallbackMethod" => "POST",
        "twiml" => '<Response><Pause length="1"/><Hangup/></Response>' // Short delay and hangup
    )
);

// Wait for a few seconds to ensure the first call is processed and goes to voicemail
sleep(3);

// Second call to drop voicemail with inline TwiML using your own MP3
$call2 = $client->calls->create(
    $phone_no, // To
    $from_no, // From
    array(
        "twiml" => '<Response><Play>https://example.com/uploads/message_1_1003.mp3</Play><Record maxLength="20" action="https://example.com/handle-recording.php"/><Hangup/></Response>'
    )
);

echo "Voicemail left successfully.";

}

I tried reducing and increasing the sleep time but it does not appear to work. Is there a better solution since I am working with numbers that cannot receive an SMS?