Getting error in PHP, foreach() argument must be of type array|object, string given

Getting that error, while developing the plugin by following a youtube video series.

$options = get_option('vaishnavi_plugin_cpt');
foreach (  ($options) as $option) {
    $this->custom_post_types[] = array(
    'post_type'             => $option['post_type'],
    'name'                  => $option['plural_name'],
    'singular_name'         => $option['singular_name'],
    'menu_name'             => $option['plural_name']
  )
}

After looking in on how to solve this issue, I have just added a check if(is_array($options))
above the foreach, the error got resolved but I am not getting the desired o/p.

Also, when I var_dump($options), it gives me string(0) "".

When I checked the get_option wp method, it says the following

When adding options like this: add_option( 'my_option_name', 'value' ) and then retrieving them with get_option( 'my_option_name' ), the returned values will be:

false returns string(0) ""
true returns string(1) "1"
0 returns string(1) "0"
1 returns string(1) "1"
'0' returns string(1) "0"
'1' returns string(1) "1"
null returns string(0) ""

Can any one please explain on why it is not showing me the array, or any possible solution.

DOMDocument Table Content Laravel Database

I want to create a table content page using the DODocument method with Laravel. How do I use it? Then I want to get it from the database.

I have a code and I want to get it from the database and display it in the view.

<!DOCTYPE html>
<html>
<head>
<title>Sample table of contents</title>
</head>
<body>
<div id="table-of-contents">
     <h2>Table of Contents</h2>
     <ul>
       <li><a href="#introduction">Introduction</a></li>
       <li><a href="#section1">Section 1</a></li>
       <li><a href="#section2">Section 2</a></li>
       <li><a href="#section3">Section 3</a></li>
       <li><a href="#section2">Section 4</a></li>
     </ul>
   </div>
<h1 id="introduction">Introduction</h1>
<p>This is an introduction section.</p>
<h2 id="section1">Section 1</h2>
<p>This is part 1.</p>
<h2 id="section2">Section 2</h2>
<p>This is part 2.</p>
<h2 id="section3">Section 3</h2>
<p>This is part 3.</p>
<h2 id="section4">Section 4</h2>
<p>This is section 4.</p>
</body>
</html>

Synfony Nelmio Attributs And Normalizer

I’ve nested objects :

class Review{
  #[Groups(['read'])]
  public int id;
  #[Groups(['read'])]
  public string author;
  /**
  * @var Comment[] comments
  */
  public array comments;
}
class Comment{
  public string lang;
  public string comment;
}

I use this Review object as response for an api route.

I have a normalizer that replace comments from Review by a comment string (the comment in desire language) so the response of my route is an JSON object like :

{
  id:3,
  author:'Philip',
  comment:'Good comment'
}

I use attributs to describe the route’s return :

#[OAResponse(
    response: 200,
    description: 'Return a review',
    content: new OAJsonContent(ref: new Model(type: Review::class,groups: ['read']))
)]

The comment property is missing in the description of the response, is there a way to add it ?

I want to use the ghostwriter/atprotocol library to access the BlueSky social API, but don’t know how to use it.Where are the Bluesky classes listed?

ghostwriter/atprotocol library

vender/autoload.php
index.php

