hide wordpress products rating if empty

I want to hide the stars rating below the title on the products where the reviews are empty. I want to hide only the stars without the ability to leave a new review.
I found a similar solution for hiding a different element and tried to adopt it.

I added this using a snippets plugin to add a class “hide-empty-stars” in body_class when the reviews are empty.

function check_for_empty_stars( $classes ) {
    global $product;
    $id = $product->get_id();

    $args = array ('post_type' => 'product', 'post_id' => $id);    
    $comments = get_comments( $args );

    if(empty($comments)) {
        $classes[] = 'hide-empty-stars';
    }

    return $classes;
}
add_filter( 'body_class', 'check_for_empty_stars' );

Then I hide the star-rating class using css

body.hide-empty-stars .star-rating{
    display: none;
}

It works but after a while I get a critical error and the log says that

mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Call to a member function get_id() on null in /var/www/vhosts/my-domain.gr/httpdocs/wp-content/plugins/code-snippets/php/snippet-ops.php(505) : eval()'d code:3

What could cause this? Is there anything wrong in my code?

woocommerce hook on custom order status changed

hey I was trying to make a plugin that sends WhatsApp messages on order status change so this is my code

add_action("woocommerce_order_status_changed", "order_status_wapp",10,3); 
function order_status_wapp($order_id, $old_status, $new_status){  
 if( $new_status == "processing" && carbon_get_theme_option( 'show_processing' )) {       require("incl/apicall.php");  
$message = carbon_get_theme_option( 'processing_message' );       
require("incl/message_attr.php");            
}

the code is working well when changing the status from the order table area ( actions ), but changing the status from the order details or programmatically shows no effect. is there any hook that triggers status change no matter what the way of changing is?

How to get “id” by onclick on server-sided datatable

I done a server-sided datatable with an edit button. How can i get the specific id when i clicked on the button ? Currently I wanted to do like this window.location.href = "updateProject.php?id=<?php echo $row["projectID"];?>"; But there is no ways for me to access the projectID.

My project table
table

My datatable
datatable

<!-- PAGE -->
    <div class="page">
        <div class="page-main">

            <?php include '../includes/importGlobal/header.php'; ?>
            <?php include '../includes/importGlobal/sidebar.php'; ?>

            <!--app-content open-->
            <div class="main-content app-content mt-0">
                <div class="side-app">

                    <!-- CONTAINER -->
                    <div class="main-container container-fluid">

                        <!-- PAGE-HEADER -->
                        <div class="page-header">
                            <div class="page-title"></div>
                            <div>
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="javascript:void(0)">Manage</a></li>
                                    <li class="breadcrumb-item active" aria-current="page">Project management</li>
                                </ol>
                            </div>
                        </div>
                        <!-- PAGE-HEADER END -->

                        <!-- Row -->
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">Projects</h3>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <div id="basic-datatable_wrapper" class="dataTables_wrapper dt-bootstrap5 no-footer">

                                                <div class="row">
                                                    <div class="col-sm-12">
                                                        <table class="table table-bordered text-nowrap border-bottom dataTable no-footer" id="basic-datatable1" role="grid" aria-describedby="basic-datatable_info">
                                                            <thead>
                                                                <tr role="row">
                                                                    <th class="wd-15p border-bottom-0 sorting sorting_asc" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="First name: activate to sort column descending" style="width: 193.5px;">Project Name</th>
                                                                    <th class="wd-15p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Last name: activate to sort column ascending" style="width: 181.55px;">Description</th>
                                                                    <th class="wd-20p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Position: activate to sort column ascending" style="width: 335.475px;">Location</th>
                                                                    <th class="wd-15p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Start date: activate to sort column ascending" style="width: 188.387px;">Status</th>
                                                                    <th class="wd-10p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Salary: activate to sort column ascending" style="width: 145.925px;">Start Date</th>
                                                                    <th class="wd-10p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Salary: activate to sort column ascending" style="width: 145.925px;">End Date</th>
                                                                    <th class="wd-10p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Salary: activate to sort column ascending" style="width: 145.925px;">Created By</th>
                                                                    <th class="wd-10p border-bottom-0 sorting" tabindex="0" aria-controls="basic-datatable1" rowspan="1" colspan="1" aria-label="Salary: activate to sort column ascending" style="width: 145.925px;">Action</th>

                                                                </tr>
                                                            </thead>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- End Row -->


                    </div>
                    <!-- CONTAINER CLOSED -->

                </div>
            </div>
            <!--app-content closed-->
        </div>

    </div>

SCRIPT


    <script>
        $(document).ready(function() {
            $('#basic-datatable1').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": "../includes/actions/listProject-logic.php",
                "ordering": true,
                "columnDefs": [{
                    "render": createManageBtn,
                    "data": null,
                    "targets": [7]
                }]

            });
        });
    </script>
    <script type="text/javascript">
        function createManageBtn() {
            return '<div class = "btn-list"><button type = "button"class = "btn btn-primary btn-sm mb-1" onclick="editRedirect()" > Edit </button> <button type = "button"class = "btn btn-primary btn-sm mb-1" onclick="deleteRedirect()"> Delete </button> </div >';

        }

        function editRedirect() {
            window.location.href = "redirect to updatePhp with specific id";
        }
      </script>

