Bootstrap multiple images cropper upload problem

Herewith is a bootstrap code for cropping multiple images in a modal. I can’t figure out how to collect all cropped images and upload them into the images folder. I appreciate any help

index.php: contains the form and the modal

<?php
require 'admin/upload.php';
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Crop multiple images with cropper js</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <style>
            .g-height-50 {
                height: 50px;
            }
            .g-width-50 {
                width: 50px !important;
            }
            @media (min-width: 0){
                .g-pa-30 {
                    padding: 2.14286rem !important;
                }
            }
            .g-bg-secondary {
                background-color: #fafafa !important;
            }
            .u-shadow-v18 {
                box-shadow: 0 5px 10px -6px rgba(0, 0, 0, 0.15);
            }
            .g-color-gray-dark-v4 {
                color: #777 !important;
            }
            .g-font-size-12 {
                font-size: 0.85714rem !important;
            }
            .media-comment {
                margin-top:20px
            }
            .singleImageCanvasContainer{
                overflow: hidden;
                width: auto;
                height: auto;
                display: inline-block;
                position: relative;
                padding-right: 0px;
                margin-right: 15px;
                border: 2px solid #dfdfdf;
                margin-bottom: 10px;
                padding: 4px;
                border-radius: .25rem;
            }
            .singleImageCanvasContainer .singleImageCanvasCloseBtn{
                position: absolute;
                right: 0;
            }
            .singleImageCanvasContainer .singleImageCanvas{
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        </style>
    </head>
    <body>
        <div class="container m-5">
            <div class="row">
                <div class="col-md-12">
                    <input type="file" name="file" id="file" accept="image/*" multiple />
                </div>
            </div>
        </div>
        <div class="modal" id="cropperModal">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Upload Images</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <form action="index_template.php" method="POST" id="myform" enctype="multipart/form-data">
                        <input type="hidden" id="post_img_data" name="image_data_url[]">
                        <div class="modal-body p-4">
                            <div class="img-preview"></div>
                            <div id="galleryImages"></div>
                            <div id="cropper">
                                <canvas id="cropperImg" width="0" height="0"></canvas>
                                <button type="button" class="cropImageBtn btn btn-danger" style="display:none;" id="cropImageBtn">Crop</button>
                            </div>
                            <div id="imageValidate" class="text-danger"></div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary ">Upload</button>
                        </div>
                    </form>
                    <?php
                    print_r($_FILES['image_data_url']);
                    ?>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.min.js" integrity="sha512-E4KfIuQAc9ZX6zW1IUJROqxrBqJXPuEcDKP6XesMdu2OV4LW7pj8+gkkyx2y646xEV7yxocPbaTtk2LQIJewXw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.min.css" integrity="sha512-Aix44jXZerxlqPbbSLJ03lEsUch9H/CmnNfWxShD6vJBbboR+rPdDXmKN+/QjISWT80D4wMjtM4Kx7+xkLVywQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
        <script>
            $(document).ready(function () {
                $("body").on("change", "#file", function (e) {
                    $('.singleImageCanvasContainer').remove();
                    $('#post_img_data').val('');
                });
            })
        </script>
        <script>
            var c;
            var galleryImagesContainer = document.getElementById('galleryImages');
            var imageCropFileInput = document.getElementById('file');
            var cropperImageInitCanvas = document.getElementById('cropperImg');
            var cropImageButton = document.getElementById('cropImageBtn');
            function imagesPreview(input) {
                var cropper;
                var img = [];
                if (input.files.length) {
                    var i = 0;
                    var index = 0;
                    for (let singleFile of input.files) {
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            var blobUrl = event.target.result;
                            img.push(new Image());
                            img[i].onload = function (e) {
                                var singleCanvasImageContainer = document.createElement('div');
                                singleCanvasImageContainer.id = 'singleImageCanvasContainer' + index;
                                singleCanvasImageContainer.className = 'singleImageCanvasContainer';
                                var singleCanvasImageCloseBtn = document.createElement('button');
                                var singleCanvasImageCloseBtnText = document.createTextNode('X');
                                singleCanvasImageCloseBtn.id = 'singleImageCanvasCloseBtn' + index;
                                singleCanvasImageCloseBtn.className = 'singleImageCanvasCloseBtn';
                                singleCanvasImageCloseBtn.classList.add("btn", "btn-sm");
                                singleCanvasImageCloseBtn.onclick = function () {
                                    removeSingleCanvas(this)
                                };
singleCanvasImageCloseBtn.appendChild(singleCanvasImageCloseBtnText);singleCanvasImageContainer.appendChild(singleCanvasImageCloseBtn);
                                var canvas = document.createElement('canvas');
                                canvas.id = 'imageCanvas' + index;
                                canvas.className = 'imageCanvas singleImageCanvas';
                                canvas.width = e.currentTarget.width;
                                canvas.height = e.currentTarget.height;
                                canvas.onclick = function () {
                                    cropInit(canvas.id);
                                };
                                singleCanvasImageContainer.appendChild(canvas)
                                var ctx = canvas.getContext('2d');
                                ctx.drawImage(e.currentTarget, 0, 0);galleryImagesContainer.appendChild(singleCanvasImageContainer);
                                (document.querySelectorAll('.singleImageCanvas').length == input.files.length) {
                                document.querySelectorAll('.singleImageCanvas')[0].getAttribute('id');
                                urlConversion();
                                index++;
                            };
                            img[i].src = blobUrl;
                            i++;
                        }
                        reader.readAsDataURL(singleFile);
                    }
                }
            }
            imageCropFileInput.addEventListener("change", function (event) {
                $('#cropperModal').modal('show');
                var mediaValidation = validatePostMedia(event.target.files);
                if (!mediaValidation) {
                    var $el = $('#file');
                    $el.wrap('<form>').closest('form').get(0).reset();
                    $el.unwrap();
                    return false;
                }
                $('#mediaPreview').empty();
                $('.singleImageCanvasContainer').remove();
                if (cropperImageInitCanvas.cropper) {
                    cropperImageInitCanvas.cropper.destroy();
                    cropperImageInitCanvas.width = 0;
                    cropperImageInitCanvas.height = 0;
                    cropImageButton.style.display = 'none';
                }
                imagesPreview(event.target);
            });
            // Initialize Cropper
            function cropInit(selector) {
                c = document.getElementById(selector);
                if (cropperImageInitCanvas.cropper) {
                    cropperImageInitCanvas.cropper.destroy();
                }
                var allCloseButtons = document.querySelectorAll('.singleImageCanvasCloseBtn');
                for (let element of allCloseButtons) {
                    element.style.display = 'block';
                }
                c.previousSibling.style.display = 'none';
                // c.id = croppedImg;
                var ctx = c.getContext('2d');
                var imgData = ctx.getImageData(0, 0, c.width, c.height);
                var image = cropperImageInitCanvas;
                image.width = c.width;
                image.height = c.height;
                var ctx = image.getContext('2d');
                ctx.putImageData(imgData, 0, 0);
                cropper = new Cropper(image, {
                    aspectRatio: 3 / 1,
                    viewMode: 4,
                    preview: '.img-preview',
                    crop: function (event) {
                        cropImageButton.style.display = 'block';
                    }
                });
            }
            function image_crop() {
                if (cropperImageInitCanvas.cropper) {
                    var cropcanvas = cropperImageInitCanvas.cropper.getCroppedCanvas({
                        width: 250, height: 250
                    });
                    var ctx = cropcanvas.getContext('2d');
                    var imgData = ctx.getImageData(0, 0, cropcanvas.width, cropcanvas.height);
                    c.width = cropcanvas.width;
                    c.height = cropcanvas.height;
                    var ctx = c.getContext('2d');
                    ctx.putImageData(imgData, 0, 0);
                    cropperImageInitCanvas.cropper.destroy();
                    cropperImageInitCanvas.width = 0;
                    cropperImageInitCanvas.height = 0;
                    cropImageButton.style.display = 'none';
                    var allCloseButtons = document.querySelectorAll('.singleImageCanvasCloseBtn');
                    for (let element of allCloseButtons) {
                        element.style.display = 'block';
                    }
                    urlConversion();
                } else {
                    alert('Please select any Image you want to crop');
                }
            }
            cropImageButton.addEventListener("click", function () {
                image_crop();
            });
            function removeSingleCanvas(selector) {
                selector.parentNode.remove();
                urlConversion();
            }
            function urlConversion() {
                var allImageCanvas = document.querySelectorAll('.singleImageCanvas');
                var convertedUrl = '';
                canvasLength = allImageCanvas.length;
                for (let element of allImageCanvas) {
                    convertedUrl += element.toDataURL('image/jpeg');
                    convertedUrl += 'img_url';
                }
                document.getElementById('post_img_data').value = convertedUrl;
            }
        </script>
        <script>
            function validatePostMedia(files) {
                $('#imageValidate').empty();
                let err = 0;
                let ResponseTxt = '';
                if (files.length > 10) {
                    err += 1;
                    ResponseTxt += '<p> You can select maximum 10 files. </p>';
                }
                $(files).each(function (index, file) {
                    if (file.size > 1048576) {
                        err += 1;
                        ResponseTxt += 'File : ' + file.name + ' is greater than 1MB';
                    }
                });
                if (err > 0) {
                    $('#imageValidate').html(ResponseTxt);
                    return false;
                }
                return true;
            }
        </script>
        <script>
            $(document).ready(function () {
                        $('.upload').click(function () {
                    canvas = cropper.getCroppedCanvas({
                        width: 400,
                        height: 400
                    });
                    canvas.toBlob(function (blob) {
                        url = URL.createObjectURL(blob);
                        var reader = new FileReader();
                        reader.readAsDataURL(blob);
                        reader.onloadend = function () {
                            var base64data = reader.result;
                            $.ajax({
                                type: 'POST',
                                dataType: "json",
                                url: 'admin/upload.php',
                                data: {crop_image: base64data},
                                success: function (data)
                                {
                                    alert('success upload image');
                                }
                            });
                        };
                    });
                });
            });
        </script>
    </body>
</html>

upload.php: herewith I’m trying to collect cropped images for uploading and later I plan to store them in mySQL db

<?php
$folderPath = '../images/';
foreach($_POST["image_data_url"]['name'] as $key => $value){
$image_parts = explode(";base64,", $_POST['image_data_url']);
$image_type_aux = explode("image/", $image_parts[0]);  
$image_type = $image_type_aux[1];  
$image_base64 = base64_decode($image_parts[1]);  
$file = $folderPath . `uniqid()` . '.png';  
file_put_contents($file, $image_base64);  
echo json_encode(["image uploaded successfully."]);  
}
?>

How to autofill with same number as previous box?

i had this code

<div class="col-sm-4">
<?=
$this->Form->control('value[' . $key . '][2]', [
'label' => false,
'class' => 'form-control desktop-country',
'type' => 'text',
'placeholder' => __('Desktop'),
'value' => isset($option->value[$key][2]) ? $option->value[$key][2] : '',
]);
                            

?>
</div>
<div class="col-sm-4">
<?=
$this->Form->control('value[' . $key . '][3]', [
'label' => false,
'class' => 'form-control mobile-country',
'type' => 'text',
'placeholder' => __('Mobile / Tablet'),
'value' => isset($option->value[$key][3]) ? $option->value[$key][3] : '',
]);

?>
</div>

it will turn like this
Example of the code

the question is… how can i make the box automatically fill with any number entered from another box? example
on india on desktop side… i fill it with 3 and the mobile/tablet will be automatically filled with 3 also… can i do that?
i hope somone can help me… i already stuck with this since morning lol….
any suggestion?

Is the “continue X” syntax unique for PHP, or was it also in C and/or other languages? [closed]

Today, I finally learned that it’s possible to do “continue 2;” to “continue” an inner loop. I never knew about this syntax in 20+ years of using PHP. I could have used this in so many cases…

Now I wonder:

  1. Was this a thing right away, or added “late in the game” for PHP?
  2. Did this also exist in C/other languages, or was it an enhancement in PHP?

I tried to find this out on my own prior to asking.

Form İnput By Editing Link (PHP)

I sometimes see that when I click a link it fill some inputs automaticly and I see “?input_name=”x”text:xx” etc. How can I do this on my php website. Thank you foro your answers.

Write json object into CSV file using php

I’m trying to write the json object into a CSV file, but it’s not working the file is empty.

any advice?

below my PHP code

//json to csv
$jsondata = '{"regNo":"92-212-98","tradName":"FEVADOL EXTRA TAB.","genericName":"PARACETAMOL, CAFFEINE","price":"5.300","strngth":"500, 65 mg","exD":"21/07","PRODREGSTATUS":"PRODNOTFOUND","authstatus":"1","marketingstatus":"1","productstatus":null}';
$json = json_decode($jsondata);

$fp = fopen('file.csv', 'w');

// if($fp == false){
// echo 'false open';
// }else{
//  echo 'true open';
// }

foreach ($json as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

How to build a AJAX-Function for HTML Select-Tag (dropdown-Menu)

I have a price/product-Comparison-Site.
My Site shows me all my Products, above I have a Select-Dropdown-Menu, where I can order the products by price, name, etc.
The Problem here is, if I switch the Orderby-Option, the site refresh. I want to change the options without a refresh of the site, so it can solve with AJAX.
The Problem here is I am very new in AJAX, JS, jQuery, WordPress, PHP so and I don’t know how to build, and add the codes in my wordpress site 🙂
I hope someone can help me here out – thank you guys in advanced.
Here my codes:

  1. So this is how I get the Select-Orderby-Filter to my site:
    // filter layout
                    if(isset($_GET['layout'])) {
                        $layout = $_GET['layout'];
                    }

                    if (have_posts()) :
                        if('1' == $userfilter)
                            get_template_part('parts/product/code', 'filter');
  1. So thats the Filter-Function-Code.php
    <?php
/*
 * VARS
 */
global $layout, $args, $orderby, $order, $default_orderby;

$orderby = $default_orderby;

if ( isset( $_GET['orderby'] ) ) {
    $orderby = $_GET['orderby'];
} else {
    switch ( $orderby ) {
        case 'price' :
            if ( $order == 'asc' ) {
                $orderby = 'price-asc';
            } else {
                $orderby = 'price-desc';
            }
            break;

        case 'name' :
            if ( $order == 'asc' ) {
                $orderby = 'a-z';
            } else {
                $orderby = 'z-a';
            }
            break;
    }
}

if ( isset( $_GET['order'] ) ) {
    $order = $_GET['order'];
}
?>
<div class="result-filter">
    <div class="row">
        <div class="col-sm-6 hidden-xs">
            <ul class="list-inline">
                <li><span class="result-title"><?php _e( 'Ansicht:', 'affiliatetheme' ); ?></li>
                <li>
                    <a class="btn btn-link <?php echo( $layout == 'grid' ? 'active' : '' ); ?>" title="<?php _e( 'Gridansicht', 'affiliatetheme' ); ?>" data-value="grid" href="<?php echo requestUriAddGetParams( array( 'layout' => 'grid' ) ); ?>">
                        <i class="fas fa-th"></i>
                    </a>
                </li>
                <li>
                    <a class="btn btn-link <?php echo( $layout == 'list' ? 'active' : '' ); ?>" title="<?php _e( 'Listenansicht', 'affiliatetheme' ); ?>" data-value="list" href="<?php echo requestUriAddGetParams( array( 'layout' => 'list' ) ); ?>">
                        <i class="fas fa-bars"></i>
                    </a>
                </li>
            </ul>

        </div>
        <div class="col-xs-12 col-sm-6 orderby">
            <select name="orderby" id="orderby" onchange="" class="form-control">
                <option value="date" <?php selected( 'date', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Neuheiten', 'affiliatetheme' ); ?></option>
                <option value="rating" <?php selected( 'rating', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Beliebtheit', 'affiliatetheme' ); ?></option>
                <option value="price-asc" <?php selected( 'price-asc', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Preis (aufsteigend)', 'affiliatetheme' ); ?></option>
                <option value="price-desc" <?php selected( 'price-desc', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Preis (absteigend)', 'affiliatetheme' ); ?></option>
                <option value="a-z" <?php selected( 'a-z', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Name (aufsteigend)', 'affiliatetheme' ); ?></option>
                <option value="z-a" <?php selected( 'z-a', ( $orderby ? $orderby : '' ), true ); ?>><?php _e( 'Name (absteigend)', 'affiliatetheme' ); ?></option>
            </select>
        </div>
    </div>
</div>

<hr>
  1. Also here the HTML Code of the Dropdown-Menu:
    <div class="col-xs-12 col-sm-6 orderby">
            <select name="orderby" id="orderby" onchange="" class="form-control">
                <option value="date" selected="selected">Neuheiten</option>
                <option value="rating">Beliebtheit</option>
                <option value="price-asc">Preis (aufsteigend)</option>
                <option value="price-desc">Preis (absteigend)</option>
                <option value="a-z">Name (aufsteigend)</option>
                <option value="z-a">Name (absteigend)</option>
            </select>
        </div>

If something is missing please tell me, I will post it here.

continuos ajax request gives error net::ERR_EMPTY_RESPONSE

steps to reproduce the error

  1. open http://www.blackboardjournals.com/test2.php
  2. click on the next button continuously for 30-40 times
  3. the counter stops after a certain count
  4. the console shows an error net::ERR_EMPTY_RESPONSE
  5. if you refresh immediately after the counter stops, the site becomes unresponsive

I am not able to understand why this error is occurring. can somebody help me understand what is wrong?

My code:

<?php

if(isset($_POST['btn_num'])){
    $btn_name=$_POST['btn_num'];
    echo $btn_name+1;
    exit();
};
?>
<script type="text/javascript">
function ajaxObj( meth, url ) {
    var x = new XMLHttpRequest();
    x.open( meth, url, true );
    x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    return x;
}
function ajaxReturn(x){
    if(x.readyState == 4 && x.status == 200){
        return true;    
    }
}

function call_next(){
    var new_ans=$('.number').html();
    var ajax =ajaxObj("POST",'test2.php');
    ajax.onreadystatechange=function(){
        if(ajaxReturn(ajax)==true){
            $('.number').html(ajax.responseText);           
        }
    }
    ajax.send('btn_num='+new_ans);
}

</script>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="/pwa/js/jquery.js" ></script>
</head>
<body>
<div class="number">1</div>
<button onclick="call_next();">next</button>
</body>
</html>

How can i import data into array ? PHP

$array_numbers = [
['number' => 1000, 'percent' => 13, 'id' => 6768, 'term' => 12],
['number' => 1500, 'percent' => 13, 'id' => 6769, 'term' => 24],
['number' => 2500, 'percent' => 16, 'id' => 6770, 'term' =>  8],
['number' => 500, 'percent' => 15,  'id' => 6771, 'term' =>  2],
['number' => 500, 'percent' => 15,  'id' => 6772, 'term' =>  4],    ];

I want to create array like this but, values should be select from the mysql table.

‘number’ is by column name ‘1500’ , ‘2500’ is the value.
How can i do ?

my query is

    $exe_id = 1;
    $query=$db->prepare("SELECT * FROM number_list ORDER BY list_id DESC");
    $query->execute();
    while ($execute=$query->fetch(PDO::FETCH_ASSOC)){ $exe_id++;    
        $arr_numbers[$execute['number']]=$execute['percent'];   
      }

with this code, i can create array includes only number and percent. I want ‘id’ and ‘term’ too.

Thanks.

add custom text + url for specific product [duplicate]

  • This is an extension question of this question :

Change add to cart button text + url to My account Order view page when customer has previously bought the product .

  • need to solve:

how can I add a custom url for a specific product in this below answered code Change add to cart button text + url to My account Order view page when customer has previously bought the product:
(product is digital or physical type it’s common I think).

  • here is part of the example code I tried to write for a specific product:

// for the product ID 45 (for example) if( $product->id == 45 ){ $add_to_cart_url = site_url(‘/custom-link/product-45/’); $button_text = __(‘View order now’, ‘woocommerce’); }

I didn’t figured out how to write add . Any advice?

function get_order_id_by_product_id( $product_id ) {
    global $wpdb;
    
    // Get user ID
    $user_id = get_current_user_id();

    // Get order ID by product ID
    $order_id = $wpdb->get_var( "
        SELECT p.ID FROM {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
        WHERE p.post_status IN ( 'wc-completed' )
        AND pm.meta_key = '_customer_user'
        AND pm.meta_value = '$user_id'
        AND woim.meta_key IN ( '_product_id', '_variation_id' )
        AND woim.meta_value = '$product_id'
        LIMIT 1
    " );

    // Return
    return $order_id;
}

// On WooCommerce shop and archives pages
function filter_woocommerce_loop_add_to_cart_link( $sprintf, $product, $args ) {
    // Only for logged in users
    if ( ! is_user_logged_in() ) return $sprintf;
    
    // Only for single type products
    if ( ! $product->is_type( 'simple' ) ) return $sprintf;
    
    // Call fuction and get order ID
    $order_id = get_order_id_by_product_id( $product->get_id() );
    
    // When NOT empty
    if ( ! empty( $order_id ) ) {
        // Setting
        $button_text_view_order = __( 'View order now', 'woocommerce' );
        
        // Get view order url
        $view_order_url = wc_get_endpoint_url( 'view-order', $order_id, wc_get_page_permalink( 'myaccount' ) );
        
        // New link + text
        $sprintf = sprintf(
            '<a href="%s" class="%s">%s</a>',
            esc_url( $view_order_url ),
            esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
            esc_html( $button_text_view_order )
        );
    }
    
    return $sprintf;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_woocommerce_loop_add_to_cart_link', 10, 3 );

// On single product page, replacing the single add to cart product button by a custom button
function action_woocommerce_single_product_summary() {
    global $product;

    // Only for logged in users
    if ( ! is_user_logged_in() ) return;
    
    // Only for single type products
    if ( ! $product->is_type( 'simple' ) ) return;
    
    // Call fuction and get order ID
    $order_id = get_order_id_by_product_id( $product->get_id() );
    
    // When NOT empty
    if ( ! empty( $order_id ) ) {
        // Remove default add to cart button and add a custom one
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        
        // Add action, priority 30 and pass data to add action function
        add_action( 'woocommerce_single_product_summary', function() use ( $order_id ) {
            // Setting
            $button_text_view_order = __( 'View order now', 'woocommerce' );
            
            // Get view order url
            $view_order_url = wc_get_endpoint_url( 'view-order', $order_id, wc_get_page_permalink( 'myaccount' ) );
            
            echo '<a href="' . $view_order_url . '" class="button">' . $button_text_view_order . '</a>';
        }, 30, 0 );
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 1 );

Casting Typed Properties in Aggregate using Doctrine

We’re creating a setup that uses DDD, and we persist our Aggregates with Doctrine. The entity consists out of multiple class properties which are (almost all) non-primitive types (i.e. CustomerFirstName, CustomerLastName).

For those properties, we’re using an embeddable to define the actual column in the persistence.

An example is;

/**
 * @ORMColumn(type="orderCustomerLastNameType")
 * @ORMEmbedded(class="ACMEDomainValueObjectsOrderCustomerLastName", columnPrefix=false)
 */
private OrderCustomerLastName $lastName; 

Now to reconstruct the Aggregate from the Database we use a custom column type.

The problem is that we would need a type for every ValueObject we’re using, which is inconvenient (to say at least).

We’re looking to create a generic type converter for all ValueObjects but for that we would need to know the class instance of the to be converted object.

The current Hydrator is only passing the value and the platform to the type converter.

Any suggestions, tips or workarounds on how to solve this is greatly appreciated!

Not loading ‘libphp5’ module with CA on apache2.4.51

On Macbook M1Max.
Installed PHP5.6 by ‘shivammathur/php/[email protected]’ via Homebrew.
And set the module info on a configuration file(httpd.conf) of Apache.

LoadModule php5_module /opt/homebrew/opt/[email protected]/lib/httpd/modules/libphp5.so "apache2"

then passed apachectl syntax check that has no error.

$ apachectl configtest
[Fri Jan 14 19:48:05.352957 2022] [so:notice] [pid 5436] AH06662: Allowing module loading process to continue for module at /opt/homebrew/opt/[email protected]/lib/httpd/modules/libphp5.so because module signature matches authority "apache2" specified in LoadModule directive
Syntax OK

BUT, apache still occurred below errors.

[Fri Jan 14 19:50:25.774217 2022] [so:error] [pid 5534] /usr/bin/codesign failed; unable to obtain code signature for module
[Fri Jan 14 19:50:25.774243 2022] [so:error] [pid 5534] AH06663: Unable to find code signature authority on module at /opt/homebrew/opt/[email protected]/lib/httpd/modules/libphp5.so that matches authority name "apache2" configured on LoadModule directive.
httpd: Syntax error on line 190 of /private/etc/apache2/httpd.conf: Code signing error - not loading module at: /opt/homebrew/opt/[email protected]/lib/httpd/modules/libphp5.so

How can fix them?

General problem with code running more than once

I like to run my code just once. But somehow it runs twice, which causes some further problems.


The Problem

The method setCurrentItem on Page runs twice.

The value true is dumped two times by var_dump(true).

I would like to implement a conditional redirect which does not work because the code is run more than once.

I would also like to get some general coding advice on my code, because I am relatively new to PHP.

Thanks, everyone!


Now: The Code

index.php:

<?php

require_once '../src/App.php';
require_once '../src/Page.php';
require_once '../src/Item.php';

$app = new App();

App.php:

<?php

class App
{
    public $pages = [];
    public $currentPage = null;

    public function __construct()
    {
        $this->loadPages();
        $this->setCurrentPage();
    }

    private function loadPages()
    {
        $paths = glob('../content/**/page.json');

        foreach ($paths as $path) {
            $data = json_decode(file_get_contents($path));
            $this->pages[$data->slug] = new Page($data);
        }
    }

    private function setCurrentPage()
    {
        $pathSegments = isset($_GET['path']) ? explode('/', trim($_GET['path'], '/')) : [];
        $slug = isset($pathSegments[0]) ? $pathSegments[0] : 'home';

        if (array_key_exists($slug, $this->pages)) {
            $this->currentPage = $this->pages[$slug];
        } else {
            $siteConfig = json_decode(file_get_contents('../config/site.json'));
            header('Location: '.$siteConfig->basePath);
        }
    }
}

Page.php:

<?php

class Page
{
    public $slug;
    public $title;
    public $dynamic;

    public $items = [];
    public $currentItem = null;

    public function __construct($data)
    {
        $this->distributeData($data);

        if ($this->dynamic) {
            $this->loadItems();
            $this->setCurrentItem();
        }
    }

    private function distributeData($data)
    {
        $this->slug = $data->slug;
        $this->title = $data->title;
        $this->dynamic = $data->dynamic;
    }

    private function loadItems()
    {
        $paths = glob('../content/*.'.$this->slug.'/**/item.json');
        
        foreach ($paths as $path) {
            $data = json_decode(file_get_contents($path));
            $this->items[$data->slug] = new Item($data);
        }
    }

    private function setCurrentItem()
    {
        $pathSegments = isset($_GET['path']) ? explode('/', trim($_GET['path'], '/')) : [];
        $slug = isset($pathSegments[1]) ? $pathSegments[1] : null;

        if (array_key_exists($slug, $this->items)) {
            $this->currentItem = $this->items[$slug];
        }

        var_dump(true);
    }
}

Display Month name and year if date is like 11-2021 [closed]

I am using datapicker on my page and I have to show only month name and year in the date. It’s inserted like like 11-2021, 12-2021 or 1-2022.

Now What I am doing is, I have to get the Month name and year

Expected output is November 2021 December 2021 or January 2022

I have tried below code

    $startDate=strtotime('11-2021');
    $month=date("F",$startDate);
    $year=date("Y",$startDate);

I want to display all the data coming from the ‘senders_name” column in my ‘staff’ table, so i can display it in my select input box dropdown

I want to display all the data coming from the ‘senders_name” column in my ‘staff’ table, so i can display it in my select input box dropdown.

In the code below I have establish a one to many relationship between staff and Post, and I am trying to loop between all senders_name data
in my select drop down option, I have attached the staff model in my PostConroller and i have pass the variable to
//this is my post table

//this is my post model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    
    protected $table = 'posts';
    

    public function staff(){
    
        return $this->belongsTo('AppModelsStaff', 'staff_id');
    }

}

//this is my staff model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Staff extends Model
{
   
    protected $table = 'staff';
    

    public function posts(){
    
        return $this->hasMany('AppModelsPost');
    }

}

//this is my PostController

 <?php
    
    namespace AppHttpControllers;
    
    use IlluminateHttpRequest;
    use AppModelsStaff;
    use AppModelsPost;

    
/**
 * Show the form for creating a new resource.
 *
 * @return IlluminateHttpResponse
 */ 
   public function create()
{   $staffs= Staff::all();
    return view("posts.create")->with('posts', $staffs);
}
    

    

//this is my create page  that shows the error(undefine variable staff)
@extends('layouts.admin')
@section('content')

<div class="block bg-warning ">
  <h1 class="lead p-3 container">Expense Requests Form</h1></div>
  @include('inc.messages')
<div class="container">

  <link rel="stylesheet" href="{{ asset('css/style.css') }}">
    
    <form action='{{url('posts')}}' method='POST'>
        @csrf
    
    
    <div> <label for="exampleSelectRounded0" style="margin-top:10px;">DRIVERS DETAILS</label><h6>Drivers Name</h6>
      @foreach ($staffs as $staff )
    <select class="custom-select rounded-0" id="exampleSelectRounded0" name="staff_id">
      
      <option  value="{{ $staff->id }}" {{ old('') == "" ? 'selected' : '' }}>{{ $staff->senders_name }}</option>
      @endforeach
</div>
</div>
<div>
<@endsection>