<?php
ini_set('display_errors','1');
error_reporting(-1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
ini_set('xdebug.var_display_max_depth', -1);

require './vendor/autoload.php';
$bsky = new Bluesky(personalDataServer: 'https://bsky.social');

No error messages are shown.
I am not sure why no error message is shown.

For Usage,

$bsky = new Bluesky(personalDataServer: 'https://bsky.social');

but where in the code is the Bluesky class written?

Error logging in to the WordPress dashboard [duplicate]

I customized and changed WordPress login page by code snippet. After I successfully login to the site, I get the following error:

Warning: Cannot modify header information – headers already sent by (output started at C:wamp64wwwxxxwp-contentthemesxxxheader.php:60) in C:wamp64wwwxxxwp-includespluggable.php on line

How to fix this error?

How to fix this error?

execute_query for inserting inside a table some values [duplicate]

i was wondering, how could i put values as ? inside the query line?

<?php
$ip = $_SERVER["REMOTE_ADDR"];
$name=$_POST["name"];
$email=$_POST["email"];
$message = $_POST["text"];
$mysql_connection = new mysqli("localhost", "webcraft", "",  "my_webcraft");
$execution = $mysql_connection->execute_query("INSERT INTO requests(ip, name, email, message) VALUES($ip, $name, $email, $message)", [$ip, $name, $email, $message]);
if($execution != TRUE){
    die("error");
}

?>

will this work?

Display custom order meta in order received page and notification emails

I’ve found this question on how to display custom order meta into the order received page and into the notifications email of woocommerce. I’ve tried to do the same by refactoring the code but I’m unable to accomplish it correctly. In my case I have only three custom informations stored in product meta to display, how I need to fix the code?

    // Display order custom meta data in Order received (thankyou) page
    public function display_order_custom_meta( $order_id ) {

        $fields_labels = array(  
            'selected_pdv',
            'selected_date',
            'selected_hour'
        );
        
        $order = wc_get_order( $order_id );
        $count = 1;

        // Loop through order items
        foreach ( $order->get_items() as $item ){
            // Loop through item quantity
            for($i = 1; $i <= $item->get_quantity(); $i++ ) {
                echo '<h6> '.$i . '</h6>';
                echo '<table><tbody>';
                // Loop through participants keys / labels pairs
                foreach( $fields_labels as $label ){
                    $meta_key = $label;
                    echo '<tr><th>'.$label.':</th><td>'.$order->get_meta( $meta_key ).'</td></tr>';
                }
                //
                echo '</tbody></table>';
            }
            $count++;
        }
    }
    add_action('woocommerce_thankyou', array($this, 'display_order_custom_meta') )

Pass checkout form fields to redirect url / Pass parameter to redirect url

I’m working with wordpress using woocommerce and checkout field editor pro for adding extra fields to the checkout form. Im also using a payment gateway from a local bank.

Right now after the payment is processed the gateway plugin redirect to a set url that make some task like save some info to database and send some extra information to the local bank. The redirect url looks like this like this example.com/?wc-api=paymant_gateway and is set in the woocommerce/payment_settings.

Recently the local bank has requested some extra info that we need to ask the customer in the checkout form and they has told us the only way to do this is to pass the parameters to the redirect url like this example.com/?wc-api=paymant_gateway&field1=value&field2=value&field3=value ,etc.

I have tested it putting the fields manually (hardcoded) in the payment settings and it works it send the extra fields to the local bank

But I dont know how to pass the checkout form values as parameters to the redirect url example.com/?wc-api=paymant_gateway

I have try to look the file that manage the call to wc_api after the payment is processed but I can’t find it because maybe it’t not necessary to pass the parameter to the redirect url but in the file that process the call to wc_api=payment_gateway I could retrieve the order info and retrieve all the checkout form saved values and insert them in the file and in the logic that sends the info to the bank but I still cant find it. I dont know how to retrieve that info tho but I have seen that woocommerce has a built in function to retrieve that information because right now all the info from the checkout form is saved in the order info.

I have harcoded the parameters in the redirect url in the woocommerce/settings/payment settings like this example.com/?wc-api=paymant_gateway&field1=value&field2=value&field3=value and it’s working. It sends the harcoded values to the local bank.

Has somebody done anything like this before?
Thanks

Trouble with PHP Array Mapping for JSON Output in WooCommerce Order Processing

Hello Stack Overflow Community,

I am working on a WooCommerce-based project in PHP and encountering an issue with mapping product details to a specific ‘class’ value in a JSON output. Despite attempting several debugging steps, I can’t seem to resolve the incorrect assignment of the ‘class’ ID in the JSON. I would appreciate any insights or suggestions.

Problem:
I have a PHP function that processes WooCommerce orders. It’s supposed to map each product in an order to a specific ‘class’ based on its plant attribute (‘pa_plant’). The ‘class’ value, along with other details, is then used to create a JSON object for each product. However, the ‘class’ ID in the resulting JSON is consistently incorrect.

Array:

$profitCentre_mapping = [
'38' => '2375',
'28' => '2385',
'34' => '2386',
'34' => '2386',
'35' => '2477'
];
$profitCentre = 'NO PROFIT CENTRE'; // Initialize profitCentre outside the loop
        if (!isset($items_by_depot[$depot_id])) {
            $items_by_depot[$depot_id] = [];
        }
        
        $profitCentre = isset($profitCentre_mapping[$depot_id]) ? $profitCentre_mapping[$depot_id] : 'NO PROFIT CENTRE';

//JSON Snippet:
            "location" => ["id" => $depot_id],
            "class" => ["id" => $profitCentre],
  1. Checked and double-checked the mapping arrays for any inconsistencies or typos.
  2. Added debugging statements to print out values of key variables during processing.
  3. Isolated the problem to ensure that the issue lies within the loop where depot_id and profitCentre are assigned.
  4. Reviewed the conditions for assigning depot_id and profitCentre.

InvalidArgumentException PHP 8.2.11 10.32.1 “now – 72000000000000 seconds” is not a valid date [closed]

Hello StackOverflow Community,

I am currently encountering a perplexing issue in my PHP 8.2.11 production environment, and despite several attempts, I have been unable to resolve it completely. The error message I’m encountering is:

InvalidArgumentException: PHP 8.2.11 10.32.1 “now – 72000000000000 seconds” is not a valid date

This issue seems to occur sporadically in my live production environment, while the code works flawlessly in my local environment.

The primary concern is related to the generation of a slug using the Laravel SlugService and now() function. To mitigate the problem, I initially used the following code:

$slug = SlugService::createSlug(AppModelsCompany::class, 'slug', $request->name) . '-' . now()->format('YmdHis');

In an attempt to mitigate the issue, I modified the code as follows:

$slug = Str::slug($data['name']) . '-' . mt_rand(100000000, 999999999);

Regrettably, the error still persists sporadically in the live production environment. I have thoroughly reviewed all date-related options, but the problem persists.

I am reaching out to seek guidance on potential solutions or insights into why this error might be occurring inconsistently in a live production environment.

error

I want to create a post PHP API for my website

I am a beginner and I need to create an API for my website, that will be used to post data into my SQL Server database.

I found a tutorial on Youtube but it doesnt seem to work for me.
(I am getting a blank page with just this in it: [])

Any help will be appreciated.

This is the code I have at the moment:

<?php
include("connection.php");
$response=array();
if($conn){
    $sql="select * from [new_candidate]";
    $result = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => 'static' ));
    if($result) { 
        header("Content-Type:JSON");
        $i=0;
        while($row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)){
            $response[$i]["candidate_id"] = $row["candidate_id"];
            $response[$i]["first_name"] = $row["first_name"];
            $response[$i]["last_name"] = $row["last_name"];
            $response[$i]["email"] = $row["email"];
            $response[$i]["tel"] = $row["tel"];
            $response[$i]["branch"] = $row["branch"];
            $response[$i]["job_id"] = $row["job_id"];
            $response[$i]["job_title"] = $row["job_title"];
            $response[$i]["date_applied"] = $row["date_applied"];
            $i++;
        }
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
} else {
    include_once("no_connection.php");
}

