My WordPress php code snippets not working

I trying to use this snippet to prevent anyone who doesn’t has a specific word in his username to describe the device he use to login into the website from using the website

this code is not doing anything at all , I’m using a plugin called “code snippets”

<?php
if( is_front_page() ) {
$userag = $_SERVER['HTTP_USER_AGENT'];
$current_user = wp_get_current_user();
$usern = $current_user->user_login;
$appleAgent = str_contains($userag, "Mac");
$appleIos = str_contains($usern, "ios");
$appleMac = str_contains($usern, "mac");
if( ($appleAgent == 1 && $appleMac == 1)     ||  ($appleAgent == 1 && $appleIos == 1)  ){
  echo "";
}elseif( ($appleAgent == FALSE && $appleIos == FALSE && $appleMac == FALSE) ){
  echo "";
}else{  echo "<script>location.href='https://www.google.com/';</script>"; }
}
?>

is there any way to make this work?

Translate strings in a WordPress plugin?

I am new to WordPress and plugins, I received an exercise to do.
I did the first part: I implemented the following in my custom plugin:

  • I register a custom post type ‘x’ that has title and editor.
  • I created a rest api endpoint to get all posts of type ‘x’.

Now in the excercise they ask me to handle the translation of the text fields in Italian and English (I think we are assuming the text is always written in Italian), but I don’t even know where to start.

Read functions saves data into the database rather than reading it and loging me

I am fairly new to PHP and I’m doing a simple login and sign up form for a social website I am making. Im coding on VS studio code and using different files such as .html , .css and .php. Im still figuring out on how to link php and html together but I successfully got my sign up to work and it registers my data into my database (im using XAMPP). the problem occured when i was trying to login in.

my sign up and login form are on the same html file as im using some js to make it visible and hidden when the user either clicks on login or register.

 <form method="post" action="/Php/login.php">
      <!-- Input box for email for login panel  -->
      <div class="input_box">
        <span class="icon"><i class="bx bxs-envelope"></i></span>
        <input name="email" type="email" required placeholder="email" />
      </div>
      <!-- input box for password for login panel -->
      <div class="input_box">
        <span class="icon"><i class="bx bxs-lock-open"></i></span>
        <input
          name="password"
          type="password"
          required
          placeholder="Password?"
        />
      </div>
<?php

session_start();
include("/xampp/htdocs/FinalYearProject/Php/signup.php");
include("/xampp/htdocs/FinalYearProject/Php/connect.php");

class Login
{

    private $Error = "";


    public function CheckLogin($data)
    {

        $email = addslashes($data['email']);
        $password = addslashes($data['password']);


        //SQL QUERY to get email 
        $query = "SELECT * FROM users WHERE email = '$email' limit 1";

        $DB = new ConnectDB();
        $result =  $DB->read($query);

        // password check and more security 
        if ($result) {
            $row = $result[0];
            if ($password == $row['password']) {
                //creating a session to maintain info for different pages/move info for the same website
                $_SESSION['gameimperiumUserID'] = $row['UserID'];
            } else {
                $this->Error .= "Invalid Password<br>";
            }
        } else {
            $this->Error .= "Invalid Email<br>";
        }

        return $this->Error;
    }
}



if ($_SERVER['REQUEST_METHOD'] == 'POST') { // information contained by the server about the server

    $login = new Login();
    $result = $login->CheckLogin($_POST);

    if ($result != "") {

        echo "<div style = 'text-align: center; font-size: 12px ; color:white; background-color: grey;'>";
        echo "the follow errors occured<br>";
        echo $result;
        echo "</div>";
    } else {
        header("Location: http://localhost/Html/Profile.html");
        die;
    }
}

I have different files for signup and connect to DB. The main problem is when i enter data into the login form and submit it , the data goes into the database and makes a new entry for a new user.
I tried changing names and variables, getting everything under a single file and changing include files but none work. I want the php file to successfully read data from the database and redirect me to my header location and do this without making a new entry in the database for a new user

How to use “createCookies(req)” function of VueUse in SSR mode with Laravel/Inertia backend?

I want to have a theme cookie where I save the current theme. I’m using VueUse’s useCookies to do it on SPA mode, but it fails on SSR mode. The documentation says I need to use createCookies function instead an pass in my node request object which is of type IncomingMessage. But the problem is I’m using Laravel/Inertia and don’t know what to pass in or how. Here’s the code I’m using:

