Laravel worker set dynamic retry_after

Have a Laravel 5.7 app with a single Job class. The job itself will fetch data and process it.
The amount of data (and therefore the length of time the job takes) can vary massively so wanted to have a dynamic timeout based on the runtime of the past n jobs (the details are stored so can be queried).

This would work in that I can set public $timeout = n in the class but the retry_after value can only be set on CLI or in the config/queue.php as the public $retryAfter in the class has a different function (according to https://divinglaravel.com/explaining-laravel-queue-configuration-keys).

Is there any way that at runtime I can set the retry_after value dynamically?

For info, absolutely cannot hard set a value due to the way the app works (and refactoring other code in the app is a no-go), and the time it takes to run will always be an unknown so just creating separate long running queues or things like that won’t work either.

Laravel Receipt pdf download

I’m using laraveldaily/laravel-invoices to generate invoices.

I’ve stored the receipt with ->save('public'); and stored this link to database with: $invoice->url().

I got a link like this: http://example.com/storage/pdf_name.pdf .
But, File stored in storage/app/public/ folder

Now, If I hit this URL, it says **"Forbidden"** You don't have permission to access this resource.

What can I do now? and is there any way to store just folder and file name? like: folder/pdf_name.pdf

WordPress Directory Issues

All WordPress core files had a wrong file directory like this. So I am facing the below error on wordpress admin panel

Error
wp-blog-header.php
Warning: Use of undefined constant ABSPATH – assumed ‘ABSPATH’ (this will throw an Error in a future version of PHP) in E:xampphtdocsdcidigital_blogwp-adminindex.php on line 13

Warning: require_once(ABSPATHwp-admin/includes/dashboard.php): failed to open stream: No such file or directory in E:xampphtdocsdcidigital_blogwp-adminindex.php on line 13

Fatal error: require_once(): Failed opening required ‘ABSPATHwp-admin/includes/dashboard.php’ (include_path=’E:xamppphpPEAR’) in E:xampphtdocsdcidigital_blogwp-adminindex.php on line 13

All core file had like this 
require_once( dirname( __FILE__ ) . '/admin.php' );

Please check and give me some solutions

Retrieve in Laravel Blade data of external api with HTTP request

In my controller i have this

     public function GetStatusDetails()
        {
     $statusDetailsResponse = 
    Http::get('https://exemple.exemple.com/fr/api/088b77/<Token>/availability/<ID>/getStatusDetailsformat=json');
        $StatusDetails = json_decode($statusDetailsResponse->body(), true);
        }
dd($StatusDetails);

The result of the DD is Here

The question is how i acces to that data in my blade please ?

laravel 8 don’t run migrate file in packages folder

When run ‘php artisan migrate’ in windows os: laravel migrate all file (databasemigrations in root folder and in packages folder).
But in Linux os just migrate file in databasemigrations of root folder.
I have Databasemigrations folder in packages folder and use the loadMigrationsFrom method in function boot() of service provider class.
How do I can migrate all files in Linux?

illegal string offset ‘huisnummer’ in if statement

i am trying to fetch information from a json which seemingly worked fine till i ran into this problem: code below, it is giving me the error “Warning: Illegal string offset ‘huisnummer’ in …” and i have no clue why

<?php
class Post extends Controller {
    protected function GetAdresgegevens() {
        $postcode = "7521AG";
        $huisnummer = 437;

        $url = "https://geodata.nationaalgeoregister.nl/locatieserver/free?fq=postcode:$postcode&fq=huisnummer~$huisnummer*";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $result = json_decode($response, true);
        curl_close($ch); // Close the connection


        $data               = [];
        $data['valid']      = false;
        $data['postcode']   = $postcode;
        $data['woonplaats'] = '';
        $data['huisnummer'] = $huisnummer;
        $data['straatnaam'] = '';

        $docs = $result['response']['docs'];

        if(!empty($docs)) {
            for ($i = 1; $i < count($docs); $i++) {
                foreach ((array) $docs["$i"] as $value) {
                    if ($value["huisnummer"] == $huisnummer && $value['postcode'] == $postcode) {
                        $data['woonplaats'] = $value['woonplaatsnaam'];
                        $data['straatnaam'] = $value['straatnaam'];
                    }
                }
            }
            echo "<pre>";
            print_r($docs);
            echo "</pre>";
            die;
        }

        $this->returnView($data, true, true);
    }
}

if i change it back to $docs[“$i”][“”huisnummer”] it works fine, code:

if(!empty($docs)) {
            for ($i = 1; $i < count($docs); $i++) {
                foreach ((array) $docs["$i"]['huisnummer'] as $value) {
                    if ($value == $huisnummer) {
                        $data['woonplaats'] = $value['woonplaatsnaam'];
                        $data['straatnaam'] = $value['straatnaam'];
                    }
                }
            }
            echo "<pre>";
            print_r($docs);
            echo "</pre>";
            die;
        }

Use of undefined constant &nbsp – assumed ‘&nbsp ‘

I have a line of code that looks like this:

<input type="<?= ( is_numeric( $antwort ) ) ? 'number' : 'text'; ?>" class="antwort" value="<?= $antwort ?>" <?= ( $i == 1 ) ? 'disabled' : ''; ?>>

The html output:

<input type="number<br />
<b>Warning</b>:  Use of undefined constant &nbsp; - assumed '&nbsp;' (this will throw an Error in a future version of PHP) in <b>/home/cardiodemowerbea/docroot/web/wp-content/plugins/cardio-score/admin/patients.php</b> on line <b>295</b><br />
" class="antwort" value="1">

Why is there a warning?
Where am I missing an &nbsp;?

How to Convert All Word’s First Letter into Big Letter and Remaining in Small Letter if whole words are in Uppercase?

I am trying to change the first Letter of Each Word into Big Letter and Remaining Small in the following case if whole words are in Big Letters.

Example: THIS IS A CAT:

Output Require: This Is A Cat.

<style>    
/*not working if all words are in UPPERCASE.*/
text-transform: capitalize; 
</style>

/*PHP not working*/
<?PHP ucword(); ?>

Robot journalists in php [closed]

Good time of day. Has anyone met the source code of the script that writes news to the site? I’ve found similar things in other programming languages, but I’m interested in php.

Why mysql delete query is not working with string variable?

I am android developer and I am weak in PHP.

This one is working:

$sql = "DELETE FROM user WHERE id    =       '$user->id'    ";

This one works too:

$sql = "DELETE FROM user WHERE email = '" . '[email protected]' . "'";

But this query not working:

$sql = "DELETE FROM user WHERE email = '" .  "'$user->email'"  . "'";

This is my phpMyAdmin table:

enter image description here

and this is my del.php api that works fine with first two query:

<?php
 include_once('../common/include.php');
 include_once('../common/encipher.php');
 $user = json_decode(file_get_contents("php://input"));
 $conn=getConnection();
 if($conn==null){
     sendResponse(500,$conn,'Server Connection Error !');
     exit;
 }
 $sql = "DELETE FROM user WHERE id = '$user->id'";
 $result = $conn->query($sql);
 if ($conn->affected_rows > 0) {
 sendResponse(200, [], 'User deleted .');
 }
 else 
 {
  sendResponse(404, [], 'Error on delete !');
 }
 $conn->close();

Laravel – S3 multiple file zip and download

Is there any way to loop or perform some foreach action inside return in Laravel?
I have this package https://github.com/stechstudio/laravel-zipstream for zip downloading from s3. All works for single file and for multiple, but only when each files are provided in separate line.

use Zip; 
public function z4()
    {
    return Zip::create("package.zip")
                ->add("s3://testbucket/images/26/17/full/BS288.jpg", "BS288.jpg")
                ->add("s3://testbucket/images/26/17/full/BS289.jpg", "BS289.jpg")
                ->add("s3://testbucket/images/26/17/full/BS290.jpg", "BS290.jpg")
    }

but how to make this with data from database

$photos = DB::table('gallery_image')
                ->where('folder_id','=',$id)
                ->select('original_name')->get();

This is array returned from $photos:

  IlluminateSupportCollection {#1017 ▼
        #items: array:131 [▼
          0 => {#1025 ▼
            +"original_name": "BS288.jpg"
          }
          1 => {#1022 ▼
            +"original_name": "BS289.jpg"
          }
          2 => {#1026 ▼
            +"original_name": "BS290.jpg"
          }

this code will return always one file

foreach($photos as $image) {
     
            return Zip::create("package.zip", [
                "s3://asystentfotografa/images/26/17/full/".$image->original_name, 
              ]);
 }

How to modify product data using ProductPageLoadedEvent in Shopware 6?

Does anyone knows to modify product data using ShopwareStorefrontPageProductProductPageLoadedEvent ?

services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="SwagBasicExampleServiceAddDataToPage" >
                <argument type="service" id="product.repository"/>
                <tag name="kernel.event_subscriber" />
        </service>
    </services>
</container>

AddDataToPage.php

<?php declare(strict_types=1);

namespace SwagBasicExampleService;

use ShopwareCoreFrameworkDataAbstractionLayerEntityRepositoryInterface;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use ShopwareStorefrontPageProductProductPageLoadedEvent;

class AddDataToPage implements EventSubscriberInterface
{
    /**
     * @var EntityRepositoryInterface
     */
    private $productRepository;

    /**
     * @param EntityRepositoryInterface $productRepository
     */
    public function __construct(
        EntityRepositoryInterface $productRepository
    )
    {
        $this->productRepository = $productRepository;
    }

    /**
     * @return string[]
     */
    public static function getSubscribedEvents(): array
    {
        return [
            ProductPageLoadedEvent::class => 'onProductsLoaded'
        ];
    }


    /**
     * @param ProductPageLoadedEvent $event
     * @return void
     */
    public function onProductsLoaded(
        ProductPageLoadedEvent $event
    )
    {
        // the product is inside the page object
        $productData = $event->getPage()->getProduct();


        //modifying name
        $this->log($productData->getName());
        $productData->setName('Prefix Product Name' . $productData->getName());
        $this->log($productData->getName());


        //modifying ManufacturerNumber
        $this->log($productData->getManufacturerNumber());
        $productData->setManufacturerNumber('Prefix ManufacturerNumber' . $productData->getManufacturerNumber());
        $this->log($productData->getManufacturerNumber());

        $event->getPage()->setProduct($productData);

    }

    /**
     * @param $message
     * @return void
     */
    private function log($message)
    {
        $logFileName = 'someFile.log';
        file_put_contents(
            $logFileName,
            $message . PHP_EOL,
            FILE_APPEND
        );
    }
}


After modifying the above mentioned changes it still shows the original data although
$event->getPage()->setProduct($productData);

I’m in doubt whether ProductPageLoadedEvent is an after dispatching event or before dispatching the event.

need help in password reset system in codeigniter4

i am new in MVC programming, especially CodeIgniter4, i made a login/register system, it works fine,
and i implemented a password reset system :
1- when a user click reset password link a form appears
2- u put your email address and u click submit (the data is sent for validation)
3- if the email is valid and exist in the database a reset link is sent to the user,
4- when the user click the link it redirect him to the reset form
5- u enter your new password and confirm

her is my code :

1- route.php

$routes->post('sendresetlink', 'ResetPwdController::sendresetlink');
$routes->get('redirect/(:num)/(:any)', 'ResetPwdController::loadResetPage/$1/$2'); // 1st param is id, 2nd is token
$routes->post('resetpassword', 'ResetPwdController::updatepassword');

2- ResetPwdController.php

//---------------------------->->- Reset password : step 1
    public function sendresetlink()
    {
        $userModel = new UserModel();
        $toEmail = $this->request->getVar('email2');
        $row = $userModel->where('email', $toEmail)->first();
        if ($row) {
            $mail = new PHPMailer(true);
            try {
                //Server settings
                // $mail->SMTPDebug = SMTP::DEBUG_SERVER;                   //Enable verbose debug output
                $mail->isSMTP();                                            //Send using SMTP
                $mail->Host       = 'smtp.gmail.com';                       //Set the SMTP server to send through
                $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                $mail->Username   = '[email protected]';               //SMTP username
                $mail->Password   = 'E123456';                           //SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
                $mail->CharSet = 'UTF-8';

                //Recipients
                $date = getServerTimestamp();
                $mail->setFrom('[email protected]', "Reset password email {$date}");
                $mail->addAddress($toEmail);     //Add a recipient

                // $pwd = generate_password(8);
                $token = generate_token();
                $id = $row["id"];
                $url   = generate_url("redirect", $id, $token);
                $link  = "<a href='" .  $url . "'>reset password</a>";
                $mail->isHTML(true);
                //Set email format to HTML
                $mail->Subject = 'Password recovery';
                $mail->Body    = 'Your new password :  click the link below ' . $link;
                $mail->AltBody = 'Your new password :  click the link below ' . $link;
                $mail->send();
                $data = ['token' => $token, 'token_active' => 1, 'token_date' => getServerTimestamp()];
                $userModel->where('id', $id)
                    ->set($data)
                    ->update();
                echo json_encode(1);  //ok msg sent with token
            } catch (Exception $e) {
                $ajaxresponse = $mail->ErrorInfo;
                echo json_encode($ajaxresponse); //message not sent 
            }
        } else {
            echo json_encode(2); //wrong email adress
        }
    }
    //---------------------------->->- Reset password : step 2  
    public function loadResetPage($id, $token)
    {
        $userModel = new UserModel();
        $row = $userModel->find($id);

        if ($row) {
            if (isValidToken($row, $token)) {
                $data = array('id' => $id, 'token' => $token);
                echo view('resetpassword', $data); // return view => call a view , return redirect => route
                //    return redirect()->to('ResetPwdController');
            } else {
                echo "<h1>Error 1 : Bad link !</h1>";
                return 0;
            }
        } else {
            echo "<h1>Error 2 : Bad user !</h1>";
            return 0;
        }
    }

    //------------------------------ Reset password : step 3
    public function updatepassword()
    {
        $rules = [
            'password' => [
                'label' => 'Password',
                'rules' => 'required|min_length[4]|max_length[50]|alpha_numeric',
                'errors' => [
                    'required' => 'password is required',
                    'min_length' => 'min length is 5',
                    'max_length' => 'max length is 50',
                    'alpha_numeric' => 'add alpha and numeric',
                ]
            ],
            'confpwd' => [
                'label' => 'Confirm Password',
                'rules' => 'required|matches[password]',
                'errors' => [
                    'required' => 'retype password',
                    'matches' => 'password dont matches',
                ],
            ]
        ];

        if ($this->validate($rules)) {
            $userModel = new UserModel();
            $id = $this->request->getVar('id');
            $token = $this->request->getVar('token');
            $row = $userModel->find($id);
            if ($row) {
                if (isValidToken($row, $token)) {
                    $data = [
                        'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
                        'token_active' => 0,
                        'token' => '',
                        'token_date' => ''
                    ];
                    $userModel->update($id, $data);
                    echo json_encode(1);
                } else {
                    echo json_encode(2); //bad token or expired link
                }
            } else {
                echo json_encode(3); //bad id link
            }
        } else {
            echo json_encode($this->validator->listErrors());
            
        }
    }

3 – my custom helper

    function generate_token($len = 25)
{
  $dumpdata = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  $token = substr(str_shuffle($dumpdata), 0, $len);
  return $token;
}
//------------------------------------------------------
function generate_password($len = 8)
{
  $dumpdata = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#&$%_";
  $token = substr(str_shuffle($dumpdata), 0, $len);
  return $token;
}
//------------------------------------------------------
function generate_url(...$segments)
{
  $url = base_url();
  foreach ($segments as $seg) {
    $url .= '/' . $seg;
  }
  return $url;
}
//------------------------------------------------------
function getServerTimestamp()
{
  date_default_timezone_set('Africa/Algiers');
  $stamp =  date('Y-m-d H:i:s');
  return $stamp;
}
//------------------------------------------------------
function isValidToken($data, $token, $period=24)
{
  $date = date(getServerTimestamp());
  $diff = date_diff2($data['token_date'], $date);
  //print_r("Reset  : {$row['token_date']}<br>Server : {$date}<br>Period : {$diff['asString']}");
  $period_second = $period*60*60;
  return ($data['token'] == $token &&
    $data['token_active'] == 1 &&
    $diff['exceeded'] > 0 &&
    $diff['exceeded'] <= $period_second //validation limit $period_second = $period*60*60
  );
}
//------------------------------------------------------
function date_diff2($date1, $date2)
{
  $diff = strtotime($date2) - strtotime($date1);

  if ($diff <= 0) {
    $asString = "[<br> <b>valid :</b> 0 <br><b>Period : </b>00:00:00:00:00:00<br> Diff : </b>" . strval($diff) . "<br>]";
    $result = array(
      'valid' => 0,
      'year' => 0,
      'month' => 0,
      'days' => 0,
      'hours' => 0,
      'minutes' => 0,
      'seconds' => 0,
      'exceeded' => $diff,
      'asString' => $asString
    );
    return $result;
  }

  $years = floor($diff / (365 * 60 * 60 * 24));
  $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
  $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
  $hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
  $minutes = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
  $seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minutes * 60));
  $asString = '[ <br> <b>valid :</b> 1 <br><b>Period : </b>' .
    strval($years) . ":" .
    strval($months) . ":" .
    strval($days) . ":" .
    strval($hours) . ":" .
    strval($minutes) . ":" .
    strval($seconds) . "<br> <b>Diff : </b>" .
    strval($diff) . "<br>]";
  $result = array(
    'valid' => 1,
    'year' => $years,
    'month' => $months,
    'days' => $days,
    'hours' => $hours,
    'minutes' => $minutes,
    'seconds' => $seconds,
    'exceeded' => $diff,
    'asString' => $asString
  );
  return $result;
}

my issue is as so i am getting an error :
when submitting data in reset form the it don’t send data to the right route and the URL in the browser is the same as the email link
help please
i do not know if it is because of echo view or my logic is wrong?