PHP GET data from URL and save it to variable

  • script should get the utm_source, utm_campaign and id from the url of the accessing visitor;
  • save them as variables;
  • list on the page like in the example:

“Hello, you are a special guest because you were recommended by our partner (insert utm_source) so we are giving you a (insert utm_campaign )% discount for your first purchase!”

“Please use this special discount code to get your discount: (insert code generated from first 2 characters of the utm_source + last 2 char of the id + utm_campaign , all should be CAPITALIZED)”

Example visitor link:
https://myurl.com?utm_source=Google& utm_campaign =30&id=11228d

Please help!

After clicking button change text and keep it even after reopen window with sessions

I am new to laravel and php and I am trying to change text after clicking button and keep it that way even after reopening window. I use sessions for this purpose.

<?php
    $bool = $_SESSION["add"];
    if ($bool == true) {
        $text = "Remove from shopping cart";
        ?>
        <button onclick="doSomething()" class="corner" id="test">{{$text}}</button>
       <?php

    } else {
        $text = "Add to shopping cart";
        ?>
        <button onclick="doSomething()" class="corner" id="test">{{$text}}</button>
        <?php
        }


function doSomething() {
    if ($text === "Add to shopping cart") {
        $_SESSION["add"] = true;
        echo "<meta http-equiv='refresh' content='0'>";


    } else {
        $_SESSION["add"] = false;
        echo "<meta http-equiv='refresh' content='0'>";
    }
}

This is my code in the beginning I defined variable bool which is value from add in sessions. I bool is true or 1, it will set button with text Remove from shopping cart, else it will set text of button as Add to shopping cart. Tell me if I am wrong but I think this should run even if key add is not defined.utton function is doSomething, I am sorry for not very original name I will fix it afterwards. And the ideabehind this function is that if the text is Add to shopping cart, then it will set session key add as true and with function which i found here:
Refresh page after form submitting
and here:https://www.w3schools.com/tags/att_meta_http_equiv.asp
it should if i understand it correctly immediately refresh page with the new value of add and with this I am aiming to change the text.

As code goes:
If I run it, it will immediately display button with text Remove from shopping cart(when I show bool it show it as 1), but when i click at it it just do nothing

Anybody know what is the issue?

Laravel session got lost

As you can see, I use this method to store my session,

but sometimes it will not working, but sometimes workings well.

This function is to check cart is exist or not.

protected function Check_Cart() {
    $this->cart_no = MDL_Cart::get_session_cart_no($this->company_no, $this->group_buy_no);
    if($this->cart_no === '') {
        MDL_Cart::Add_new_cart();
    }
}

and I will call this funcrion first to check cart is exist in session or not.

protected function Request_Get_Cart_All_Data() {
    $check_cart = $this->Check_Cart();
    // ...
}

Then I will use this function to get session

protected function Get_Cart_Order_Type() {
    $cart_no = MDL_Cart::get_session_cart_no($this->company_no, $this->group_buy_no);
    // ...
}

And I use this method to store my session.

Add_new_cart() {
    Session::forget('group_cart_data.' . $company_no);
    Session::put('group_cart_data.' . $company_no, $cart_no);
    Session::save();
}

public static function get_session_cart_no($company_no, $group_buy_no = null) {
    if ($group_buy_no) {
        return Session::get('group_cart_data.' . $company_no);
    } else {
        return Session::get('cart_data.' . $company_no);
    }
}

When I get session, only Request_Get_Cart_All_Data() has the session, but Get_Cart_Order_Type() cannot get the same session, why?

I’m sure that the session is been writed at Request_Get_Cart_All_Data() because I print the session out to look.

How to get exact value from url in php CI?

I try to get encrypted value from url request in PHP CI

Link example = abc.com/?txTd=369gx4NCCyF+eV3YE0veng==

When i try to get txTd, the output is different

$book_id = $_GET[‘txTd’]; the the result is 369gx4NCCyF eV3YE0veng==

