When deleting uploaded images, it trigger the store button instead of performing delete action

I posted this previously, but after checking the code back and dig deeper, I found the delete button code and thus I’ll post the updated info here.
Uploading the images has no problem but when deleting the uploaded images, it triggers the store button instead. I recorded the error here, https://youtu.be/Eq3Y8s2G2GE . I am wondering why is this happening ? I tried to change things here and there but it is still the same. The following are my code. Please help.

Storing the images initially

public function store(Request $request)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'description' => 'required|max:150',
            'category_id' => 'required',
            'type_id' => 'required',
            'price' => 'required|numeric|min:0|not_in:0',
            'start_date' => 'required',
            'end_date' => 'required',
            'is_active' => 'required',
            'images.*' => 'image|max:2048', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        $product = DB::table('products')
            ->insertGetId([
                'name' => $data['name'],
                'description' => $data['description'],
                'type_id' => $data['type_id'],
                'category_id' => $data['category_id'],
                'price' => $data['price'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'is_password' => $request['is_password'],
                'is_stamping' => $request['is_stamping'],
                'created_at' => now(),
            ]);

        // handle image uploads
        if ($request->hasFile('images')) {
            $i = 1;
            foreach ($request->file('images') as $image) {
                $name = $request['name'] . '-' . $i;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $image->getClientOriginalExtension();
                //$fileName = Str::slug($request['name']) . '-' . time() . '.' . $image->getClientOriginalExtension();
                $path = $image->storeAs('public/Product/Images', $fileName);
                DB::table('product_images')->insert([
                    'product_id' => $product,
                    'name' => $name,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
                $i++;
            }
        }
}
        return Redirect::route('produk.index');
    }

Editing the uploaded images afterwards, deleting or adding more images

public function update(Request $request, $id)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'description' => 'required|max:150',
            'category_id' => 'required',
            'type_id' => 'required',
            'price' => 'required|numeric|min:0|not_in:0',
            'start_date' => 'required',
            'end_date' => 'required',
            'is_active' => 'required',
            'images.*' => 'image|max:2048', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        DB::table('products')
            ->where('id', $id)
            ->update([
                'name' => $data['name'],
                'description' => $data['description'],
                'type_id' => $data['type_id'],
                'category_id' => $data['category_id'],
                'price' => $data['price'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'is_active' => $data['is_active'],
                'is_password' => $request['is_password'],
                'is_stamping' => $request['is_stamping'],
                'updated_at' => now(),
            ]);

        // handle image uploads
        if ($request->hasFile('images')) {
            //DB::table('product_images')->where('product_id', $id)->delete();
            //Storage::deleteDirectory('public/Product/Images/' . $id);
            foreach ($request->file('images') as $image) {
                $name = $request['name'] . '-' . $id;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $id . '.' . $image->getClientOriginalExtension();
                $path = $image->store('public/Product/Images/' . $fileName);
                DB::table('product_images')->insert([
                    'product_id' => $id,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
            }
        }
return Redirect::route('produk.index');
    }

The button that gets triggered,

const formik = useFormik({
        initialValues: {
            name: action === "create" ? "" : `${data.name}`,
            description: action === "create" ? "" : `${data.description}`,
            category_id: action === "create" ? "" : `${data.category_id}`,
            type_id: action === "create" ? "" : `${data.type_id}`,
            price: action === "create" ? "" : `${data.price}`,
            is_active: action === "create" ? "" : `${data.is_active}`,
            start_date: action === "create" ? "" : `${data.start_date}`,
            end_date: action === "create" ? "" : `${data.end_date}`,
            // is_password: action === "create" ? "" : `${data.is_password}`,
            // is_stamping: action === "create" ? "" : `${data.is_stamping}`,
        },
        validationSchema: validationSchema,

        onSubmit: async (values) => {
            try {
                switch (action) {
                    case "create":
                        await post(route("produk.store"));
                        Swal.fire({
                            text: "Maklumat produk berjaya disimpan",
                            icon: "success",
                        });
                        break;
                    case "update":
                        await put(route("produk.update", product.id), data);
                        Swal.fire({
                            text: "Maklumat produk berjaya dikemaskini",
                            icon: "success",
                        });
                        break;
                }
            } catch (error) {
                Swal.fire({
                    icon: "error",
                    title: "Oops...",
                    text: "Something went wrong!",
                });
            }
        },
    });

    return (
        <form method={"post"} onSubmit={formik.handleSubmit}>

                        ....................
FileUpload component where the delete button lies in it
<FileUpload
    uploadedFiles={product_images?.flatMap((file) => file)}
    product={product}
    action={action}
    setData={setData}
    onError={(error) => {
            Swal.fire({
            text: error,
            icon: "error",
    });
    }}
            name="images"
            buttonText="Muat Naik"
            allowedFileTypes={[
                "image/png",
                "image/jpg",
                "image/jpeg",
            ]}
    />

Delete button to remove file upload when adding product

    const removeFileUpload = (e, index) => {
        const updatedFileUpload = [...fileUpload];
        updatedFileUpload.splice(index, 1);
        setFileUpload(updatedFileUpload);
        setData(name, updatedFileUpload);
    };

Delete button to remove img when editing/updating product

return (
                   ...........
                    
        <button
           onClick={() => removeFileUpload(index)}
           className="outline-none border-none"
         >
           <FaTimes className="text-red-600" />
        </button>
.....

Possible PHP Bug in Date Validation with DateTime::createFromFormat

Hello I hope everyone’s Ok and I hope I0m mistaken but I use a little code to validate dates in order to check that the client input is a valid and real date
I use

function validateDate($date, $format="Y-m-d H:i:s"){
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

Everything was working fine until this late night, as I was checking some code and I was getting some of my own custom error messages saying that the date was invalid. So I started echoing some data with the following code

    $date = "2023-04-02 02:48:27";
    var_dump($date);
    $d = DateTime::createFromFormat("Y-m-d H:i:s", $date);
    var_dump($d->format("Y-m-d H:i:s"));

And the result shecked me:

string '2023-04-02 02:48:27' (length=19)
string '2023-04-02 03:48:27' (length=19)

The weird thing is that it only happens when the hour is 02, if i type another hour this doesn’t happen.

Do you think this is a bug or am I doing something wrong?

I’m using php 7.4, I’m about to upload it but this was weird so you can know!

Anchor Links inside TCPDF leading to incorrect position

I am using TCPDF in PHP to create an e-book style PDF. It consists of a two pages for the introduction, a TOC page added at the bottom of the code using the addTOC() function and multiple chapters of HTML text and images. For each chapter, I add a bookmark. The bookmark, as used in the TOC, references the correct position.

In addition, I need to create a link to a previously added chapter inside the HTML text. For this reason, after adding the bookmark I immediately add a link to the current position using the AddLink() and SetLink() functions and write the links to an array.

$bookmarkid=$pdf->Bookmark($chno." ".$chapter["title"], 0, 0, '', 'B', array(0,64,128));
$targetlink=$pdf->AddLink();
$pdf->SetLink($targetlink,$pdf->getY(),$pdf->PageNo());
$pdf->Link($targetlink,0,$bookmarkid,$pdf->getY());
$chanker[$chno]=$targetlink;

This way, I can replace my temporary anchors in the HTML and insert the correct link returned by the AddLink() function.

foreach($chanker as $no=>$anker){
  $text=str_replace("#ch_$no","#$anker",$text);
}

All this said, these internal links are clickable, but lead to some completely wrong positions (e.g. not a 1 page offset, but seemingly random).

What reasons could there be for this behavior? Is there some better way to add these internal links?

Edit: added code
Edit 2: modified code, it was the wrong version

Sending outlook’s mails in laravel

I am facing a problem with sending mails using outlook account in php laravel the exception messages says :

Swift_TransportException
Connection could not be established with host smtp-mail.outlook.com :stream_socket_client(): Unable to connect to tcp://smtp-mail.outlook.com:587 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)

my .env file :

MAIL_DRIVER=smtp MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
MAIL_USERNAME=mail
MAIL_PASSWORD=password
[email protected]
MAIL_FROM_NAME=${APP_NAME} MAIL_ENCRYPTION=tls

Thank’s in advance!

WooCommerce programmatically created order hook

In my scenario I need to fix orders that come without shipping costs. This script works.
But it only works if orders are made on the shop-frontend!
Whenever an order is created by script/plugin, it doesn’t get recognized.

Usually, I use the hook woocommerce_checkout_order_processed.
Now I found the hook save_post_shop_order, which works somehow but fires about 6x and only one time with shipping data.

Problem: I need the correct shipping data. Many hooks I tried don’t work at all or don’t give me shipping details within the order data.

What is the correct hook for orders created with

$order = new WC_Order($order_id);
.
.
.
$order-> save();

Button on html table to delete and edit the table only works for the first row at a time, irrespective of the row i chose to edit

This is the table

 <table class="table table-bordered">
                                        <thead>
                                        <tr>
                                            <th><strong>Description</strong></th>
                                            <th><strong>Maximum Vote</strong></th>
                                            <th><strong>Actions</strong></th>
                                        </tr>


                                        <?php
                                        $sql ="SELECT * FROM positions ORDER BY priority ASC";
                                        $result = mysqli_query($conn, $sql);
                                        mysqli_close($conn);


                                        while ($rows=$result->fetch_assoc())

                                        {


                                        ?>
                                        </thead>
                                        <tbody>


                                        <tr>
                                            <td>
                                                <i class="fab fa-angular fa-lg text-danger me-3"></i> <strong><?php echo $rows['description'];?></strong>
                                            </td>
                                            <td><?php echo $rows['max_vote'];?></td>
                                            <td>
                                                 <button
                                                        type="button"
                                                        class="btn btn-sm btn-primary"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#edit"
                                                        data-id='<?php echo $rows['id']; ?>'

                                                >
                                                    <i class="bx bx-edit-alt me-1"></i>Edit
                                                </button>

                                                <button
                                                            type="button"
                                                            class="btn btn-sm btn-danger"
                                                            data-bs-toggle="modal"
                                                            data-bs-target="#delete"
                                                            data-id='<?php echo $rows['id']; ?>'>


                                                    <i class="bx bx-trash me-1"> </i>Delete
                                                    </button>

                                            </td>
                                        </tr>

                                        </tbody>

                                        <?php

                                        }


                                    ?>
                                    </table>

And this is the modal I’m using

<div class="container mt-3">
    <div class="col-lg-4 col-md-6">
        <div class="mt-3">

            <!-- Modal -->
            <div class="modal fade" id="edit" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel1">Edit Position</h5>
                            <button
                                    type="button"
                                    class="btn-close"
                                    data-bs-dismiss="modal"
                                    aria-label="Close"
                            ></button>
                        </div>
                        <div class="modal-body">
                            <div class="card mb-4">



                                <div class="card-body">
                                    <form action="positions_edit.php?id=<?php echo $rows["id"]; ?>" method="post">
                                        <input type="hidden" class="id" id="id" name="id"/>
                                        <div class="mb-3">

                                            <label class="form-label" for="description">Description</label>
                                            <input type="text" class="form-control" id="description" name="description" value="<?php echo $rows['description'];?>" />
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label" for="max_vote">Maximum Vote</label>
                                            <input type="text" class="form-control" id="max_vote"  name="max_vote" value="<?php echo $rows['max_vote'];?>" />
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                                Close
                                            </button>
                                            <button type="submit" class="btn btn-danger" name="edit">Update</button>
                                        </div>


                                    </form>
                                </div>
                            </div>

                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>










<!-- DELETE -->

<div class="container mt-3">
    <div class="col-lg-4 col-md-6">
        <div class="mt-3">

            <!-- Modal -->
            <div class="modal fade" id="delete" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel1">Deleting...</h5>
                            <button
                                    type="button"
                                    class="btn-close"
                                    data-bs-dismiss="modal"
                                    aria-label="Close"
                            ></button>
                        </div>
                        <div class="modal-body">
                            <div class="card mb-4">


                                <div class="card-body">
                                    <form action="positions_delete.php?id=<?php echo $rows["id"]; ?>" method="post">
                                        <div class="mb-3">
                                            <div class="text-center">
                                                <p>DELETE POSITION</p>
                                               <strong><h2><?php echo $rows["description"]; ?></h2></strong>

                                            </div>

                                            <input type="hidden" class="id" id="id" name="id"/>

                                        </div>



                                </div>



                            </div>

                        </div>
                                                          <div class="modal-footer">
                                                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                                              Close
                                                            </button>
                                                              <button type="submit" class="btn btn-danger" name="delete">Delete</button>
                                                          </div>

                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

I queried the from action of the modal but its seems the problem is still there.
so what I basically want to achieve is for any row I decide to delete, the modal should show the details of that particular row and make changes to that row. But in my case for any row I decide to edit or delete the modal shows details of the first row

How do I use regex to replace any hostname in a url

I have several thousand posts in my wp site which have hard coded URLs to images on various domain names (live URL, development URL, UAT url etc). For example:

 <img src="https://prod.domain.com/wp-content/image-path.jpg" 
 srcset="https://dev.domain.com/wp-content/image-path.jpg, 
         https://dev.domain.com/wp-content/image-path.jpg,
         https://another.different-domain.com/wp-content/image-path.jpg">

 <img src="https://another.different-domain.com/wp-content/image-path.jpg" 
 srcset="https://another.different-domain.com/wp-content/image-path.jpg, 
         https://another.different-domain.com/wp-content/image-path.jpg,
         https://another.different-domain.com/wp-content/image-path.jpg">

I need to be able to search and replace any host from the string (full html tag) with a specific host. Basically redirecting everything to the CDN. At a later date Ill clean up the DB.

I’ve tried the following regex in a regex generator online which seems to produce the matches I need. However, when I take this to code it doesnt work and the $new_html_tag variable is null.

https://regex101.com/r/zePZRO/1

$filtered_image = /*html as per regex demo*/
$new_html_tag = preg_replace('(?<=https://).*?(?=/wp-content)', 'https://new-domain.com', $filtered_image);

Doctrine ODM query to dwo Dotuments

I have two documents in Symfony6 and I would like to query them with a single aggregation.

The documents are not related, but they have one common field: “name”.

I would like to create an autocomplete that searches through two documents by the “name” field and merges them.

I tried using facet and aggregation but unfortunately without success 🙁

I encounter the following message while installing a WordPress theme

I encounter the following message while installing a WordPress theme:

NOTICE: ZipArchive and Shell Exec are not enabled on this server please talk to your host or server admin about enabling ZipArchive or Shell Exec on this server or manually extract archive then choose Advanced > Manual Extract in installer.

Image:

enter image description here

Searching on Google did not solve my problem

multiple checked box filter not showing data

I am trying to filter search result based on brand so it is in array form.Suppose I have two brand check box When I check any one of the check box then it show data but when I both checkthen it show no data . Please help me to fix

I tried var_dump($sql); then it show data brand data in this way

string(13) "Adidas','Zara"

Here is the code

 if (isset($search_params['brand']) && is_array($search_params['brand']) && count($search_params['brand']) > 0) {
        $brands = $search_params['brand'];
        $placeholders = rtrim(str_repeat(':brand, ', count($brands)), ', ');
        $sql .= " AND products_brand.brand_name IN ($placeholders)";
        $data['brand'] = implode("','", $brands);
    }

 $data[':status'] = $search_params['status'];
        echo var_dump($data);
        return $db->read($sql, $data);

PHP: Many entrys form one file show on a website

I have a Problem i want to search in an file with content like this:

startstring 01.01.1970 00:00:00endstring
otherstartstring Blabla.par
Blabla2.par
Blabla3.par
Blabla4.par
}
startstring 01.02.1970 00:00:00endstring
otherstartstring Blabla.par
}
startstring 01.03.1970 00:00:00endstring
otherstartstring Blabla.par
Blabla2.par
}
startstring 01.03.1970 00:00:00endstring
otherstartstring Blabla.par
Blabla2.par
Blabla3.par
Blabla4.par
}

and show on a website (and import in a MariaDB Database):

date=01.01.1970 00:00:00
text=Blabla. Blabla2. Blabla3. Blabla4.

For now i have the script for just one “Blabla.”

$date = array();
$text = array();
foreach ($file as $line) {
    if (strpos($line, "startstring ") !== false) {
        $date[] = substr($line, strpos($line, "startstring") + 14, 19);
    }
    if (strpos($line, "otherstartstring") !== false) {
        $text[] = substr($line, strpos($line, "otherstartstring") + 27, -6);
    }
}

TCPD: How to make text only appear in the browser preview

When you create buttons in TCPDF the buttons are only visible in the browser preview.
After saving the file, all the buttons disappear from the pdf document.

I want to have a simple text displayed in the browser preview. After downloading the pdf file the text should disappear just like the buttons do.

Is there a way to achieve this?

I’m beginner in mongodb need the query to get below respose [closed]

enter image description hereI have two table transaction and employee.enter image description here

Lookup on emplyee table
Group By on :- user_id
Filter on : coupon_users_details.created_at (format ‘Y-m-d’)

[
{
“user_id”: 9,
“name”:”abc”,
“coupon_amount”:[
{
“is_cancelled”:1,
“coupon_amount”:20
},
{
“is_cancelled”:1,
“coupon_amount”:20
}
]
},
{
“user_id”: 9,
“name”:”abc”,
“coupon_amount”:[
{
“is_cancelled”:1,
“coupon_amount”:20
},
{
“is_cancelled”:1,
“coupon_amount”:20
}
]
}
]

Join two tables and display images in array based on id in php mysql

I am trying to join 2 tables based on the id. I want to display the second table images to be displayed together in a single array
art_column {
id : 66
name : Test2
title : Art 2
image : null
art_work : {Penguins.jpg},{Tulips.jpg}
}

Table artcolumn stores id,name,image,title
Table artwork_images store a_id,art_work
Joining id and a_id i get the data but how can i store in array in the given format

Here is the code

    $result = ("SELECT artcolumn.id,title, image,name,art_work FROM artcolumn JOIN               artwork_images ON artwork_images.a_id = artcolumn.id") or die(mysqli_error());
    $sql=mysqli_query($con,$result);

if (mysqli_num_rows($sql) > 0) {
    // looping through all results items node
    $response["artcolumn"] = array();
    while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
        // temp user array
        $news = array();
        $news["id"] = $row["id"];
       
       
        $news["name"] = $row["name"];
            $news["title"] = $row["title"];
         $news["image"] = $row["image"];
        
       $news["art_work"] = $row["art_work"];
     
        array_push($response["artcolumn"], $news);
 
    }

In my code id,name,title,images get repeated for second image also

How to prvent XSS attack in html output tag? [duplicate]

I’m new to html, and I’m trying to prvent XSS attack in html output tag like

.
for example here is a some simple html code to text XSS hacking

<!DOCTYPE html>
<html>
  <head>
    <link rel="icon" type="image/x-icon" href="icon.png">
  </head>
<body>
  <style>
    
    #edit {
      position: absolute;
      left: 50%;
      top: 90%;
      transform: translate(-50%, -50%);
      width: 250px;
      height: 50px;
      background-color: #34495E;
      font-size: 18px;
      color: white;
      
    }

    #texta {
      height: 90%;
      width: 100%;
    }
  </style>
  
  <?php
  $myfile = fopen("text", "r+") or die("Unable to open file!");
  if (filesize("text") == 0) {
      $con = null ;
  } else {
      $con = fread($myfile,filesize("text"));
  }
  
  ?>
  <p><?php echo$con; ?></p>

  <form action="save.php" method="post">
    <textarea id="texta" name="txt" rows="30" cols="150"><?php echo $con; ?></textarea>

    <input type="Submit" id= "edit" value="Save">
  </form>
  

</body>
</html>

and here is the save.php which save the text in textarea.

<?php

$text = $_POST["txt"];
$file = fopen("text", "w+");
fwrite($file, $text);
fclose($file);
header("location: index.php");
die();
?>

I hacked it with XSS so easly, what should I add to the code to prevent XSS hack?