listProject-logic.php

<?php
// Database connection info 
$dbDetails = array(
    'host' => 'xxx',
    'user' => 'xxx',
    'pass' => 'xxx',
    'db'   => 'xxx'
);

// DB table to use 
$table = 'projects';

// Table's primary key 
$primaryKey = 'projectID';


// Array of database columns which should be read and sent back to DataTables. 
// The `db` parameter represents the column name in the database.  
// The `dt` parameter represents the DataTables column identifier. 
$columns = array(
    array('db' => 'projectName', 'dt' => 0),
    array('db' => 'projectDescription',  'dt' => 1),
    array('db' => 'destinationName',      'dt' => 2),
    array('db' => 'projectStatus',     'dt' => 3),
    array('db' => 'startDate',    'dt' => 4),
    array('db' => 'endDate',    'dt' => 5),
    array('db' => 'uid',    'dt' => 6)

);

// Include SQL query processing class
require 'ssp.class.php';

// Output data as json format
echo json_encode(
    SSP::simple($_GET, $dbDetails, $table, $primaryKey, $columns)
);

Laravel best way to validate route param id existence and ownership

i’m working on a Laravel 9 API project whereby I have the following models:

  • Buyer
  • BuyerTier
  • BuyerTierOption

And each relate to one another, e.g: Buyers have BuyerTiers, and BuyerTiers have BuyerTierOtpions.

I’ve encountered a slight problem with the default Laravel validation whereby my URL already contains the buyer ID that I want to create a new tier for, but I need to make sure this ID not only exists, but belongs to my company.

How I’d get around this is to create a field in my request called buyer_id and create a custom rule like ValidModelOwnership which validates the ID and company, but I feel like Laravel should be able to do this as it’s in the URL, what am I missing:

/**
 * Store a newly created resource in storage.
 *
 * @param  IlluminateHttpRequest  $request
 * @return IlluminateHttpResponse
 */
