Getting Error “Trying to access array offset on value of type null” in Laravel while sending Email

I have an online appointment form from where user can take appointment. An email will be generated after taking appointment. But getting below error while sending email.

Trying to access array offset on value of type null

store function inside appointment controller

$emailDataArray = array(
    'appointment_id' => $lastInsertedId,
    'patient_name' => $request->appointment_name,
    'patient_number' => $request->appointment_contact_no,
    'patient_age' => $request->appointment_age,
    'patient_gender' => $request->appointment_gender,
    'branch_name' => $branch_name->name,
    'doctor_name' => $doctor_name->name,
    'schedule_date' => $request->schedule_date,
    'schedule_time' => $schedule_time->schedule_time,
    'purpose' => $purpose->about_us,
);
$email = $this->sendMail($emailDataArray);

sendMail function inside appointment controller

Mail::send('frontend.mail.mail', $emailDataArray, function($message) use ($emailDataArray)
{
    $message->to('[email protected]')->subject('APPOINTMENT');
    $message->from('[email protected]');
});

mail.blade.php

<p>PATIENT NAME &#09;: {{ $patient_name }}</p>
<p>PATIENT NUMBER &#09;: {{ $patient_number }}</p>
<p>PATIENT AGE &#09;: {{ $patient_age }}</p>
<p>PATIENT GENDER &#09;: {{ $patient_gende] }}</p>
<p>BRANCH NAME &#09;: {{ $branch_name }}</p>
<p>DOCTOR NAME &#09;: {{ $doctor_name}}</p> 
<p>DATE &#09;: {{ $schedule_date }}</p>
<p>TIME &#09;: {{ $schedule_time }}</p>
<p>PURPOSE &#09;: {{ $purpose }}</p>

How to solve this? Anybody Help please?

Replace the xml string templates from database dynamically [duplicate]

I have a request that has been stored in the database. when I execute this request

    $sql ="SELECT * FROM `route` WHERE `company` ='SHOFCO'";
    $result = compute::instance()->fetch($sql,false,true);
    $xml = $result['requestTemplate'];

It will return

    $xml ="<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mob="urn:microsoft-dynamics-schemas/codeunit/Mobile_Solutions">
   <soapenv:Header/>
   <soapenv:Body>
      <mob:InsertPaybill>
         <mob:refnumber>$MpesaReceiptNumber</mob:refnumber>
         <mob:pdate>$TransTime</mob:pdate>
         <mob:descriptions>$FullNames</mob:descriptions>
         <mob:amount>$Amount</mob:amount>
         <mob:accountNumber>$PhoneNumber</mob:accountNumber>
         <mob:transactionDate>$TransTime</mob:transactionDate>
         <mob:transactionDescription>$FullNames</mob:transactionDescription>
         <mob:paybillnumber>$PayBillNumber</mob:paybillnumber>
         <mob:referenceNumber>$AccountReference</mob:referenceNumber>
      </mob:InsertPaybill>
   </soapenv:Body>
</soapenv:Envelope>";

Now I want the vairable in the string $MpesaReceiptNumber,$TransTime,FullNames etc to be replaces with the actual values stored in the below varibles.

$MpesaReceiptNumber ="RDT6AZ26DK";
$FullNames ="TEST ALEX";
$TransTime ="2023-04-29";
$Amount ="1";
$PhoneNumber ="0704722837";
$PayBillNumber ="4012913";
$AccountReference ="12345";

Here is my full code

$MpesaReceiptNumber ="RDT6AZ26DK";
$FullNames ="TEST ALEX";
$TransTime ="2023-04-29";
$Amount ="1";
$PhoneNumber ="0704722837";
$PayBillNumber ="4012913";
$AccountReference ="12345";

$sql ="SELECT * FROM `route` WHERE `company` ='SHOFCO'";
$result = compute::instance()->fetch($sql,false,true);
$xml = $result['requestTemplate'];

echo $xml;

When I run my code it just echo without replacing the varibales.

WooCommerce admin settings: TypeError in add_product_attributes_lookup_table_settings()

A few years back I created a plugin (not publicly available) that worked fine for the WooCommerce version I was using (5.8.1).
At some point however, the Admin Settings page stopped working. I notices it only now (with WC 7.6.0) since I hardly ever use that page, so I don´t know what changed and when.

My error is:

Een fout van het type E_ERROR werd veroorzaakt op regelnummer 664 van het bestand <my-document-root>/wp-content/plugins/woocommerce/src/Internal/ProductAttributesLookup/LookupDataStore.php. Foutmelding: Uncaught TypeError: AutomatticWooCommerceInternalProductAttributesLookupLookupDataStore::add_product_attributes_lookup_table_settings(): Argument #1 ($settings) must be of type array, null given in <my-document-root>/wp-content/plugins/woocommerce/src/Internal/ProductAttributesLookup/LookupDataStore.php:664
Stack trace:
#0 [internal function]: AutomatticWooCommerceInternalProductAttributesLookupLookupDataStore->add_product_attributes_lookup_table_settings()
#1 <my-document-root>/wp-content/plugins/woocommerce/src/Internal/Traits/AccessiblePrivateMethods.php(158): call_user_func_array()
#2 <my-document-root>/wp-includes/class-wp-hook.php(308): AutomatticWooCommerceInternalProductAttributesLookupLookupDataStore->__call()
#3 <my-document-root>/wp-includes/plugin.php(205): WP_Hook->apply_filters()
#4 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/settings/class-wc-settings-page.php(130): apply_filters()
#5 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/settings/class-wc-settings-page.php(98): WC_Settings_Page->get_settings_for_section()
#6 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/settings/class-wc-settings-page.php(211): WC_Settings_Page->get_settings()
#7 <my-document-root>/wp-includes/class-wp-hook.php(308): WC_Settings_Page->output()
#8 <my-document-root>/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters()
#9 <my-document-root>/wp-includes/plugin.php(517): WP_Hook->do_action()
#10 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/views/html-admin-settings.php(40): do_action()
#11 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-settings.php(153): include('...')
#12 <my-document-root>/wp-content/plugins/woocommerce/includes/admin/class-wc-admin-menus.php(291): WC_Admin_Settings::output()
#13 <my-document-root>/wp-includes/class-wp-hook.php(308): WC_Admin_Menus->settings_page()
#14 <my-document-root>/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters()
#15 <my-document-root>/wp-includes/plugin.php(517): WP_Hook->do_action()
#16 <my-document-root>/wp-admin/admin.php(259): do_action()
#17 {main}
  thrown

I created a small pretty useless plugin to reproduce this. I think it goes wrong on line 89 (return woocommerce_admin_fields($this->getSettings());). The form with the admin settings is properly displayed, but the submit button doesn´t show and I do get the critical error above.

The code below just adds a settings page to WooCommerce Settintgs -> Products -> Foo Bar

<?php
/**
 * @package Foo_Bar
 * Plugin Name: Foo Bar
 * Description: With this plugin, nothing useful can be done
 * Version: 0.0.0
 * Author URI: http://oveas.com/
 * WC tested up to: 7.6.0
 */
 
if (!defined('ABSPATH')) {
    die;
}

function FooBar_getSettingsId()
{
    return 'foo-bar';
}

function FooBar_Activate()
{
    global $wpdb;

    $settingsId = FooBar_getSettingsId();

    $query = $wpdb->prepare("SELECT * FROM $wpdb->options WHERE `option_name`=%s", $settingsId);

    $db_result = $wpdb->get_row($query);
    if(is_null($db_result) || $db_result == "" || !isset($db_result)) {
        $query = $wpdb->prepare(
              "INSERT INTO $wpdb->options SET "
            . '  option_name = %s'
            . ', option_value = %s'
            . ', autoload = %s'
            , $settingsId
            , 'a:2:{s:10:"option-one";s:7:"default";s:10:"check-this";s:3:"yes";}'
            , 'yes'
        );
        $wpdb->query($query);
    }
}

function FooBar_Deactivate()
{
}

function FooBar_Uninstall()
{
    global $wpdb;

    $settingsId = FooBar_getSettingsId();

    $query = $wpdb->prepare("DELETE FROM $wpdb->options WHERE `option_name` = '$settingsId'", '');
    $db_result = $wpdb->query($query);

    $settings = Display_Options_Config::getInstance()->getSettings(false);
    foreach ($settings as $field => $config) {
        $query = $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE `meta_key` = '" . $config['id'] . "'", '');
        $db_result = $wpdb->query($query);
    }
}

class FooBar
{
    public function __construct()
    {
        if (is_admin()) {
            $this->createAdminSettings();
        }

    }

    public function createAdminSettings()
    {
        add_filter('woocommerce_get_sections_products', array($this, 'addSection'), 10, 1);
        add_filter('woocommerce_get_settings_products', array($this, 'adminSettings'), 10, 2);
    }

    public function addSection($sections)
    {
        $sections['foo-bar'] = 'Foo Bar';
        return $sections;
    }