// AppLayout.vue
import { useThemes } from '@/stores/useThemes'
const themes = useThemes()
// useThemes.ts
import { createCookies, useCookies } from '@vueuse/integrations/useCookies'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export type Theme = string

export const useThemes = defineStore('themes', () => {
    const cookies = useCookies(['theme'])

    const theme = ref(cookies.get('theme') || 'default')

    /**
     * @field General themes
     */
    const generalThemes: Theme[] = ['Default', 'Light', 'Dark']

    /**
     * @field Light themes
     */
    const lightThemes: Theme[] = [
        'Cupcake',
        'Corporate',
        'Fantasy',
        'Autumn',
        'Winter',
        'Limonade',
        'Garden',
        'Retro',
        'Cyberpunk',
        'Valentine',
        'Nord',
    ]

    /**
     * @field Dark themes
     */
    const darkThemes: Theme[] = ['Coffee', 'Aqua', 'Night', 'Sunset', 'Halloween', 'Business']

    /**
     * Set theme by string name
     * @param {string} lang Language to be set
     */
    function setTheme(themeName: string) {
        if (
            themeName != null &&
            themeName != undefined &&
            themeName.trim() != '' &&
            (generalThemes.includes(capitalize(themeName)) ||
                lightThemes.includes(capitalize(themeName)) ||
                darkThemes.includes(capitalize(themeName)))
        ) {
            theme.value = themeName
            cookies.set('theme', theme.value)
        }
    }

    /**
     * Capitalize a string's first letter
     * @param {string} value String to be capitalized
     */
    function capitalize(value: string): string {
        return value
            .split(' ')
            .map((word) => {
                return word[0].toUpperCase() + word.substring(1)
            })
            .join(' ')
    }

    /**
     * Initialize theme if not set
     */
    function initTheme() {
        console.log(theme.value)
        setTheme(theme.value)
    }

    return { theme, initTheme, setTheme, generalThemes, lightThemes, darkThemes }
})

The line const cookies = useCookies(['theme']) throws error in SSR mode and must be replaced by createCookies. Here’s the Laravel side:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use IlluminateSupportFacadesCookie;
use InertiaInertia;

class PageController extends Controller {
    public function home(Request $req): InertiaResponse {
        return Inertia::render('Home', [
            'canLogin' => Route::has('login'),
            'canRegister' => Route::has('register'),
            'themeCookie' => $req->cookie('theme') ?? 'default',
            'animatedCookie' => boolval($req->cookie('animated')) ?? true,
        ]);
    }
}

Note that VueUse’s useCookies uses universal-cookie package internally.

can’t seem to increase the memory limit [duplicate]

FYI, I’m a designer and don’t have mutch experience in this field. I bareley understand what i am doing atm.

I need to increase the memory limit of a wordpress site to use a plugin. It’s curently at 128M but it needs to be 256M.

I edited the php.ini and wp_config file without succes. I don’t have the rights to acces the server via FTP at the moment. i want to see where the instalation gets the memory limit from but i don’t know how.

I have tried some of the advice on here. I believe the awnser is already somewhere on here, i just lack the experience to apply it. does anyone have an advice for me?

An exception has been thrown during the rendering of a template (“Object of class Closure could not be converted to string”)

I’m trying to set by default the username of the user by default in a empty field is the field is empty but I get an error message when I try do so.