public function store($company_id, $buyer_id, Request $request)
{
    $this->authorize('create', BuyerTier::class);

    $validator = Validator::make($request->all(), [
        'name' => [
            'required',
            'string',
            Rule::unique(BuyerTier::class)
                ->where('buyer_id', $buyer_id)
                ->where('company_id', $company_id)
        ],
        'buyer_id' => [
            'required',
            'numeric|min:50',
            new ValidModelOwnership(Buyer::class, [
                ['company_id', $company_id],
                ['id', $request->input('buyer_id')]
            ])
        ],
        'country_id' => [
            'required',
            'numeric',
            new ValidModelOwnership(Country::class, [
                ['company_id', $company_id],
                ['id', $request->input('country_id')]
            ])
        ],
        'product_id' => [
            'required',
            'numeric',
            new ValidModelOwnership(Product::class, [
                ['company_id', $company_id],
                ['id', $request->input('product_id')]
            ])
        ],
        'processing_class' => 'required|string|alpha_num',
        'is_default' => [
            'required',
            'boolean',
            new ValidDefaultModel(BuyerTier::class, $buyer_id)
        ],
        'is_enabled' => 'required|boolean'
    ]);

    if ($validator->fails()) {
        return response()->json([
            'message' => 'One or more fields has been missed or is invalid.',
            'errors' => $validator->messages(),
        ], 400);
    }

    try {
        $tier = new BuyerTier;
        $tier->user_id = Auth::id();
        $tier->company_id = $company_id;
        $tier->buyer_id = $buyer_id;
        $tier->country_id = $request->input('country_id');
        $tier->product_id = $request->input('product_id');
        $tier->name = trim($request->input('name'));
        $tier->description = $request->input('description') ?? null;
        $tier->processing_class = $request->input('processing_class');
        $tier->is_default = $request->boolean('is_default');
        $tier->is_enabled = $request->boolean('is_enabled');
        $tier->save();

        return response()->json([
            'message' => 'Buyer tier has been created successfully',
            'tier' => $tier
        ], 201);
    } catch (Exception $e) {
        return response()->json([
            'message' => $e->getMessage()
        ], 400);
    }
}

And I’m making a post request to:

  • {{endpoint}}/api/company/1/buyers/1/tiers/

How would I get my add event modal to show?

I am writing a interactive PHP calendar that uses JavaScript and CSS to add events.

I have got the event modal to work when clicking on a calendar icon, however I followed the same process for this new ‘add event’ modal and it doesn’t seem to be opening. I have tried debugging it but can’t get to the bottom of it and assume that I am overlooking something because of my inexperience in this area. What could I do to get this function to work and for the html to appear?

My working JS event selector modal:

// Function that will open the event list modal
    openEventModal(x, y, startDate, endDate) {
        // If there is already a modal open, return false
        if (this.isModalOpen) {
            return false;
        }
        // Update the isModalOpen var
        this.isModalOpen = true;
        // Update the calendar CSS opacity property
        document.querySelector('.calendar').style.opacity = '.3';
        // Declare the events list
        let eventsList = '<div class="events">';
        let hasEvents = false;
        // Iterate the events array
        this.container.querySelectorAll('.days .event').forEach(element => {
            // Determine the specified date
            let eventDate = new Date(startDate);
            let eventDate2 = new Date(startDate);
            let eventDateStart = new Date(element.dataset.datestart);
            eventDate.setDate(eventDate.getDate()-parseInt(element.dataset.day));
            if (eventDate.toISOString().split('T')[0] == eventDateStart.toISOString().split('T')[0]) {
                // Event template
                eventsList += '<div class="event">';
                eventsList += '<h5><i class="date">' + (eventDate2.toISOString().split('T')[0] == eventDateStart.toISOString().split('T')[0] ? this.formatAMPM(eventDateStart) : 'Ongoing') + '</i> &mdash; ' + element.innerHTML + '</h5>';
                eventsList += '<p class="description">' + element.dataset.description + '</p>';
                eventsList += '</div>';
                hasEvents = true;
            }
        });
        if (!hasEvents) {
            eventsList += '<p>There are no events.</p>'
        }
        eventsList += '</div>';
        // Declare the modal title, which will consist of the date
        let dateTitle = new Date(startDate);
        dateTitle = dateTitle.getDate() + ' ' + dateTitle.toLocaleString('default', { month: 'long' }) + ' ' + dateTitle.getFullYear();
        // Add the date select template modal to the HTML document
        document.body.insertAdjacentHTML('beforeend', `
            <div class="calendar-event-modal">
                <h5>${dateTitle}</h5>
                ${eventsList}
                <a href='#' class="add_event">Add Event</a>
                <a href="#" class="close">Close</a>
            </div>
        `);
        // Select the above modal
        let modalElement = document.querySelector('.calendar-event-modal');
        // Retrieve the modal rect properties
        let rect = modalElement.getBoundingClientRect();
        // Position the modal (center center)
        modalElement.style.top = parseInt(y-(rect.height/2)) + 'px';
        modalElement.style.left = parseInt(x-(rect.width/2)) + 'px';  
        // Retrieve the calendar rect properties
        let calendar_rect = document.querySelector('.calendar').getBoundingClientRect();
        let calendar_x = (calendar_rect.width / 2) + calendar_rect.x;
        let calendar_y = (calendar_rect.height / 2) + calendar_rect.y;
        // Iterate all events   
        modalElement.querySelectorAll('.events .event').forEach(element => {

   // Add event button onclick event
          modalElement.querySelector('.add_event').onclick = event => {
            event.preventDefault();
            // Remove the current modal
            modalElement.remove();
            // Modal is no longer open
            this.isModalOpen = false;
            // Open the add event modal
            this.openAddEventModal(calendar_x, calendar_y, startDate, endDate);
        };  
        // Close button onclick event
        modalElement.querySelector('.close').onclick = event => {
            event.preventDefault();
            // Remove the modal
            modalElement.remove();
            // Update the calendar CSS opacity property
            document.querySelector('.calendar').style.opacity = '1';
            // Modal is no longer open
            this.isModalOpen = false;
        };
 
        });

The Add event Modal that won’t add:

openAddEventModal(x, y, startDate, endDate) {
        if (this.isModalOpen) {
            return false
        }

        this.isModalOpen =true;

        document.querySelector('.calendar').style.opacity='.3';

        let startDateStr, endDateStr, t;

        document.body.insertAdjacentHTML('beforeend', `
            <div class="calendar-add-event-modal">
                <form>
                    <label for="title">Title</label>
                    <input id="title" name="title" type="text" placeholder="Title" value="${edit ? edit.title : ''}">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" placeholder="Description">${edit ? edit.description : ''}</textarea>
                    <label for="startdate">Start Date</label>
                    <input id="startdate" name="startdate" type="datetime-local" value="${startDateStr}">
                    <label for="enddate">End Date</label>
                    <input id="enddate" name="enddate" type="datetime-local" value="${endDateStr}">
                    <label for="color">Color</label>
                    <input id="color" name="color" type="color" placeholder="Color" value="${edit ? edit.color : '#5373ae'}" list="presetColors">
                    <input type="hidden" name="eventid" value="">                  
                    <span id="msg"></span>                                    
                </form>
                <a href="#" class="add_event">${edit ? 'Update' : 'Add'} Event</a>
                <a href="#" class="close">Cancel</a>
            </div>
        `);

        let modalElement = document.querySelector('.calendar-add-event-modal');
        let rect = modalElement.getBoundingClientRect();

        modalElement.style.top = parseInt(y-(rect.height/2)) + 'px';
        modalElement.style.left = parseInt(y-(rect.height/2)) + 'px';

        modalElement.querySelector('.add_event'.disabled=true);

        fetch(this.ajaxUrl, {cache: 'no-store', method: 'POST', body: new FormData(modalElement.querySelector('form')) }).theb(response => response.text()).then(data => {
            if(data.includes('success')) {
                modalElement.remove();

                this.fetchCalendar();

                this.isModalOpen = false;

            } else {
                modalElement.querySelector('#msg').innerHTML = data;
                modalElement.querySelector('.add_event').disabled = false;
            }
        });

I thought my iteration of the add_event function should make the html appear, but it doesn’t open and displays nothing, but seems to try to open.

Saving generated sql file to PHP script folder

I have a PHP script that generates a MySQL database backup.

Executing the PHP on a web browser, prompts the user to download the generated sql file.

Here you have the piece of code that generates the sql file and prompts to download the generated sql file:

if(!empty($sqlScript))
{
    // Save the SQL script to a backup file
    $backup_file_name = $database_name . '_backup_' . time() . '.sql';
    $fileHandler = fopen($backup_file_name, 'w+');
    $number_of_lines = fwrite($fileHandler, $sqlScript);
    fclose($fileHandler); 

    // Download the SQL backup file to the browser
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backup_file_name));
    ob_clean();
    flush();
    readfile($backup_file_name);
    exec('rm ' . $backup_file_name); 
}

I don´t need to download the file,what I need is to execute the PHP file every x days and save the generated sql file on the same server folder.