    public function adminSettings($settings, $currentSection)
    {
        if ($currentSection == 'foo-bar' && function_exists('woocommerce_admin_fields')) {
             // This is where it goes wrong: settings are added, but then there's some fatal
            return woocommerce_admin_fields($this->getSettings());
        } else {
            return $settings;
        }
    }

    public function getSettings()
    {
        $settings['section_title'] = array(
              'name'     => 'Foo Bar'
            , 'type'     => 'title'
            , 'desc'     => 'Some useful description'
            , 'id'       => FooBar_getSettingsId() . '[section-title]'
        );


        $settings['option-one'] = array(
              'name' => 'Option one'
            , 'type' => 'select'
            , 'options' => array(
                  'default'        => 'Use WooCommerce default'
                , 'something-else' => 'Something else'
                , 'both'           => 'Both'
            )
            , 'desc' => 'Make a useful selection'
            , 'id'   => FooBar_getSettingsId() . '[option-one]'
        );

        $settings['check-this'] = array(
              'name' => 'Make a selection'
            , 'type' => 'checkbox'
            , 'desc' => 'Enable or disable this'
            , 'id'   => FooBar_getSettingsId() . '[check-this]'
        );

        return apply_filters('foo-bar-settings', $settings);
    }
}


function FooBar_Execute()
{
    if (in_array( 'woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
        $plugin = new FooBar();
    }
}

register_activation_hook( __FILE__, 'FooBar_Activate' );
register_deactivation_hook( __FILE__, 'FooBar_Deactivate' );
register_uninstall_hook( __FILE__, 'FooBar_Uninstall' );

FooBar_Execute();

I cannot find where and how add_product_attributes_lookup_table_settings() is called, so all suggestions are welcome.
The rest of the plugin (like product specific settings — not in this code example) works fine, it’s just this page.

How to turn off assertion evaluation with no access to php.ini?

With access to php.ini one can turn off assertion evaluation with:

zend.assertions = -1

In shared hosting often one can only use ini_set:

ini_set('assert.active', '0');

But this setting does still evaluate the code in the assertions. In my understanding it does the same as zend.assertions = 0.

Can the effect of zend.assertions = -1 be achieved when there is no possibility to edit php.ini?

Edit:

Based on the answer I’m adding this remark:

ini_set(‘zend.assertions’, …) is prevented by the hosting company.

How to automatically send emails on a person’s birthday using PHP, MySQL, and Angular?

I am currently facing a problem that I cannot solve. I have a web application that uses a PHP API to send emails via the PHP Mailer library. I also have a MySQL database containing a Person table with attributes such as names, first names, and birth dates.

I would like to automatically send an email to each person in my table on their birthday. I have looked for solutions such as the Windows scheduler, but I prefer a more automated solution.

I am looking for ideas on how to solve this problem using PHP, MySQL, and Angular. If anyone has encountered this problem and has a solution, or ideas on how to proceed, I am open to suggestions.

Thank you very much for your help.

I tried to use windows Scheduler as mentioned before but I have to add every action one by one and it is quite slow.

Why is the message sent to the client after the loop process is complete?

I have a problem, why are messages sent to the client sent after the looping process is finished even though every process and before the process I added the function send(); to send a message to the client but the message is received by the client after the looping process is complete, here is the code

  1. how to send message to client with send(); function in realtime and no need to wait for the loop process to finish ?
public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg, true);
    
        if ($data['type'] === 'file') { 
           
        require ('../../conn.php'); 
        $fileName = $data['name'];          
        $username = $data['username']; 
        $usernameMD5 = md5($username);
        $path = $this->uploadsPath.$usernameMD5. DIRECTORY_SEPARATOR .$fileName;        
        $from->send("File '{$fileName}' uploaded and processed.");
        flush();
       
        //cek file
        if (!file_exists($path)) {
            $from->send("File '{$fileName}' not found.");
            return;
          }         
          
          //mulai proses
          $spreadsheet = IOFactory::load($path);
          $sheet = $spreadsheet->getActiveSheet();
          $total_rows = $sheet->getHighestRow() - 1;  

          
          for ($i = 2; $i <= $sheet->getHighestRow(); $i++) { 
            if ($i > $total_rows) {
                $from->send("Processed all rows.");             
                break;
            }
            $from->send("Processed row $i"); // kirim pesan ke client
            flush();       

 
          }          

        }
}  

Please help so I can send messages to the client server while it is looping, in the code above I use ratchet as a websocket.
Thank You

Failed to get sum of a specific row in php [duplicate]

Failed to get total of students in a specific class from mysqli