->add('username', TextType::class, [
'label' => 'username',
 data'=> function(User $user){
return is_null($user->getUsername()) ? $user->getUsername(): "";}

I’ve tried to do it differently like this way but doesn’t do anything.

$builder->add('username, TextType::class, [
    'attr' => [
        'class' => 'form-control form-opacity',
        'autofocus' => true
    ],
    'data' => (is_null($builder->getData()->getUsername()) ? $builder->getData()->getUsername() : "username"
]);

PHP Date Format Issue on blank date fields

strtotime return wrong value upon blank field – form submission

Date selection is working fine but empty field giving 01-01-1970

<form method="post">
<input type="date" name="DOB"/>
<input type="submit" value="Submit" name="BtnSubmit"/>
</form>

<?php
if(isset($_POST["BtnSubmit"]))
{$F_DOB = $_POST["DOB"];
$F_DOBNew = date("d-m-Y", strtotime($F_DOB));
echo $F_DOBNew;}
?>

Above is the code what I am doing and working fine upon clicking the button. Few date fields are not required so when a user click on the button and left the date fields empty, the empty date fields shows 01-01-1970 upon submission.

How can i solve Wampserver random error 500 on requests [duplicate]

i get random error 500 on a local server that has wamp. I don’t know what to do anymore to get rid of those random 500. I have the same app on a cloud server and it works perfect no error 500. For example in 2h with 30 devices i get like 30 error 500, with 60 devices i get 200 error 500 in same interval. What settings i should try? php and apache logs dont have any errors.

Xamp issue with Mac os Catalina

I have xamp latest version installed on Mac os Catalina, only the apache web server starts, the other 2 servers do not, when I try opening the xamp application dashboard that opens in the browser the address localhost is displayed in the URL tab but the dashboard doesn’t display anything, also when I create my PHP files that have PHP items, they they load in browser but don’t display anything, even when I use both html and PHP in the same file, it’s only the html content that displays, PHP content doesn’t display

I tried restarting, uninstalling and re-installing xamp, adding a load module php7 module line in https.config but still dint work, the php load module present in the default file are PHP 4 and 5 and they are not commented out

How to call Ajax server-side scripts with ajax in devextreme and PHP

i want use DevExtreme tools in my PHP project. But when i use the DevExtreme-PHP-Data example of Devexpress some of the functions don’t work.

What I got so far is:

I am using the DevExtreme sample (link) but when processing the data, sorting and filtering there is a lot of errors from the PHP example.

the service.php sample page :

service.php (link)
DataController.php (link)

Somehow the PHP script does work, but when processsing with the dxDataGrid I got a lot of errors.

Like this example (when tyring to sort on the column) :

enter image description here

I found a good example from frostushaer on github but this example also do not use the Server-Side ajax page.

Can’t find a great complete PHP ajax sample out there.

How do I use in this sample of DevExtreme extra WHERE statements in the DataController?

How do I setup another example for updating data?

<?php
require_once("../../DevExtreme/LoadHelper.php");
spl_autoload_register(array("DevExtremeLoadHelper", "LoadModule"));

use DevExtremeDbSet;
use DevExtremeDataSourceLoader;

class DataController {
    private $dbSet;
    public function __construct() {
        //TODO: use your database credentials
        $mySQL = new mysqli("serverName", "userName", "password", "databaseName");
        $this->dbSet = new DbSet($mySQL, "tableName");
    }
    public function FillDbIfEmpty() {
        if ($this->dbSet->GetCount() == 0) {
            $curDateString = "2013-1-1";
            for ($i = 1; $i <= 10000; $i++) {
                $curDT = new DateTime($curDateString);
                $curDT->add(new DateInterval("P".strval(rand(1, 1500))."D"));
                $item = array(
                    "Name" => "Name_".strval(rand(1, 100)),
                    "Category" => "Category_".strval(rand(1, 30)),
                    "CustomerName" => "Customer_".strval(rand(1, 50)),
                    "BDate" => $curDT->format("Y-m-d")
                );
                $this->dbSet->Insert($item);
            }
        }
    }
    public function Get($params) {
        $result = DataSourceLoader::Load($this->dbSet, $params);
        if (!isset($result)) {
            $result = $this->dbSet->GetLastError();
        }
        return $result;
    }
    public function Post($values) {
        $result = $this->dbSet->Insert($values);
        if (!isset($result)) {
            $result = $this->dbSet->GetLastError();
        }
        return $result;
    }
    public function Put($key, $values) {
        $result = NULL;
        if (isset($key) && isset($values) && is_array($values)) {
            if (!is_array($key)) {
                $keyVal = $key;
                $key = array();
                $key["ID"] = $keyVal;
            }
            $result = $this->dbSet->Update($key, $values);
            if (!isset($result)) {
                $result = $this->dbSet->GetLastError();
            }
        }
        else {
            throw new Exeption("Invalid params");
        }
        return $result;
    }
    public function Delete($key) {
        $result = NULL;
        if (isset($key)) {
            if (!is_array($key)) {
                $keyVal = $key;
                $key = array();
                $key["ID"] = $keyVal;
            }
            $result = $this->dbSet->Delete($key);
            if (!isset($result)) {
                $result = $this->dbSet->GetLastError();
            }
        }
        else {
            throw new Exeption("Invalid params");
        }
        return $result;
    }
}
?>

Reorder Countries from WooCommerce Checkout Country fields, keeping states sync

The Issue
I’m working on customizing the WooCommerce checkout page by reordering the countries in the billing_country and shipping_country dropdown fields. I’ve achieved this by using the woocommerce_checkout_fields filter to modify the fields’ options.

However, after making these customizations, I’m facing an issue where the billing_state field doesn’t update correctly when the billing_country field is changed. The state/province options remain the same, regardless of the selected country.

Current Code (Previous Stackoverflow Post)
Here’s the code I’m using to reorder the countries and apply the Select2 (selectWoo) functionality:

// Reorder and customize the country dropdowns
add_filter('woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns');
function reorder_checkout_country_dropdowns($fields)
{
    $countries_array = array_merge(
        array(
            'DE' => 'Germany',
            'AT' => 'Austria',
            'CH' => 'Switzerland',
            '-' => '------------',
        ),
        WC()->countries->get_allowed_countries()
    );

    $fields['billing']['billing_country']['type'] = $fields['shipping']['shipping_country']['type'] = 'select';
    $fields['billing']['billing_country']['options'] = $fields['shipping']['shipping_country']['options'] = $countries_array;

    return $fields;
}

// Enqueue JavaScript to apply Select2 functionality
add_action('woocommerce_checkout_init', 'enable_back_selectWoo_on_countries_dropdowns');
function enable_back_selectWoo_on_countries_dropdowns()
{
    wc_enqueue_js("$('#billing_country,#shipping_country').selectWoo();");
}

Attempted Solutions
This code reorders the countries in the dropdowns and applies the Select2 (selectWoo) functionality. However, it doesn’t address the issue with the billing_state field not updating correctly when the billing_country is changed.

I’ve tried various approaches, such as adding an event listener to the billing_country field and updating the billing_state field accordingly, but I haven’t been able to find a solution that works consistently.

The Question
How can I ensure that the billing_state field updates with the correct state/province options when the billing_country field is changed, even after customizing the country dropdown?

Image example to show the issue

Shows Wrong State Selection for Billing Country Austria

As you can see in the image above, when “Austria – Österreich” is selected as the billing country in the WooCommerce checkout, the state selection field is incorrectly showing the states/provinces for “Germany” instead of the expected states/provinces for Austria.

The issue is not happening, when I comment out the second line add_filter('woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns');

[MacOS][M1][Non-Docker][MAMP] Error: SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above [duplicate]

Configuration:

  1. MacOS Sonoma 14.2.1 (M1), NO DOCKER.

  2. PostgreSQL was installed from https://get.enterprisedb.com/postgresql/postgresql-16.2-1-osx.dmg , and

    psql --version psql (PostgreSQL) 14.11 (Homebrew)

  3. libpq was installed by:

    brew install libpq

  4. Also, libpg in MAMP PRO (PHP 8.3) (by phpinfo();)- version 9.4.24

On any login attemp via code (PGGSSENCMODE also added to php.ini):

putenv('PGGSSENCMODE=disable');

try {
    $pdo = new PDO("pgsql:host=$servername;dbname=$dbname;user=$username;password=$password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "Success connection";

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

there is error SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above.

Also tryed:
in /opt/homebrew/var/postgresql@14/postgresql.conf set password_encryption = md5
in /opt/homebrew/var/postgresql@14/pg_hba.conf set METHOD = trust , also md5

Method dont changed from configuration file, so changed in session:

sudo psql postgres postgres 
SET password-encryption = ‘md5’;
ALTER USER "postgres" with password 'password';

but then login from console:

sudo psql postgres postgres 
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  password authentication failed for user "postgres"

login from php (the error persisted):

SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

How to get (where to download) libpq.so 10.x for M1 (for replace in /Applications/MAMP/bin/php/php8.3.0/lib/php/extensions/no-debug-non-zts-20230831/)?

Its hardcode in module used non-md5 (scram-sha-256) method of authentification?

Nginx redirect to php after rewrite

I had this configuration working flawlessly:

# Route for Laravel Backend
location ~ ^/(app|api|sanctum|admin) {
    try_files $uri $uri/ /index.php?$query_string;
    gzip_static on;
}

# Nginx Pass requests to PHP-FPM for Laravel Backend
location ~ .php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    fastcgi_pass backend:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
}

then i wanted to cover every call to the backend under a unique prefix:

  location ^~ /backend/ {
    # Remove the '/backend' prefix and pass the remaining path to index.php
    rewrite ^/backend/(.*)$ /$1 break;

    try_files $uri $uri/ /index.php?$query_string;
}

# PHP-FPM Configuration
location ~ .php$ {
    try_files $uri /index.php =404;
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    fastcgi_pass backend:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param REQUEST_URI $request_uri;
}

The problem is that the php backend application is actually reached, but it seems that only the index.php file is delivered without it being able to get the backend routes

[2024-04-03 09:05:58] production.INFO: Global Request URI: /