I can use cron jobs to launch the PHP file, my only need is to change above code in order to save the generated sql file on the same script folder.

newb question, how do I have a checkbox write data to my sql database

I would like to know how to have a checkbox send a 1 value to mysql database, or if checkbox is not ticked to keep entry NULL or 0

 <div class="form-group">
        <div class="custom-control creator-checkbox">
            <div class="">
                <input class="creator-control-input @error('terms') is-invalid @enderror" id="creator" type="checkbox" name="creator" value="1" placeholder="{{ __('creator') }}">
                <label class="creator-control-label" for="tosAgree">
                    <span>{{ __('Sign up as a content creator') }}</a>.</span>
                </label>
            </div>
        </div>
    </div>

this creates the field on the registration page but I dont know how to get it to put the info into mysql

I want to remove default theme header and footer from WooCommerce cart and checkout page

I am making a custome theme and i want to add the custom header and footer to cart and checkout page. But, get_footer('cart') is not working and it is loading the default header and footer even when i am not calling for header and footer they are still there.

How can we display my custom “footer_cart.php” to the woocommerce cart page? Either with get_footer(); or with is_cart function

How to make two columns of a table requiring to be unique at user request

I have tried validating the user request like this:

$data = $request->validate([
            'fname' => 'nullable',
            'lname' => 'nullable',
            'gender' => 'required',
            'mobile' => 'required|unique:users,usr_name',
            'ncode' => 'nullable',
            'password' => 'required',
            'password_confirmation' => 'required',
        ]);

So as you can see I have said that the mobile filed value must be unique:users,usr_name but I do need to check that it is unique at members table as well (the mbr_mobile column):

unique:members,mbr_mobile

So how to combine these two rules at once?

.htaccess url rewriting not works

I have a website gofastparking i am trying to rewrite url but it does not work below is the htaccess code.

# .htaccess main domain to subfolder redirect
RewriteEngine on

#RewriteCond %{HTTP_HOST} ^(www.)?gofastparking.com$
RewriteCond %{REQUEST_URI} !^/gofastparking/    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /gofastparking/$1

RewriteRule ^(/)?$ gofastparking/index.php [L]

RewriteRule airport-parking-heathrow$ car-parking-heathrow.php [NC]
    
# CASE SENSITIVE METHOD
<Files .htaccess>
    Order allow,deny
    Deny from all
</Files>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

before rewriting:
https://www.gofastparking.com/car-parking-heathrow

here is the url that should work but it give 404.

after url rewriting:
https://www.gofastparking.com/airport-parking-heathrow

any help would be appreciated.

download php file instead of opening it

I am beginner and trying to add phpmailer to my html document, so I added it, change its name from index.html to index.php, then I downloaded php and apache. now I am trying to launch website in localhost but instead of launching browser downloads php file. I did very long research but can’t fix the problem. also, I think I don’t have .htaccess file if it’s necessary help me add it. here is my httpd.conf file:

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" 
# will be interpreted as '/logs/access_log'.
#
# NOTE: Where filenames are specified, you must use forward slashes
# instead of backslashes (e.g., "c:/apache" instead of "c:apache").
# If a drive letter is omitted, the drive on which httpd.exe is located
# will be used by default.  It is recommended that you always supply
# an explicit drive letter in absolute paths to avoid confusion.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
Define SRVROOT "c:/Apache24"

ServerRoot "${SRVROOT}"