Am trying to get the sum of students in a specific class from table. I have a code that gets duplicated rows so I want to count those rows based on the Id passed forexample if the Id passed is for a student in class seven, I want to count all rows with seven and display the total number
Here is my code

<div class="bio">
                <span><b>Student's name: </b></span><span class="text-uppercase pl-3"><?php echo $row['student_name'] ?></span><br>
                <span><b>Position in class:</b></span> <span>47</span> out of <span>
                    <?php
                    $id = $_GET['id'];
                       $sql1 = "SELECT sigles, COUNT( sigles ) total_members FROM tbl_student GROUP BY sigles
                       HAVING total_members > 1;";
                       $res1 = mysqli_query($conn, $sql1);
                      //  echo $total_members;
                      $count = mysqli_num_rows($res1);
                      echo $count;
                      
                       

                    ?>
                </span> pupils <br>
                <span><b>Division:</b></span> <span>1</span>
            </div>

this is how my database looks
enter image description here

so am expecting the answer to be 4 since they are 4 sevens in the column

data scraping travel information using PHP

Goodmorning,

I have a question about data scraping using php.
For a travel agency I need to scrape two websites wherby my contractor wants information about the competetion. specific information the need is all the trips that offered/ prices and the attandance.

I also received a php script that I can use but it is a bit technical for me.
Is there someone that can help me to adjust the php script?

Thanks in advance,

Tried to adjust script but didn’t work unfortunatly.

<?php


namespace ScraperNRV;

use GuzzleHttpClient;
use PsrHttpMessageResponseInterface;

class Sawadee extends Scraper
{
    private $client;
    private $maxPages = 30;
    /**
     * @var Cookie
     */
    private $cookies;

   
   # protected $to = 

    /**
     * TUI constructor.
     * @param Cookie $cookies
     */
    public function __construct(Cookie $cookies)
    {
        $this->cookies = $cookies;
    }

    public function scrape()
    {
        $this->fetchUris();
        print_r($this->products);die;
        $onlyFirst = true;
        foreach ($this->products as $product) {
            try {
                //                if ($onlyFirst) {
                $this->updateProductInfo($product['url']);
                $onlyFirst = false;
                //                }
            } catch (Throwable $e) {
                echo $e->getMessage() ."n";
            }
        }
        $this->generateCsv();
        $this->sendMail();
    }

    private $iniUrl = 'reizen/?_smstate=1$5_28_65';
    private $searchPageUrl = 'reizen/?page=';
    private function fetchUris()
    {
        $options = [];
        $response = $this->getClient()->request("GET", $this->iniUrl, $options);
        $this->cookies->update($response);
        $this->parseSearchPage($response);
        for ($p = 2; $p < $this->maxPages; $p++) {
            try {
                $response = $this->getClient()->request("GET", $this->searchPageUrl . $p, $this->getOptions(true));
                if ($response->getStatusCode() !== 200) {
                    echo "Parsed page $p gives http code " . $response->getStatusCode() . "n";
                    break;
                }
                $this->cookies->update($response);
                $this->parseSearchPage($response);
                $wait = rand(1, 5);
                echo "Parsed page $p of {$this->maxPages}, waiting $wait sec.n";
                //                sleep($wait);
            } catch (Throwable $e) {
                echo $e->getMessage() . "n" . $e->getTraceAsString() . "n";
            }
        }
    }

