Implementing PHP into Django project [closed]

I have a project done in PHP format and I have to include Python Django to implement my machine learning algorithms such as SVM, random forest, logistic regression, and naive Bayes. Is it possible to do so? Can I use my Django project to include my PHP files? Also, my PHP files are under xampp htdocs while my Django project is under the C: folder

Can you help me with the codings so I can put them in my Django project to include my PHP files?

woocommerce_before_pay_action Not Consistently Saving Order Meta Data

I have a very simple custom gateway plugin intended to store some passive data on Woocommerce orders, no actual processing is taking place. It uses the woocommerce_before_pay_action hook to capture the meta data from the custom woocommerce_form_field payment fields via $_POST and store them in the order meta like this:

function save_cash_custom_fields( $order ){
//If this order had been paid for with cash
if( $order->get_payment_method() === 'ms_cash' ){
    //If the cash_paid_by field is set
    if( isset( $_POST['cash_paid_by'] ) ){
        $order->update_meta_data( 'cash_paid_by', sanitize_text_field( $_POST['cash_paid_by'] ) );
    }
    //If the cash_received_by field is set
    if( isset( $_POST['cash_received_by'] ) ){
        $order->update_meta_data( 'cash_received_by', sanitize_text_field( $_POST['cash_received_by'] ) );
    }
}
add_action( 'woocommerce_before_pay_action', 'save_cash_custom_fields', 10, 1 );

And it works. Sometimes. It’s being really inconsistent, sometimes it captures the data and other times it doesn’t, there are no errors showing and the fields aren’t even being created in the database the times it doesn’t work.

I’ve stepped through the function and output every step of the way, and it’s always there. No errors are being logged anywhere, and the transaction is completing correctly, just this meta data is not being stored.

Can anyone suggest why this is being intermittent? Is the hook not the best option for this?

how to fix it (A PHP Error was encountered Severity: Warning Message: Undefined array key “kapasitas”

A PHP Error was encountered Severity: Warning Message: Undefined array key “kapasitas” Filename: Admin/data_trip.php Line Number: 75

A PHP Error was encountered Severity: Warning Message: Undefined array key “kapasitas” Filename: Admin/data_trip.php Line Number: 75

public function tambah_aksi() {
    // Validasi form
    $this->form_validation->set_rules('nama_gunung', 'Nama Gunung', 'trim|required');
    $this->form_validation->set_rules('harga', 'Harga', 'trim|required|numeric');
    $this->form_validation->set_rules('basecamp', 'Basecamp', 'trim|required');
    $this->form_validation->set_rules('fasilitas', 'Fasilitas', 'trim|required');
    $this->form_validation->set_rules('tanggal', 'Tanggal', 'trim|required');
    $this->form_validation->set_rules('kapasitas', 'Kapasitas', 'trim|required|numeric');

    if ($this->form_validation->run() == false) {
        // Jika validasi gagal, load view 'admin/form_data_trip' untuk menampilkan form input
        $this->load->view('admin/form_data');
    } else {
        // Konfigurasi upload gambar
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = 2048;
        $config['encrypt_name'] = TRUE;

        $this->upload->initialize($config);

        if ($this->upload->do_upload('gambar')) {
            $gambar_data = $this->upload->data();
            $gambar = $gambar_data['file_name'];
        } else {
            $gambar = '';
            $upload_error = $this->upload->display_errors('<p class="error">', '</p>');
            $this->session->set_flashdata('upload_error', $upload_error);
        }

        // Tambahkan data trip baru
        $data_trip = array(
            'nama_gunung' => $this->input->post('nama_gunung'),
            'harga' => $this->input->post('harga'),
            'basecamp' => $this->input->post('basecamp'),
            'fasilitas' => $this->input->post('fasilitas'),
            'gambar' => $gambar
        );

        $id_trip = $this->model_trip->tambahTrip($data_trip);

        // Tambahkan jadwal trip
        $data_jadwal = array(
            'id_trip' => $id_trip,
            'jadwal_trip' => $this->input->post('tanggal'),
            'kapasitas' => $this->input->post('kapasitas')
        );

        // Validasi kapasitas
        $current_capacity = $this->model_trip->getCurrentCapacity($id_trip);
        if ($current_capacity < $this->input->post('kapasitas')) {
            $this->model_trip->tambahJadwal($data_jadwal);
            redirect('admin/trip'); // Redirect ke halaman data trip setelah berhasil menambahkan
        } else {
            $this->session->set_flashdata('kapasitas_error', 'Kapasitas melebihi yang tersedia.');
            redirect('admin/trip/tambah');
        }

I am having an issue with my Laravel Code

I am getting this error when I try to check a particular page of my laravel website

prebuilt.js:184 Uncaught (in promise) FirebaseError: Function where() called with invalid data. Unsupported field value: undefined
at new Ur (prebuilt.js:184:9)
at by (prebuilt.js:16135:16)
at Qp.Lc (prebuilt.js:15738:16)
at prebuilt.js:16052:17
at dy (prebuilt.js:16010:12)
at fy (prebuilt.js:15937:12)
at prebuilt.js:16554:17
at eg._apply (prebuilt.js:16539:40)
at qy (prebuilt.js:16530:30)
at im.where (prebuilt.js:17803:43)

I have tried looking through the codes to identify the undefined variables but it seems like I am not getting it right. It’s still showing the same error message, I believe there’s something I am not getting right

how to find different pages from the downloaded website of appinventiv

i have downloaded the website of the company appinventiv for converting it into the wordpress theme. but when the download of the files have completed i saw that there are 100’s of files and its bit confusing in finding out the pages files from that, how can I find the different pages from the downloaded website easily . what steps should i follow to find the different pages. i tried opening each file and then try understanding them but it is not going well as this process is confusing me alot as the code in each file appears to be same. same header sections same content. now what should I do

Convert PHP openssl_encrypt and openssl_decrypt to GO language [closed]

I’m having a challenge converting the PHP openssl_* functions to GO language. I want to be able to encrypt a text using PHP and decrypt it using GO. This is the PHP functions encryption and decryption:

<?php

function Encrypt($ClearTextData)
{
    $secretKey = 'RJBwYSb5dFcyqUEHD300jY9nhxmi6Lnx';
    try {
        $EncryptionKey = base64_decode($secretKey);
        $InitializationVector = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
        $EncryptedText = openssl_encrypt($ClearTextData, 'AES-256-CBC', $EncryptionKey, 0, $InitializationVector);
        $data = base64_encode($EncryptedText . '::' . $InitializationVector);

        return $data;
    } catch (Exception $ex) {
        throw $ex;
    }
}

function Decrypt($CipherData)
{
    $secretKey = 'RJBwYSb5dFcyqUEHD300jY9nhxmi6Lnx';
    try {
        if (!$CipherData) {
            throw new ErrorException('Empty cipher string', 4004);
        }

        $EncryptionKey = base64_decode($secretKey);
        list($Encrypted_Data, $InitializationVector) = array_pad(explode('::', base64_decode($CipherData), 2), 2, null);
        return openssl_decrypt($Encrypted_Data, 'AES-256-CBC', $EncryptionKey, 0, $InitializationVector);
    } catch (Exception $ex) {
        throw $ex;
    }
}

I want to have the same functions in GO. The decrypt function in GO should be able to decrypt what has been encrypted in PHP

Moodle local installation in local with wamp server

I copy a moodle code folder alraedy costomised from a mac and want to run it on my windows with wamp server. I’ve already modify the config.php file
But when I try to access the web app trough the wamp navigator I got à php Fatal error:

Uncaught error : Cache class not found in ~localdirectory/www/mdl/moodle/lib/classes/string_manager_standard.php on line 82

I try looping for cache option in the navigatrice trough the console and comparate the initial classes files to the one I copy but I can’t find nothing

Why Am I Getting Different Cipher Outputs Between Node.js and PHP When Reading Large Files by Chunks?

Inconsistent Cipher Output Between Node.js and PHP When Reading Large Files by Chunks

Problem Description

I’m facing an issue with ensuring consistent cipher output between Node.js and PHP when reading large files by chunks. The output differs even though the same values are being read and processed. Below is the code for both PHP and Node.js implementations.

PHP Code

<?php
require 'vendor/autoload.php';

define('PLAINTEXT_DATA_KEY', 'poSENHhkGVG/4fEHvhRO6j9W3goETWZAg+ZgTWxhw34=');
define('ENCRYPTED_DATA_KEY', 'AQIDAHg4CVTLXnBsl/PpZjf+n1uhc03fcdvJT7Ytc8qauQHURgE9yj3RsilBWvaeXRwGWajRAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMik8zaXe7Vw+JvKPrAgEQgDsyaXx8zP7xpmOEfMUuqD0VWhp0eAZZHXFWd6KymDhpEp1Y6+Mo8wdYBycT0m96VWw/56pWtXJ+Pngw9g==');
define('IV', "X1bIRjgIoDn/BDFhHIbg7g==");
define('ALGORITHM', 'aes-256-cbc');
define('CHUNK_SIZE', 16 * 1024);

function logMessage($message) {
    echo $message . PHP_EOL;
}
logMessage(CHUNK_SIZE . "n");

class Cipher {
    private function pkcs7_pad(string $data, int $blockSize): string {
        $padLength = $blockSize - (strlen($data) % $blockSize);
        return $data . str_repeat(chr($padLength), $padLength);
    }

    private function pkcs7_unpad(string $data): string {
        $padLength = ord($data[strlen($data) - 1]);
        return substr($data, 0, -$padLength);
    }

    public function encrypt($source, $dest, $calcMd5 = true, $debugMode = true) {
        $flag = true;
        $totalSize = 0;
        $md5Context = $calcMd5 ? hash_init('md5') : null;
        $md5ContextEnc = null;
        if ($debugMode && $flag) {
            $md5ContextEnc = hash_init('md5');
        }

        $initialBuffer = base64_decode(IV) . base64_decode(ENCRYPTED_DATA_KEY);
        $inputFile = fopen($source, 'rb');
        $outputFile = fopen($dest, 'wb');
        $outfileBase64 = null;
        if ($debugMode) {
            $outfileBase64 = fopen('outfiles/encryptedbuffer.log', 'wb');
        }

        try {
            fwrite($outputFile, $initialBuffer);

            while (!feof($inputFile)) {
                logMessage("-----");
                $buffer = fread($inputFile, CHUNK_SIZE);
                logMessage('Read plaintext Len: ' . strlen($buffer));
                $totalSize += strlen($buffer);
                if ($calcMd5 && $md5Context) {
                    hash_update($md5Context, $buffer);
                }
                if (feof($inputFile)) {
                    $buffer = $this->pkcs7_pad($buffer, 16);
                }
                $cipherText = openssl_encrypt($buffer, ALGORITHM, PLAINTEXT_DATA_KEY, OPENSSL_NO_PADDING, base64_decode(IV));
                if ($cipherText === false) {
                    unlink($dest);
                    throw new Exception("Error while encrypting the data.");
                }
                logMessage('cipher text len: ' . strlen($cipherText));

                if ($debugMode && $flag) {
                    hash_update($md5ContextEnc, $cipherText);
                }

                if ($flag) {
                    $md5HashEnc = hash_final($md5ContextEnc);
                    logMessage(("md5 of encrypted file: " . $md5HashEnc));
                    $flag = false;
                }
                $written = fwrite($outputFile, $cipherText);
                if ($debugMode) {
                    fwrite($outfileBase64, base64_encode($cipherText));
                    fwrite($outfileBase64, "n");
                    logMessage('base64 encode cipherText len ' . strlen(base64_encode($cipherText)));
                }

                if ($written !== strlen($cipherText)) {
                    unlink($dest);
                    throw new Exception("Error while writing the encrypted data to file");
                }
            }

        } catch (Exception $e) {
            throw $e;
        } finally {
            fclose($inputFile);
            fclose($outputFile);
        }
        $md5Hash = $calcMd5 ? hash_final($md5Context) : null;
        logMessage('MD5 hash of downloaded data: ' . $md5Hash);
        if ($debugMode && $flag) {
            $md5HashEnc = hash_final($md5ContextEnc);
            logMessage(("md5 of encrypted file: " . $md5HashEnc));
        }
        logMessage("Total size: " . $totalSize);
    }
}

$cipher = new Cipher();
$cipher->encrypt("infiles/a.txt", "outfiles/a.txt.enc");
?>
import { createCipheriv, createHash } from "crypto";
import { BASE64_ENCODING, DATA_EVENT, HEX, MD5 } from "./constants";
import { base64ToBuffer, base64ToUint8Array, bufferToBase64, ensurePaths } from "./common";
import { createReadStream, createWriteStream } from "fs";
import { log } from "console";

const PADDING_BLOCK_SIZE = 16;
const ALGORITHM = "aes-256-cbc";
const PLAINTEXT_DATA_KEY = "poSENHhkGVG/4fEHvhRO6j9W3goETWZAg+ZgTWxhw34=";
const ENCRYPTED_DATA_KEY =
  "AQIDAHg4CVTLXnBsl/PpZjf+n1uhc03fcdvJT7Ytc8qauQHURgE9yj3RsilBWvaeXRwGWajRAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMik8zaXe7Vw+JvKPrAgEQgDsyaXx8zP7xpmOEfMUuqD0VWhp0eAZZHXFWd6KymDhpEp1Y6+Mo8wdYBycT0m96VWw/56pWtXJ+Pngw9g==";
const IV = "X1bIRjgIoDn/BDFhHIbg7g==";

const CHUNK_SIZE = 16 * 1024; 

class Cipher {
  private pkcs7Pad(buffer: Buffer, blockSize: number = PADDING_BLOCK_SIZE): Buffer {
    const padding = blockSize - (buffer.length % blockSize);
    const padBuffer = Buffer.alloc(padding, padding);
    return Buffer.concat([buffer, padBuffer]);
  }

  private pkcs7Unpad(buffer) {
    const padding = buffer[buffer.length - 1];
    return buffer.subarray(0, buffer.length - padding);
  }

  async encrypt(source: string, dest: string, calcMd5: boolean = true, debugMode: boolean = false) {
    let flag = true;
    const iv = base64ToBuffer(IV);
    let hash: any;
    let hashEnc: any;
    if (calcMd5) {
      hash = createHash(MD5).setEncoding(HEX);
    }
    if (debugMode && flag) hashEnc = createHash(MD5).setEncoding(HEX);

    const cipher = createCipheriv(ALGORITHM, base64ToUint8Array(PLAINTEXT_DATA_KEY), iv);
    cipher.setAutoPadding(false);

    await ensurePaths(dest);

    const readStream = createReadStream(source, { highWaterMark: CHUNK_SIZE });
    const writeStream = createWriteStream(dest, { highWaterMark: CHUNK_SIZE });

    let encryptedBase64WriteStream;
    if (debugMode) {
      await ensurePaths("outfiles/encrypt/encrypted-buffer.log");
      encryptedBase64WriteStream = createWriteStream("outfiles/encrypt/encrypted-buffer.log", { highWaterMark: CHUNK_SIZE });
    }

    const encryptedDataKeyBuffer = Buffer.from(ENCRYPTED_DATA_KEY, BASE64_ENCODING);
    const initialBuffer = Buffer.concat([iv, encryptedDataKeyBuffer]);
    writeStream.write(initialBuffer);

    let totalSize = 0;
    let tempChunkStorage = Buffer.alloc(0);
    readStream.on(DATA_EVENT, (chunk) => {
      totalSize += chunk.length;

      if (typeof chunk === "string") {
        chunk = Buffer.from(chunk);
      }

      tempChunkStorage = Buffer.concat([tempChunkStorage, chunk]);

      while (tempChunkStorage.length >= CHUNK_SIZE) {
        const block = tempChunkStorage.subarray(0, CHUNK_SIZE);
        log(`Read plaintext Len: ${block.length}`);
        writeStream.write(block);

        if (calcMd5) hash.update(block);

        const encryptedBuffer = cipher.update(block);
        console.log(`cipher text len: ${encryptedBuffer.length}`);
        if (debugMode) encryptedBase64WriteStream.write(bufferToBase64(encryptedBuffer) + "n");
        if (debugMode && flag) hashEnc.update(encryptedBuffer);

        console.log(`base64 encode cipherText len: ${bufferToBase64(encryptedBuffer).length}`);

        if (flag) {
          const finalHashEnc = hashEnc.digest("hex");
          log(`MD5 hash of encrypted data: ${finalHashEnc}`);
          flag = false;
        }
        // process.exit();

        tempChunkStorage = tempChunkStorage.subarray(CHUNK_SIZE);
        log(`Leftover data size: ${tempChunkStorage.length}`);
      }
    });
    readStream.on("end", () => {
      if (tempChunkStorage.length > 0) {
        log(`Writing remaining data of size: ${tempChunkStorage.length}`);
        writeStream.write(tempChunkStorage);
        if (calcMd5) hash.update(tempChunkStorage);

        const encryptedBuffer = cipher.update(this.pkcs7Pad(tempChunkStorage));
        console.log(`cipher text len: ${encryptedBuffer.length}`);

        if (debugMode) encryptedBase64WriteStream.write(bufferToBase64(encryptedBuffer) + "n");

        if (debugMode && flag) hashEnc.update(encryptedBuffer);

        cipher.final();
      }

      writeStream.end();
      if (calcMd5) {
        const finalHash = hash.digest("hex");
        log(`MD5 hash of downloaded data: ${finalHash}`);
      }
      if (debugMode && flag) {
        const finalHashEnc = hashEnc.digest("hex");
        log(`MD5 hash of encrypted data: ${finalHashEnc}`);
      }

      log("Finished downloading.");
      log("Total size: " + totalSize);
    });
    readStream.on("error", (err) => {
      log("Error downloading: " + err);
      writeStream.close();
    });
  }
}

const test = async () => {
  const cipher = new Cipher();
  await cipher.encrypt("outfiles/rawinputfiles/a.txt", "outfiles/encrypt/a.txt.enc", true, true);
};
test();

First few bytes of encrypted data (base64)

PHP: 2SV3m3J4+vp+ZAX/LBrKjfKVzayHCPjaVbP2ws6hYvVtFW6xdxm8FwjhTA5JsNMYyjXdRggFXpCIjKJb2FX19h5NQnEm2hbVTJEhK1iakzeGpQTR2JpQFXX3gw8++/2XFdBP3MdKGd4mRqzDN4F3XFvkO7DXici5H6ND0R223MxhCht1ICnsQFdZudbZhWd2oyHB04gPrkmts+MdoMTZ2biSdrui3nROSuXW41oraQijwwLMMSMAEAT8ZszxIplL3yYzQdP1X8c11tgzRsB3pBuBbFqhuPYi6qD6ws5un0RC1Uo2ZW03GJ8t3uhgBnewd02wnnpNifknviI5m6enZj1kHN9Eq/GZqt9tvdTL0s0+vg2Z5dUOpqi/

NodeJS:

tFV7iqTTCwsFoQAGmOpWPZOqE0yqDRTJHzBKs6eKafHfsxeZBqIBubz9ZiLd06trzmsYBnWT46B+Jxx+kio17dKYqyYQ61eGOKWs3hHStobi5854PSbx97acyCzCQmuQ8Nif3bps5GRAkJl77O6OzswxlD8YEvAByAqAI40fq+lMPASu41dvWOsFP0TOak36EKDoUGRhNeDmItcgAXKydrDjbyz5LEi

Text File:
text

WooCommerce php – how to show all Product Categories? (WordPress, Astra)

I am working on a Shop Page in WordPress, using WooCommerce and Astra. I want to display all the product categories on the product page. However, Astra only displays one single category.
In the official WordPress forum it sais that this can be fixed with php. However, they’re not giving any more information on how exactly.

Since I’m not capable of writing php, I was wondering if anyone could help me with this.

Thanks for reading,
Reiskeks

How to get letters from a folder in Cyrillic?

I want to receive all letters from a folder in Cyrillic
I tried many different functions, but I didn’t find a working method, everything is ok with other folders

$folder = "Название папки на кирилице" ;
imap_open("{imap.example.com}/".$folder, $login, $password);

i get error

Notice: Unknown: [CLIENTBUG] SELECT No such folder. sc=xQG456O15YuQ0_200927_imap-production-586 (errflg=2) in Unknown on line 0

I tried
imap_utf7_decode() and iconv

How to get SQLite error in PHP/Laravel when quoted column does not exist

Related to my previous question, I found out that due to an error I made, Laravel generates a wrong SQL query:

select * from "companies" where "companies"."id" = '9c54986f-8284-4da9-b826-c7a723de279b' and "companies"."deleted_at" is null and "company_id" = '9c54986f-8284-4da9-b826-c7a723de279b'

The problem here is that company_id does not exist in companies; however, the query does not generate an error when run, it just returns no result.

I suppose the problem here is that "company_id" is treated as a literal instead of a column reference; if I remove the quotes I get a proper error:

Error: in prepare, no such column: company_id (1)

I also get a proper error if I add the table prefix to the column name:

sqlite> select * from "companies" where "companies"."id" = '9c54986f-8284-4da9-b826-c7a723de279b' and "companies"."deleted_at" is null and "companies"."compa
ny_id" = '9c54986f-8284-4da9-b826-c7a723de279b';
Error: in prepare, no such column: companies.company_id (1)

Is there a way to solve this problem by acting on Laravel’s or SQLite’s configuration? I cannot alter how the queries are generated, as they are generated by the framework itself.

Why WHERE clause is not working in fetching data from database in dataTable

whenever i use Where clasue in query, it is not working

i want to show some specific data by condition

i tried this below –
$query = “SELECT * FROM batch_details where ins_name=’safi’ “;
but when i use where clause in query it doesn`t work

//fetch.php

include('database_connection.php');

$column = array("id", "batch_student_name","student_marks");

$query = "SELECT * FROM `batch_details` ";

if(isset($_POST["search"]["value"]))
{
    $query .= '
    WHERE batch_student_name LIKE "%'.$_POST["search"]["value"].'%" ';
}

if(isset($_POST["order"]))
{
    $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY id ASC ';
}

$query1 = '';

if($_POST["length"] != -1)
{
    $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$statement = $connect->prepare($query);

$statement->execute();

$number_filter_row = $statement->rowCount();

$result = $connect->query($query . $query1);

$data = array();

foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row['id'];
    $sub_array[] = $row['batch_student_name'];
    $sub_array[] = $row['student_marks'];
    
    $data[] = $sub_array;
}

function count_all_data($connect)
{
    $query = "SELECT * FROM `batch_details` ";

    $statement = $connect->prepare($query);

    $statement->execute();

    return $statement->rowCount();
}

$output = array(
    'draw'      =>  intval($_POST['draw']),
    'recordsTotal'  =>  count_all_data($connect),
    'recordsFiltered'   =>  $number_filter_row,
    'data'      =>  $data
);

echo json_encode($output);

My php form on my website is ending blank submissions to my email [duplicate]

Below is the php code i have on my website. We have been getting some email form submissions that are working but we have also been getting a large amount of empty submissions. When i try to submit a form without filling it out the site wont allow it. BUT lately a. lot have been coming in looking like this.

“Information Submitted:
Name:
Email:
Phone:
Message:

Is this someone trying to hack my site?

I am very new to coding/backend web development and have basically taught myself everything through youtube so i definitely need some help.

$userName       = $_POST['name-3'];
$userPhone      = $_POST['name-2'];
$userEmail = htmlspecialchars($_POST['email-2']);
$userMessage    = $_POST['email-3'];

$to             = "[email protected]";
$subject        = "Email from my website";
$body           = "Information Submitted:";

$body .= "rn Name: " . $userName;
$body .= "rn Email: " . $userEmail;
$body .= "rn Phone: " . $userPhone;
$body .= "rn Message: " . $userMessage;

mail($to, $subject, $body);///

if (filter_var($userEmail, FILTER_VALIDATE_EMAIL)){
    
 //email is valid
} else {
    //email is invalid
}

if ($_POST['submit']) {
    if (mail ($to, $subject, $body, $from)) { 
       $success = "Message successfully sent";
    } else {
        $success = "Message Sending Failed, try again";
    }
}

My site is hosted on Cpannel through Godaddy. In my web files, there is an error log that tells me “Undefined array key “submit” in /send.php” for each line of the fields below. I feel like this is going to be a super simple fix and I would appreciate the help!

I have tried adding different validations and such but in general I am just confused.

How to reset password without email using token in Laravel?

I’m trying to implement a password reset functionality in my Laravel application without requiring the email address, using only the reset token. I encountered an issue because the Password::tokenExists method requires both the token and user data, but there’s no straightforward way to get user data with only the token.

Here’s my current approach:

Store the reset token in the remember_token column of the users table.
Retrieve the user based on the remember_token.
Validate the token.
Reset the password if the token is valid.
Here’s my implementation:

public function resetPassword(Request $request) {
    try {
        $request->validate([
            'token' => 'required|string',
            'password' => 'required|string|min:8'
        ]);

        $user = User::where('remember_token', $request->token)->first();

        // Validate the token
        if (!$user || !Password::tokenExists($user, $request->token)) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid or expired token.',
            ], 400);
        }

        // Reset the password
        $user->password = Hash::make($request->password);
        $user->remember_token = null;
        $user->save();

        // Remove the reset token after successful password reset
        Password::deleteToken($user);

        return response()->json([
            'status' => true,
            'message' => 'Password has been reset successfully.',
        ]);

    } catch (ValidationException $e) {
        return response()->json([
            'status' => false,
            'message' => $e->getMessage(),
            'errors' => $e->errors(),
        ], 422);

    } catch (Exception $e) {
        return response()->json([
            'status' => false,
            'message' => $e->getMessage(),
        ], $e->getCode() ?: 500);
    }
}

My questions are:

  • Is storing the reset token in the remember_token column and retrieving the user based on this token a good approach?
  • Are there any better or more secure methods to achieve password reset functionality without requiring the email address?

Any suggestions or improvements would be greatly appreciated!