Running php website on Google App Engine Standard doesn’t route to subfolders and files

I’m trying to migrate our website from a linux vm (also on google) to google App Engine Standard enviroment.

When i deploy the app and test it the main page (index.php) works fine but when i try to go to other files, for example /somefolder/somefile.php it doesnt. It just shows the index.php but without the pictures etc.

I searched the internet and i found that this is probably due to not having a front end controller(?)

My app.yaml file is as followed:

service: nameoftheapp
runtime: php83

handlers:
# Serve images as static resources.
- url: /(.+.(gif|png|jpg))$
  static_files: 1
  upload: .+.(gif|png|jpg)$

- url: /(.+.php)$
  script: auto

- url: /.*
  script: auto

my index.php is:

<?php



// android store
if (preg_match('#android#i', $_SERVER ['HTTP_USER_AGENT'])) {
    header('Location: market://details?id=nl.myapp');
    exit;
}

// ios
if (preg_match('#(iPad|iPhone|iPod)#i', $_SERVER ['HTTP_USER_AGENT'])) {
    header('Location: https://apps.apple.com/us/app/myapp/id973246494');
    exit;
}
echo "<html> <head> </head> <body>";
echo '<center><p><br><p><br>Sometext</center> <p>';
echo '<center> some more text.</center> <p>';
echo "<center> <img width='800' src='images/logo_GW_forweb.jpg'</center> <p>";
echo "<center> yet some more text</center> <p>";
echo "</body>";

?>

the index.php serves as a simple landing page for users to redirect them to the appstores for the app. As far as this goes, this works well. also the logo, which resides in a subfolder is shown.

But i myself want to go to https://mywebsite.nl/somefolder/somefile.php

This part doesnt work. Can this be resolved by just setting the right app.yaml (i do have like 10 subfolders with some having their own subfolders and a total of 100+ .php files)

Do i need something else? I was hoping there would be a settings for the app.yaml that routes all reguests to the right place.

I made a test app to see how to get it working. This one works, but i doubt this is the way to go.

The app.yaml file states:

runtime: php83
service: test

handlers:
- url: /.*
  script: index.php

And the index states:

<?php
$requestUri = $_SERVER['REQUEST_URI'];