    private $initGridUrl  = 'data/pricegrid/pricegridprices/?clearprices=1';
    private $selectionUrl = 'data/pricegrid/selection/';
    private $receiptUrl   = 'data/pricegrid/priceselect/';
    public function updateProductInfo(string $url)
    {
        $startTime = microtime(true);
        echo "Get page $url - " . date("Y-m-d H:i:s") . "n";
        $this->products[$url] = [
            'url'    => $url,
            'airline' => "",
            'prices' => [],
        ];
        $response = $this->getClient()->request("GET", $url, $this->getOptions(true));
        $this->cookies->update($response);
        if ($response->getStatusCode() !== 200) {
            echo "Parsed page $url gives http code " . $response->getStatusCode() . "n";
            return;
        }
        $dom = new DOMDocument();
        @$dom->loadHTML($response->getBody()->getContents());
        $xpath = new DOMXPath($dom);
        $html = $xpath->query("//html");
        $entityId = $html->item(0)->getAttribute('data-tmd');
        list($theme, $type, $id) = explode("_", $entityId);
        $h1 = $xpath->query("//h1");
        $this->products[$url]['name'] = trim($h1->item(0)->nodeValue);
        $crumbs = $xpath->query("//ul[contains(@class,'crumbtrail')]/li");
        $this->products[$url]['country'] = trim($crumbs->item(0)->nodeValue);
        $response = $this->getClient()->request("POST", $this->initGridUrl, $this->getOptions(true, true, [
            'masterentitytype' => $type,
            'masterentityid'   => $id,
            'theme'            => $theme,
            'firstview'        => 'true',
        ]));
        $this->cookies->update($response);
        if ($response->getStatusCode() !== 200) {
            echo "Parsed page $url gives http code " . $response->getStatusCode() . "n";
            return;
        }
        $this->parsePriceInfo($url, $entityId, $response->getBody()->getContents());
        $proceed = true;
        $direction = 'earlier';
        $previousMessage = '';
        while ($proceed) {
            echo "Price page $url -> $directionn";
            try {
                $response = $this->getClient()->request("POST", $this->selectionUrl, $this->getOptions(true, true, [
                    'MoveRelativeDates' => $direction,
                    'Entity'            => $entityId,
                ]));
            } catch (Throwable $e) {
                echo $e->getMessage() . "n";
                $proceed = false;
                continue;
            }

            $this->cookies->update($response);
            if ($response->getStatusCode() !== 200) {
                echo "Parsed page $url gives http code " . $response->getStatusCode() . "n";
                $proceed = false;
                continue;
            }
            $content = $response->getBody()->getContents();
            if ($previousMessage == $content) {
                if ($direction === 'earlier') {
                    $direction = 'later';
                    continue;
                } else {
                    $proceed = false;
                    continue;
                }
            }
            $previousMessage = $content;
            $json = json_decode($content, true);
            if (!($json['pricegrid'] ?? false)) {
                if ($direction === 'earlier') {
                    $direction = 'later';
                    continue;
                } else {
                    $proceed = false;
                    continue;
                }
            }
            $this->parsePriceInfo($url, $entityId, $json['pricegrid']);
            echo "Price page $url -> $direction donen";
        }
        echo "UpdateProductInfo - " . (microtime(true) - $startTime) . "n";
    }

    private function parsePriceInfo(string $url, string $entityId, string $content)
    {
        $startTime = microtime(true);
        $dom = new DOMDocument();
        @$dom->loadHTML($content);
        $xpath = new DOMXpath($dom);
        $toolTip = $xpath->query("//*[boolean(@data-tui-tooltip-element)]/..");

        foreach ($toolTip as $details) {
            $priceId = $details->getElementsByTagName('span')->item(0)->getAttribute('rev');
            $price = $details->getElementsByTagName('span')->item(0)->nodeValue;
            $date = "";
            $occupation = "";
            $duration = "";
            $board = "";
            $transport = "";
            $departure = "";
            foreach ($details->getElementsByTagName('tr') as $details) {
                $fields = $details->getElementsByTagName('td');
                $name   = $fields->item(0)->nodeValue;
                $value  = $fields->item(1)->nodeValue;
                if (strripos($name, 'bezet') !== false) {
                    $occupation = trim(str_ireplace('n', '', str_ireplace('volwassene', '', $value)));
                } elseif (strripos($name, 'duur') !== false) {
                    $duration = (int) trim(str_ireplace('dgn', '', $value)) - 1;
                } elseif (strripos($name, 'verzorging') !== false) {
                    $board = $value;
                } elseif (strripos($name, 'vervoer') !== false) {
                    $transport = $value;
                } elseif (strripos($name, 'datum') !== false) {
                    $date = $this->parseDate($value);
                } elseif (strripos($name, 'vanaf') !== false) {
                    $departure = $value;
                }
            }
            $datePrice = $this->products[$url]['prices'][$date] ?? [
                    'first'      => true,
                    'date'       => $date,
                    'occupation' => $occupation,
                    'duration'   => $duration,
                    'board'      => $board,
                    'transport'  => $transport,
                    'departure'  => $departure,
                    'price'      => $price,
                    'outbound'   => '',
                    'inbound'    => '',
                    'pax'    => '',
                ];
            if ($price < $datePrice['price'] || $datePrice['first']) {
                //                $info = [];
                //                if (strtolower($transport) == 'vliegtuig') {
                $info = $this->getReceipt($entityId, $priceId);
                //                }
                $datePrice = [
                    'first'      => false,
                    'date'       => $date,
                    'occupation' => $occupation,
                    'duration'   => $duration,
                    'board'      => $board,
                    'transport'  => $transport,
                    'departure'  => $departure,
                    'price'      => $price,
                    'outbound'   => $info['outbound'] ?? '',
                    'inbound'    => $info['inbound'] ?? '',
                    'pax'        => $info['pax'] ?? '',
                ];
            }
            $this->products[$url]['prices'][$date] = $datePrice;
            //error_log(print_r([$date, $occupation, $duration, $board, $transport, $departure, $price], true));
        }
        echo "parsePriceInfo - " . (microtime(true) - $startTime) . "n";
    }