#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:logs

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to 
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
#LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule auth_form_module modules/mod_auth_form.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
#LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so
#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule brotli_module modules/mod_brotli.so
#LoadModule buffer_module modules/mod_buffer.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cache_socache_module modules/mod_cache_socache.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule data_module modules/mod_data.so
#LoadModule dav_module modules/mod_dav.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
#LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
#LoadModule expires_module modules/mod_expires.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule filter_module modules/mod_filter.so
#LoadModule http2_module modules/mod_http2.so
#LoadModule headers_module modules/mod_headers.so
#LoadModule heartbeat_module modules/mod_heartbeat.so
#LoadModule heartmonitor_module modules/mod_heartmonitor.so
#LoadModule ident_module modules/mod_ident.so
#LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
#LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
#LoadModule ldap_module modules/mod_ldap.so
#LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule log_forensic_module modules/mod_log_forensic.so
#LoadModule lua_module modules/mod_lua.so
#LoadModule macro_module modules/mod_macro.so
#LoadModule md_module modules/mod_md.so
LoadModule mime_module modules/mod_mime.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
#LoadModule proxy_html_module modules/mod_proxy_html.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_http2_module modules/mod_proxy_http2.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so
#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
#LoadModule reflector_module modules/mod_reflector.so
#LoadModule remoteip_module modules/mod_remoteip.so
#LoadModule request_module modules/mod_request.so
#LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule rewrite_module modules/mod_rewrite.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule session_module modules/mod_session.so
#LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_crypto_module modules/mod_session_crypto.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule socache_redis_module modules/mod_socache_redis.so
#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule unique_id_module modules/mod_unique_id.so
#LoadModule userdir_module modules/mod_userdir.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule version_module modules/mod_version.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule xml2enc_module modules/mod_xml2enc.so

<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.  
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User daemon
Group daemon

</IfModule>

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. [email protected]
#
ServerAdmin [email protected]

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost
#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other 
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "${SRVROOT}/htdocs"
<Directory "${SRVROOT}/htdocs">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error.log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
    LogFormat "%h %l %u %t "%r" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    CustomLog "logs/access.log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog "logs/access.log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to 
    # exist in your server's namespace, but do not anymore. The client 
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts. 
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "${SRVROOT}/cgi-bin/"

</IfModule>

<IfModule cgid_module>
    #
    # ScriptSock: On threaded servers, designate the path to the UNIX
    # socket used to communicate with the CGI daemon of mod_cgid.
    #
    #Scriptsock cgisock
</IfModule>

#
# "${SRVROOT}/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "${SRVROOT}/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>
    #
    # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
    # backend servers which have lingering "httpoxy" defects.
    # 'Proxy' request header is undefined by the IETF, not listed by IANA
    #
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig conf/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    
    addType text/html .php
    AddType  application/x-httpd-php-source  .phps

    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
</IfModule>

#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type.  The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited

#
# EnableMMAP and EnableSendfile: On systems that support it, 
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted 
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on

# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be 
# included to add extra features or to modify the default configuration of 
# the server, or you may simply copy their contents here and change as 
# necessary.

# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf

# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf

# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf

# Language settings
#Include conf/extra/httpd-languages.conf

# User home directories
#Include conf/extra/httpd-userdir.conf

# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf

# Virtual hosts
#Include conf/extra/httpd-vhosts.conf

# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf

# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf

# Various default settings
#Include conf/extra/httpd-default.conf

# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>

# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
#       starting without SSL on platforms with no /dev/random equivalent
#       but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

LoadModule php_module "C:phpphp8apache2_4.dll"
addHandler applications/x-httpd-php .php
PHPIniDir "C:php"

‘gcloud’ auth print-access-token Command is not recognizable from Process::fromShellCommandline(‘gcloud auth print-access-token’)

I configured Google Cloud for OCR and authenticated user by ADC, and implemented complete logic in laravel 8 & php 7.4.19. To access the access_token I was running command ‘gcloud auth print-access-token’ and it was returning token, but suddenly it started given error ‘gcloud is not recognized as internal or external command’

I am running command using SymfonyComponentProcessProcess::fromShellCommandline(‘gcloud auth print-access-token’), It was sending a token which I used to send REST API request at https://vision.googleapis.com/v1/images:annotate to fetch image text. Everything was working fine on localhost but now, It is giving me error
The command “gcloud auth print-access-token” failed.nnExit Code: 1(General error)nnWorking directory: nnOutput:n================nnnError Output:n================n’gcloud’ is not recognized as an internal or external command,rnoperable program or batch file.”

Even environment variables are set, still this is coming, which was not coming before

$stmt->execute() with INSERT INTO is inserting the same repeat value when in a loop

I’m inserting data into a MySQL Table using a for loop in PHP. I’m generating a random ID for $botid and then inserting it based on the amount of $botsToAdd.