+ is missing from the string. Is there anyway to get exact url ? or the encryption key should be change ?

EDIT
I try to put every symbol in the txTd. and the result is if there are #& in the middle of the value , the rest of value will not be shown, and also if there is + , + will change to space. So is there any way to encrypt without #&+ symbols?

UpdateOrCreate not updating data – Laravel Eloquent

I am new to laravel.
I have an issue when I am trying to update or create record in DB.
I have a table called DspAccountFee with this columns:
enter image description here

I want to create record of dsp_account_id + screen_type when the combination not exists, and to update if the combination exists.
this is my code: (just tried to update the first row keys of -> dsp_account_id(5187) + screen type (ctv). However nothing changed.

DspAccountFee::updateOrCreate(
                ['dsp_account_id' => $dsp_account_id, 'screen_type' => 'ctv'],
                ['pmp_percent' =>$fields['fee_ctv_pmp_percent'], 'omp_percent' => $fields['fee_ctv_omp_percent']]
                );

When I print the values before the DB operation they exists:

Log::info("dsp_account:");
Log::info($dsp_account_id);
Log::info("ctv pmp percent:");
Log::info($fields['fee_ctv_pmp_percent']);
Log::info("ctv omp percent:");
Log::info($fields['fee_ctv_omp_percent']);
Log::info("app pmp percent:");

enter image description here

What I am missing why it is not update the db? Nothing in logs and No exception

this is my method in the model

protected $fillable = array(
        'dsp_account_id', 'screen_type'
    );

Creating a file that returns an image from an external server

As the title says, I want to create a file that returns an image from an external server without downloading / storaging it. I tried something with PHP headers, but it didn’t work as intended (I can’t find the code right now sorry). For example, if we have an image_displayer.php file.

image_displayer.php?url=https://example.com/images/epic_image.png

This URL should return the “https://example.com/images/epic_image.png” image. This image will be displayed from an HTML file from the same server. I couldn’t get it working with PHP headers (it was giving problems in the HTML file)
It doesn’t have to be in PHP. It doesn’t matter to me.
Thanks in advance.

Refund with Amelia using PayPal v2 REST API?

I have used the Amelia Booking plugin for my one of the site.

I would like to implement the split payment & refund to customer functionality with PayPal payment gateway.

I made one addon which can split the payment using PayPal payout APIs(https://api-m.sandbox.paypal.com/v1/payments/payouts).

Split is working fine but to make a refund I need customer’s PayPal details.

So I did below things:

Amelia is storing the transaction information in the database in below format.

{   
    "data": 
    {        
     "PayerId": "4ABCDEFGHIJKL",                 
     "PaymentId": "PAYID-ABCDEFGHIJKLMNO2PQRSTUVW", 
     "transactionReference": "PAYID-ABCDEFGHIJKLMNO2PQRSTUVW"
    }, 
    "amount": "00.00", 
    "gateway": "payPal", 
    "currency": "USD"
}

So from above information I can access “transactionReference” to fetch the customer’s details using (https://api-m.sandbox.paypal.com/v1/payments/payment/{transactionReference}) API call to make refund.

But unfortunately this endpoint is deprecated, so is there anyway to fetch the customer’s PayPal data using above information from PayPal v2 API ?

regex failed to scrap all images

I am trying to scrap all images from an e-commerce website using php,
but the problem is it didn’t scrap all images,(30% of image failed to be scraped)
his the code:

    <?phpfor ($i = 2; $i < sizeof($count); $i++) {?>
        <?php preg_match_all('|<img.*?src=['"](.*?)['"].*?>|i', $html, $matches); ?>
        <img src=<?php echo $matches[1][$i] ?> class="card-img-top">
   <?php}?>
    ?>

I couldn’t find the solution , I have tried many regex but none of them worked
can anyone please help me to find a better regex to scrap all images.

How to move the Laravel timestamps column to a special location

I want to move timestamps columns to a specific location. Let’s pretend I already have an app running on a production server with the following schema:
ORDERS

Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

So after a few days, I added the following columns:

  $table->foreignId('user_id')->constrained('users');
            $table->foreignId('address_id')->constrained('user_addresses');
            $table->string('payment_method')->nullable();
            $table->string('payment_status')->default('pending');
            $table->string('order_status')->default('in_cart');
            $table->text('note')->nullable();
            $table->decimal('total', 8, 2)->default(0);
            $table->string('waybill')->nullable();
            $table->string('logistic')->nullable();
            $table->dateTime('payment_at')->nullable();

The problem here is that all these columns are added after timestamps, but I don’t want to add them after timestamps. I want to add them between id and timestamps. Also, I don’t want to lose already created timestamps.

How to save custom form data into database in magento 2.4

I have a custom for (ss below). enter image description here

The problem I am having is that, When I add something and then click on save button, it redirects me to Catalog/Category when the form is located in CONTENT/Element/Frequently Asked Questions and has nothing to do with Catalog/Category.

I don’t know why it would go to Catalog/category and when it redirects to Category page, it also gives me an error (ss below)enter image description here

Below is my Save.php located under MagebitFaqControllerAdminhtmlQuestionSave.php

<?php
declare(strict_types=1);

namespace MagebitFaqControllerAdminhtmlQuestion;

use MagentoFrameworkExceptionLocalizedException;

class Save extends MagentoBackendAppAction
{
    protected $dataPersistor;

    /**
     * @param MagentoBackendAppActionContext $context
     * @param MagentoFrameworkAppRequestDataPersistorInterface $dataPersistor
     */
    public function __construct(
        MagentoBackendAppActionContext $context,
        MagentoFrameworkAppRequestDataPersistorInterface $dataPersistor
    ) {
        $this->dataPersistor = $dataPersistor;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @return MagentoFrameworkControllerResultInterface
     */
    public function execute()
    {
        /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        if ($data) {
            $id = $this->getRequest()->getParam('id');

            $model = $this->_objectManager->create(MagebitFaqModelQuestion::class)->load($id);
            if (!$model->getId() && $id) {
                $this->messageManager->addErrorMessage(__('This Add new FAQ form no longer exists.'));
                return $resultRedirect->setPath('*/*/');
            }
            $model->setData($data);

            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('You saved the Faq.'));
                $this->dataPersistor->clear('faqquestionform');

                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId()]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the faq form.'));
            }

            $this->dataPersistor->set('faqquestionform', $data);
            return $resultRedirect->setPath('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}

The other Save.php located under MagebitfaqUiComponentFormButtonSave.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By: MageDelight Pvt. Ltd.
 */
namespace MagebitFaqUiComponentFormButton;
use MagentoCmsBlockAdminhtmlPageEditGenericButton;
use MagentoFrameworkViewElementUiComponentControlButtonProviderInterface;
use MagentoUiComponentControlContainer;
class Save extends GenericButton implements ButtonProviderInterface
{
    /**
     * Get button data
     *
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Save'),
            'class' => 'save primary',
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'faq_question_form.faq_question_form',
                                'actionName' => 'save',
                                'params' => [false],
                            ],
                        ],
                    ],
                ],
            ],
            'class_name' => Container::SPLIT_BUTTON,
            'options' => $this->getOptions(),
        ];
    }
    /**
     * Retrieve options
     *
     * @return array
     */
    protected function getOptions()
    {
        $options[] = [
            'id_hard' => 'save_and_close',
            'label' => __('Save & Close'),
            'data_attribute' => [
                'mage-init' => [
                    'buttonAdapter' => [
                        'actions' => [
                            [
                                'targetName' => 'faq_question_form.faq_question_form',
                                'actionName' => 'save',
                                'params' => [true],
                            ],
                        ],
                    ],
                ],
            ],
        ];
        return $options;
    }
}

and below is my custom form called faq_question_form.xml located under MagebitFaqviewadminhtmlui_component where I have this save button

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">faq_question_form.faq_question_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">Category Information</item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
        <item name="reverseMetadataMerge" xsi:type="boolean">true</item>
    </argument>
    <settings>
        <buttons>
            <button name="back" class="MagebitFaqUiComponentFormButtonBack"/>
            <button name="save" class="MagebitFaqUiComponentFormButtonSave"/>
        </buttons>
        <namespace>faq_question_form</namespace>
        <dataScope>data</dataScope>
        <deps>
            <dep>faq_question_form.faq_question_form_data_source</dep>
        </deps>
    </settings>
    <dataSource name="faq_question_form_data_source">
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
        <settings>
            <validateUrl path="catalog/category/validate"/>
            <submitUrl path="catalog/category/save"/>
        </settings>
        <dataProvider class="MagebitFaqModelQuestionDataProvider" name="faq_question_form_data_source">
            <settings>
                <requestFieldName>id</requestFieldName>
                <primaryFieldName>id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <fieldset name="general" sortOrder="5">
        <settings>
            <collapsible>false</collapsible>
            <label/>
        </settings>
        <field name="id" formElement="hidden">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
            </settings>
        </field>
        <field name="parent" formElement="hidden">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
            </settings>
        </field>
        <field name="path" formElement="hidden">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
            </settings>
        </field>
        <field name="level" formElement="hidden">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
        </field>
        <field name="store_id" formElement="hidden">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <dataType>number</dataType>
            </settings>
        </field>
        <field name="is_active" sortOrder="10" formElement="checkbox">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">category</item>
                    <item name="default" xsi:type="number">1</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">false</rule>
                </validation>
                <dataType>boolean</dataType>
                <label translate="true">Enable Question</label>
            </settings>
            <formElements>
                <checkbox>
                    <settings>
                        <valueMap>
                            <map name="false" xsi:type="string">0</map>
                            <map name="true" xsi:type="string">1</map>
                        </valueMap>
                        <prefer>toggle</prefer>
                    </settings>
                </checkbox>
            </formElements>
        </field>
        <field name="question" sortOrder="30" formElement="input">
            <settings>
                <dataType>string</dataType>
                <label translate="true">Question</label>
            </settings>
        </field>
        <field name="answer" formElement="textarea" sortOrder="40">
            <settings>
                <dataType>string</dataType>
                <label translate="true">Answer</label>
            </settings>
        </field>
    </fieldset>
</form>

My custom module folder structure is is below ss:

enter image description here

How can I get the data from this custom form and save into my custom db table without it redirecting to a random place?

Exclude custom Woocommerce function for specific product type child elements in minicart, cart & checkout

Have search all over the internet wondering if it is possible to exclude current function for specific product type child elements in cart and checkout. I have a custom code which set the prices for multicurrency. In my store I use woocommerce composite type products which are set from real products into package which you could choose on the website and add them to cart with specified discount you set in product admin settings.

Problem is that my code overrides the code from the plugin so I do not get discount and I see prices from my custom meta fields. I have been investigating how the plugin actually works and the best solution how to fix this would be to exclude my code from the composite product and its child elements in cart, minicart and checkout. Problem is that I did not find the ideal solution to do it.

I have tried to apply the code only to simple and variable products but It also disabled the composite childs because composite product is made of other products so under composite you have simple or variable products packed together with applied discount.

In plugin files I have found this code, which recognises the product type in cart.

foreach ( $cart_object->cart_contents as $cart_item_key => $cart_item ) {
                        // child product price
                        if ( ! empty( $cart_item['wooco_parent_id'] ) ) {
                            $parent_product = wc_get_product( $cart_item['wooco_parent_id'] );

                            if ( $parent_product && $parent_product->is_type( 'composite' ) ) {
                                if ( method_exists( $parent_product, 'get_pricing' ) && ( $parent_product->get_pricing() === 'only' ) ) {
                                    $cart_item['data']->set_price( 0 );

                                }

My code – I set up product prices for several languages for multicurrency with this function

add_filter( 'woocommerce_get_price', 'display_super_sale_pricex', 10, 2 );
add_filter('woocommerce_product_get_sale_price', 'display_super_sale_pricex', 10, 2); 
function display_super_sale_pricex( $price, $product ) {
    
    
    /*foreach ( $cart_item as $cart_item_key => $item ) {
    $parent_product = wc_get_product( $item['wooco_parent_id'] );
    }*/
    //if ($product->is_type( 'simple' ) && !$parent_product ){
        if(weglot_get_current_language()=='cs'){
            if( !empty ($product->get_meta('woocommerce_mena_zlava_kc')) ){
            $price = $product->get_meta('woocommerce_mena_zlava_kc');
        }else{
            $price = $product->get_meta('woocommerce_mena_kc');
        }} 
    
        if(weglot_get_current_language()=='hu'){
            if( !empty ($product->get_meta('woocommerce_mena_hufa')) ){
            $price = $product->get_meta('woocommerce_mena_hufa');
        } else {
            $price = $product->get_meta('woocommerce_mena_huf');
        }}  
    
        if(weglot_get_current_language()=='ro'){
            if( !empty ($product->get_meta('woocommerce_mena_leia')) ){
            $price = $product->get_meta('woocommerce_mena_leia');
        } else {
            $price = $product->get_meta('woocommerce_mena_lei');
        }}
    
    return $price;
    //}
}

Is there any possibility to exclude my code for the composites product child elements in cart, minicart and checkout within this funcion? Thanks in advance.

How to get value of text area using PHP?

This is sub page code of my project here here user can edit text so I have used text-area but the problem here is I don’t know how to get text or value of text-area using PHP so I can update it back to serve?

<?php

$eid = $_GET['id'];

$con = mysqli_connect("localhost","root","","news") or die("Connection Failed!");
$sql = "SELECT * From content where pid = {$eid}";
$result = mysqli_query($con, $sql) or die("Query Failed!");

$t = mysqli_fetch_assoc($result);

?>

<html>
  <head></head>
  <link rel="stylesheet" href="bootstrapcssbootstrap.min.css">
<body>

<div class="container mt-2">
  <h1><?php echo $t['title'] ?></h1>
  <textarea type="text" name="edit-box" id="edit-box" class="w-75 p-3 mt-3 h-75">
      <?php echo $t['article'] ?>
  </textarea>
  <button type="button" name="button" class="btn btn-primary mb-4">Update</button>
</div>


<!-- PHP: Sending updated data to server -->
<?php
  
?>


</body>

</html>

Yii2 query give different result with sql query

I have 2 table

Table1
| id | name |
| ——– | ————– |
| 1 | Ulrich |
| 2 | Stern |

Table2
| id | school | tid|
| ——– | ————– | ——– |
| 1 | A | 1 |
| 2 | B | 1 |

I want to join 2 table to get all information. With SQL query like this

SELECT Table1.id, name, school FROM `Table1`
INNER JOIN `Table2`
ON Table1.id = Table2.tid

It gives me all information as I expect (I mean 2 rows with name ‘Ulrich’).

But when I do with Yii2 query

$query = self::find();
$query -> alias('t1')
       -> innerJoin(['t2'=>'Table2'], 't1.id=t2.tid')

$result = NULL;
if($total = $query->count()) {
    $result = $query
             -> select([t1.*, t2.school])
             ->asArray()
             ->all()
                ;
    $result[0]['count'] = $total;
}

it only gives me 1 row with name ‘Ulirch’.

Can anyone help me with this problem. Thank you very much.

Ajax fetching data from database

I have an input field with the date type, and there is a database that contains data with dates. I need that when selecting a date in the date field without refreshing the page, all the data associated with this date will be displayed. Please help with code