    private function getReceipt(string $entityId, string $priceId): array
    {
        $startTime = microtime(true);
        if (empty($priceId)) {
            echo "Empty price id givenn";
            return ['outbound' => "", 'inbound' => ""];
        }
        $response = $this->getClient()->request("POST", $this->receiptUrl, $this->getOptions(true, true, [
            'PriceSelectionId'  => $priceId,
            'Entity'            => $entityId,
        ]));
        $this->cookies->update($response);
        if ($response->getStatusCode() !== 200) {
            echo "Parsed receipt for price id $priceId gives http code " . $response->getStatusCode() . "n";
            return [];
        }
        $content = $response->getBody()->getContents();
        $json = json_decode($content, true);
        if (!($json['pricegrid'] ?? false)) {
            return [];
        }
        $outbound = [];
        $inbound = [];
        $pax = "";
        $dom = new DOMDocument();
        @$dom->loadHTML($json['pricegrid']);
        $xpath = new DomXPath($dom);

        $classname = "dep-loc";
        $nodes = $xpath->query("//*[contains(@class, '$classname')]");
        if ($nodes->length == 2) {
            $outbound[] = $nodes->item(0)->nodeValue;
            $inbound[] = $nodes->item(1)->nodeValue;
        }

        $classname = "arr-loc";
        $nodes = $xpath->query("//*[contains(@class, '$classname')]");
        if ($nodes->length == 2) {
            $outbound[] = $nodes->item(0)->nodeValue;
            $inbound[] = $nodes->item(1)->nodeValue;
        }
        $classname = "trnsprt";
        $nodes = $xpath->query("//*[contains(@class, '$classname')]");
        if ($nodes->length == 2) {
            $outbound[] = $nodes->item(0)->nodeValue;
            $inbound[] = $nodes->item(1)->nodeValue;
        }
        $classname = "grp-cmpstn-cnt";
        $nodes = $xpath->query("//*[contains(@class, '$classname')]/@data-totalpassengers");
        if ($nodes->length == 1) {
            $pax = $nodes->item(0)->nodeValue;
        }
        echo "getReceipt - " . (microtime(true) - $startTime) . "n";
        return ['outbound' => implode("- ", $outbound), 'inbound' => implode("- ", $inbound), 'pax' => $pax];
    }

    private function parseSearchPage(ResponseInterface $response)
    {
        $dom = new DOMDocument();
        @$dom->loadHTML($response->getBody()->getContents());
        $xpath = new DOMXPath($dom);
        $buttons = $xpath->query("//div[contains(@class,'pricelabel')]/a");

        foreach ($buttons as $button) {
            $this->products[$button->getAttribute('href')] = [
                'url'    => $button->getAttribute('href'),
                'prices' => [],
            ];
        }
    }

    private function getClient(): Client
    {
        if ($this->client === null) {
            return new Client([
                // Base URI is used with relative requests
                'base_uri' => "https://www.tui.nl/",
                $this->getOptions(),
            ]);
        }
        return $this->client;
    }

    private function getOptions(bool $addCookie = false, bool $ajax = false, array $params = []): array
    {
        $options = ['headers' => [
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
            'Host' => 'www.tui.nl',
            'Accept-Encoding' => 'gzip, deflate, br',
            'Connection' => 'keep-alive',
        ],
                    'decode_content' => true];
        if ($addCookie) {
            $options['headers']['Cookie'] = $this->cookies->toString();
        }
        if ($ajax) {
            $options['headers']['X-TS-AJAX-Request'] = "true";
            $options['headers']['X-Requested-With'] = "XMLHttpRequest";
        }
        if (!empty($params)) {
            $options['form_params'] = $params;
        }
        return $options;
    }

    private $months = [
        'januari'   => '01',
        'februari'  => '02',
        'maart'     => '03',
        'april'     => '04',
        'mei'       => '05',
        'juni'      => '06',
        'juli'      => '07',
        'augustus'  => '08',
        'september' => '09',
        'oktober'   => '10',
        'november'  => '11',
        'december'  => '12',
    ];

    private function parseDate(string $date): string
    {
        $parts = explode(' ', $date);
        return sprintf("%s-%s-%02d", $parts[3], $this->months[strtolower($parts[2])], $parts[1]);
    }
}