// Hier kun je logica toevoegen om het verzoek te routeren naar de juiste actie/controller
if ($requestUri === '/test/test.php') {
    require 'test/test.php';
} elseif ($requestUri === '/root.php') {
    require 'root.php';
} else {
    // Standaard HTML-tekst als de URI niet overeenkomt met specifieke routes
    echo "<!DOCTYPE html>";
    echo "<html lang="en">";
    echo "<head>";
    echo "    <meta charset="UTF-8">";
    echo "    <meta name="viewport" content="width=device-width, initial-scale=1.0">";
    echo "    <title>Test App</title>";
    echo "</head>";
    echo "<body>";
    echo "    <h1>Hallo dit is een test</h1>";
    echo "    <p>Welkom bij de PHP-testapplicatie op Google App Engine!</p>";
    echo "    <p><a href="test/test.php">Ga naar test.php</a></p>";
    echo "    <p><a href="root.php">Ga naar root.php</a></p>";
    echo "</body>";
    echo "</html>";
}
?>

This one works. i can access the root.php as well as the test.php which is located in the subfolder test. But i doubt this would be the way to go for my own website.

php array is not output in js

I’m trying to output an array to the Highcharts js graph. I’ve been working on this for two days now, and the array is output properly via echo and print_r in php code. But substituting the variable into the graph does not work.

Php code:

<?php 
$data = array();
$conn = mysqli_connect("localhost", "root", "", "fitness");
$sql=("SELECT weight fROM users  where id_users=".$_SESSION['id']." ");          
if($result = mysqli_query($conn, $sql)){
   while($row = mysqli_fetch_array($result)){
        $data[] = array($row['weight]);             
             }
              $ar =  json_encode($data);
    echo json_encode($ar);

} else{
    echo "<li><h2>The graph is empty</h2></li>";
}
mysqli_close($conn);
?>

I’m trying to substitute an array like this:

var weight = (<?php echo $ar;?>);

I’ve tried a bunch of combinations. the only code that output a variable to the graph is js in php, which is output via echo with an array variable in the graph. but it’s such nonsense that I gave it up. and the code itself output only one array value, although there are several in the database.

SVG image is being identified as PNG, after being base64 decoded from a Base64 string

I am trying to add a validation in my Symfony controller where I need to validate file types of base64 image. So basically I am sending base64 images to the backend and there I am checking whether the file is jpeg or png. If the file is anything other than those then the validation should fail.

So my code seems to be working fine for JPEG and PNG where it passes the validation and fails for WebP. But when I try with a base64 SVG file, it passes as well (which should not pass). If I debug it, I can see the mime type of the file as image/png. So apparently it is being identified as a PNG file.

What could be the reason for this? And how can I fix it?

Here’s the code:

public function isAllowed(array $file): bool
{
    $fileType     = $file['filetype'];
    $base64Image  = $file['base64'];

    $binaryData = base64_decode($base64Image);

    $directoryPath = '/var/www/tmp';

    if (!is_dir($directoryPath)) {
      mkdir($directoryPath, 0777, true);
    }

    $tempFileName = tempnam($directoryPath, 'uploaded_file');
    file_put_contents($tempFileName, $binaryData);

    $file = new File($tempFileName);

    $validatorBuilder = Validation::createValidatorBuilder();
    $validator = $validatorBuilder->getValidator();

    $constraints = [
      new SymfonyComponentValidatorConstraintsFile([
        'mimeTypes' => self::ALLOWED_IMAGE_FILE_TYPES
      ]),
    ];

    $errors = $validator->validate($file, $constraints);

    unlink($tempFileName);

    return count($errors) > 0 ? false : true;
}

Please note:

  1. base64 string is without the first part. That is, if file has base64 string as data:image/png;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMj then in the function it is only PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMj. It is working fine without the first part.
  2. Using Symfony 4.
  3. When a temp file is created, it doesn’t have any extension.

Download Files with Python from PHP

I would like to download several files with a Python script from a PHP function.

These files are not accessible by a direct link e.g., www.example.com/file.pdf. However, the headers are sent after some security checks. PHP server side:

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($publicName).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($internalPath));
        readfile($internalPath);

Calling this with common browsers works well.

For further purposes I need Python script on the client side to download and save the provided files which is currently very basic like this:

import urllib.request
urllib.request.urlretrieve("https://example.com/app/provideFile/filename", "download.pdf")

The script runs without any error and saves direct downloads (https://example.com/file.pdf) correctly. Calling the PHP logic (https://example.com/app/provideFile/filename) leads to broken files with very small file sizes on the client.

Is there a way to modify the server side or the client side to make this working?