The loop itself works but the $botid is always inserted with the same value. So on the first iteration of the for loop if it generated an ID of 2147483647 then all subsequent inserts are inserting with 2147483647 instead of the new $botid.

My code:

if ($botsToAdd > 0) {

    //Disable autocommit
    mysqli_autocommit($con, FALSE);

    //For loop for $botsToAdd
    for ($i = 0; $i < $botsToAdd; $i++) {
        //Generate a unique bot ID (integer) that is 11 digits long
        $botid = rand(10000000000, 99999999999);

        //Insert the bot into the cube_checkin table
        $stmt = $con->prepare('INSERT INTO cube_checkin (cube_id, user_id, is_bot) VALUES (?, ?, 1)');
        $stmt->bind_param('ii', $cubeid, $botid);
        $stmt->execute();
        $stmt->close();
    }

    //Commit the transaction
    if (mysqli_commit($con)) {
        http_response_code(200);
        header('Content-Type: application/json');
        echo json_encode(array("success" => "Bots have been added to the cube!"));
        exit();
    } else {
        http_response_code(400);
        header('Content-Type: application/json');
        echo json_encode(array("error" => "There has beeen an error adding bots to the cube."));
        exit();
    }

}

I really cannot understand why it’s behaving like this as I am closing the statement within the loop.

PDO statement’s execute() method not working as expected

Doing some DB work with PHP’s PDO. The code is very simple. Just trying to create a table in the database with prepared statement. But code is not working.


    $dsn = "mysql:host=$hostname;port=$port;dbname=$database;charset=UTF8";
    $pdo = new PDO($dsn, $username, $password);
    $dn  = 'pns';
    $query_string    = 'CREATE DATABASE IF NOT EXISTS :db';
    $query_statement = $pdo->prepare($query_string);
        
    if ($query_statement !== FALSE)
    {
        print 'Hi'; **// Code reaches here**
        $statement_execute = $query_statement->execute([
            ':db' => $dn
        ]);
    }

I am getting the below error instead…

Exception : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''pns'' at line 1

Please help.

Thanks.

Data chosen from select input isn’t known after uploading on the server but works on normal local host

So, before uploading on the server through cPanel, this code works fine. But on the server, I cannot.

On Server
On localhost

Both the codes are the same. It just doesn’t work on the website server. Please help me.

Here is the code snippet:

PHP CODE (below)

<?php
if(isset($_POST['form1'])) {
    $valid = 1;

    if(empty($_POST['tcat_id'])) {
        $valid = 0;
        $error_message .= "You must have to select a Main Menu<br>";
    }

    if(empty($_POST['mcat_name'])) {
        $valid = 0;
        $error_message .= "Sub Menu can not be empty<br>";
    }

    if($valid == 1) {

        // Saving data into the main table tbl_mid_category
        $statement = $pdo->prepare("INSERT INTO tbl_mid_category (mcat_name,tcat_id) VALUES (?,?)");
        $statement->execute(array($_POST['mcat_name'],$_POST['tcat_id']));
    
        $success_message = 'Sub Menu is added successfully.';
    }
}
?>

HTML FORM BELOW:

<form class="form-horizontal" action="" method="post">

                <div class="box box-info">
                    <div class="box-body">
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">Main Menu Name <span>*</span></label>
                            <div class="col-sm-4">
                                <select name="tcat_id" class="form-control select2">
                                    <option value="">Select Main Menu</option>
                                    <?php
                                    $statement = $pdo->prepare("SELECT * FROM tbl_top_category ORDER BY tcat_name ASC");
                                    $statement->execute();
                                    $result = $statement->fetchAll(PDO::FETCH_ASSOC);   
                                    foreach ($result as $row) {
                                        ?>
                                        <option value="<?php echo $row['tcat_id']; ?>"><?php echo $row['tcat_name']; ?></option>
                                        <?php
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">Sub Menu Name <span>*</span></label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="mcat_name">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label"></label>
                            <div class="col-sm-6">
                                <button type="submit" class="btn btn-success pull-left" name="form1">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>

            </form>