How to correct output real-time Symfony Process Output without it being considered as an error

I have following Symfony Process which calls a standard git clone command and writes the output in real-time:

$process = new Process(
    [
        'git',
        'clone',
        self::REPOSITORY_URL . $project . '.git',
        $destinationPath
    ]
);

$cli = $this->cli;
$process->run(static function ($type, $buffer) use ($cli) {
    if(Process::ERR === $type) {
        $cli->error($buffer);
    } else {
        $cli->print($buffer);
    }
});

What I get is the output Cloning into '/my/projects/project'..., but formatted as an error.

I was able to pinpoint, that $type always has the value 'err', even during non-error output.

I had this problem before, when I used $process->start() first. Apparently, the process was not considered as finished, therefore I could solve it with $process->wait(). But I didn’t get the output in real-time, thus the usage of $process->run() now. I feel like there might be a way to work with wait() again, but I’m not sure how.

how to set public_path in Laravel 9 on the shared hosting

working with Laravel 9 project and I have following public_path with image access in the blade file

<img src="{{ $message->embed(public_path('images/logo.png')) }}" alt="" style="width: 300px; max-width: 600px; height: auto; margin: auto; display: block;">

this is working fine in my localhost and I have images folder in default public folder in the Laravel. but when I deploy My project to the shared hosting Hostgrator Laravel project public folder containts goes to the public_html folder. any way my other images are working well in live server but above image path not working and encounted following error message

Swift_IoException Unable to open file for reading [/home3/abc/abc/public/images/logo.png] 

I think it is because public_path in the image script. then how could I fix this problem here?

filter using jquery range slider in codeigniter php not working

i have a product list page, where there is a filter option with some checkboxes, the checkbox filters are working fine, now i used range slider to list products between some price range, below is my code:

my view:

function filterProducts(minPrice, maxPrice) {

  var myCheckboxes = new Array();
  $("input[name='types[]']:checked").each(function() {
    myCheckboxes.push($(this).val());
  });

  var myCheckboxes1 = new Array();
  $("input[name='istyles[]']:checked").each(function() {
    myCheckboxes1.push($(this).val());
  });

  var myCheckboxes17 = new Array();
  $("input[name='ocs[]']:checked").each(function() {
    myCheckboxes17.push($(this).val());
  });

  $.ajax({
    url: '<?php echo base_url()?>homecontroller/filterpt',
    type: 'POST',
    data: {
      id: <?=$idz?>,
      types: myCheckboxes,
      istyles: myCheckboxes1,
      mstones: myCheckboxes2,
      ocs: myCheckboxes17,
      minPrice: minPrice,
      maxPrice: maxPrice
    },
    error: function() {
      alert('Something is wrong');
    },
    success: function(data) {
      var count = $('.myth').length;

      $('#marble').html(data);
      $('#count').html(count);
    }
  });
}

$(document).ready(function() {
  $('[name="types[]"], [name="istyles[]"], [name="ocs[]"]').click(function() {
    filterProducts(0, 0);
  });


});



$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 200000,
    values: [0, 200000],
    slide: function(event, ui) {
      $("#amount").val("₹" + ui.values[0] + " - ₹" + ui.values[1]);


      filterProducts(ui.values[0], ui.values[1]);

    }
  });
  $("#amount").val("₹" + $("#slider-range").slider("values", 0) +
    " - ₹" + $("#slider-range").slider("values", 1));
});

my controller:

 public function filterpt() {
        $types=$this->input->post('types');
        $istyles=$this->input->post('istyles');
        $ocs=$this->input->post('ocs');
        $id=$this->input->post('id');
          $min=$this->input->post('minPrice');
    $max=$this->input->post('maxPrice');
       
      
      
          $data = $this->product->filterpt($types,$istyles,$ocs,$id,$min,$max);

my model:

  function filterpt($types,$istyles,$ocs,$id,$min,$max)
      {

       
            $this->db->where('types', $id);
            $this->db->where("status", "Active");
         


if($min >0 || $max >0)
        {
            $this->db->where('jrp >= ',$min);
            $this->db->where('jrp <= ',$max);
        }
        if(isset($istyles)){
          $this->db->where_in('istyles', $istyles);
          }
          
          }

this is my live url:live
however the range slider doesnt show results based on the prices selected, there is some issue going in front end, coz even when i comment the min max where condition in model, the range slider shows random products on selection. can anyone please tell me what is wrong in here.

Load custom external page on wordpress + dynamic url

This might be a tricky one but let’s try.

I’m hosting a wordpress website on domain.com.
This website has several pages such as

domain.com/about
domain.com/product

Now, im having another product which is made as vue website which is hosted on app.domain.com

This vue application is offering option for users to create their own urls such as:

app.domain.com/bill
app.domain.com/michael

on top of that each user can create their own subpages so for example bill user he could create:

app.domain.com/bill/30-minutes
app.domain.com/bill/60-minutes

So, what I would like to do is somehow in my WordPress site to load these external pages so they become like.

domain.com/bill
domain.com/bill/30-minutes

I don’t want to have a redirect, but I want to keep the URL.
So What I can do is some sort of coding to fetch these landing pages,

But my question is how do I rewrite this for WordPress or NGINX that I’m running?
So for example:

domain.com/bill that I should make a request to another page, and not try to load a wordpress page.

Any suggestions are welcome

Thanks in advance.

php not redirecting on login submit with header(Location: …)

I already searched here on stackoverflow and on google but couldn’t solve the problem.

For my login page I used the code here https://github.com/Tutorialwork/Tutorials/tree/ac1ee61c5b43bde9b811759eaabcbed027b56385

With all respect to the developer who originally wrote this code.

When I click on the submit button (named as “Einloggen”) it is not redirecting to the “geheim.php”. This is not working on my server only. If I use XAMPP and put in the database credentials it is working without any problem.

On the server it looks like it is just refreshing the index.php page. There is no error in the Chrome console. I tried it with Chrome and Safari. Both on the Mac.

In the mysql.php the credentials I used are the credentials for the server. I put in the real credentials and not the credentials as in the code. This anyhow is not the problem.

When I echo the variable $count then it gives me value of 1 which means that the connection is working. I used the code like I posted it here. So, the echo I just used for testing purposes. Because I read that echo’s causing problems with “Location”.

When I type in wrong password or wrong user it shows me the echo as expected and written in the code (“Der Login ist fehlgeschlagen”). Means that database is really not the problem.

This line is not working:

header("Location: geheim.php");

I didn’t post the register.php here because it shouldn’t be the cause of the problem.
But you can use it to create a user.

In sql or in PhpMyAdmin I created the database table.

CREATE TABLE accounts (USERNAME varchar(255), PASSWORD varchar(255));

index.php:Main page where I can login.
mysql.php: Contains database credentials.
logout.php: Is doing the logout on the geheim.php page by clicking on the button
geheim.php: The page which should be displayed after I click the submit Button on the index.php

Like I said, the credentials are fine and it is working locally on my computer. It is redirecting, login logout. But when I upload it on the server it is not redirecting.

index.php

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Login</title>
  </head>
  <body>
    <?php
    if(isset($_POST["submit"])){
      require("mysql.php");
      $stmt = $mysql->prepare("SELECT * FROM accounts WHERE USERNAME = :user"); //Username überprüfen
      $stmt->bindParam(":user", $_POST["username"]);
      $stmt->execute();
      $count = $stmt->rowCount();
      if($count == 1){
        //Username ist frei
        $row = $stmt->fetch();
        if(password_verify($_POST["pw"], $row["PASSWORD"])){
          session_start();
          $_SESSION["username"] = $row["USERNAME"];
          header("Location: geheim.php");
        } else {
          echo "Der Login ist fehlgeschlagen";
        }
      } else {
        echo "Der Login ist fehlgeschlagen";
      }
    }
     ?>
    <h1>Anmelden</h1>
    <form action="index.php" method="post">
      <input type="text" name="username" placeholder="Username" required><br>
      <input type="password" name="pw" placeholder="Passwort" required><br>
      <button type="submit" name="submit">Einloggen</button>
    </form>
    <br>
    <a href="register.php">Noch keinen Account?</a>
  </body>
</html>

mysql.php

<?php
$host = "localhost";
$name = "test";
$user = "root";
$passwort = "";
try{
    $mysql = new PDO("mysql:host=$host;dbname=$name", $user, $passwort);
} catch (PDOException $e){
    echo "SQL Error: ".$e->getMessage();
}
 ?>

logout.php

<?php
session_start();
session_destroy();
header("Location: index.php");
 ?>

geheim.php

<?php
session_start();
if(!isset($_SESSION["username"])){
  header("Location: index.php");
  exit;
}
 ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Top Secret</h1>
    <a href="logout.php">Abmelden</a>
  </body>
</html>

PHP Include without username in directory

I am trying to include a PHP file from another folder, one directory up from public_html but currently I can only include that file with the below statement.

include ‘/home/username/auth/test.php’;

How do I include that file without using the username in the directory, your guys help will be much appreciated.