PHP – how to convert array of values to array with nested keys from values of first array? [closed]

I have this array:

$input = ['a', 'b', 'c', 'd'];

the output should be:

$output = convertArrayValues($input, 'final');

$output['a']['b']['c']['d'] = 'final;

I need code for convertArrayValues() method which will do the job of converting:

$input = ['a', 'b', 'c', 'd'];

into:

 $output['a']['b']['c']['d'] = 'final;

Dumped array input:

array:4 [
  0 => "a"
  1 => "b"
  2 => "c"
  3 => "d"
]

Dumped array output:

array:1 [
  "a" => array:1 [
    "b" => array:1 [
      "c" => array:1 [
        "d" => 'final
      ]
    ]
  ]
]

PDFTK library disable links in PDF

In PHP I use library PDFTK for password protect output PDF files.
Everything works as should apart links in documents that been protected by password.

All links are set “disabled” attribute and it’s not possible to click it.

How to fix it?

enter image description here

How to change image on the post when shared offsite in php?

I have some job postings on my website, and for each Job Ad i want to share it on LinkedIn and Facebook. Up till here it works but there is a random image on that sharing. how can i change that?

I have used this

<a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo (''.get_home_url().'/jobb/'.get_query_var('job_name'));?>" alt="linkedin"> Linked In </a>

but it shows this , see attched image.

enter image description here

How can I get variation purchage by product id in woocommerce?

How can I get variation purchase by product id in woocommerce?

I want to compare with sale total and purchase total
from api in another web page. but I tried to find the way to get from functions.php
I didn’t found it. someone who know how to get variation purchase price by product id.
please show me how to get it. Thanks anyway.

How to manage summer and winter datetimes in php

I have a site where I need to store a lot of events with a start and end date. So I store the startDate and endDate at GMT time in the database.

However, when France switches to winter time, we end up with not GMT +2 but GMT +1. No problem for converting a DateTime to the correct time… But how do you manage dates that were set before the switch to winter time and are scheduled for the future (once winter time has been changed)? My whole schedule is off by an hour.

I think my problem is fairly trivial, but I’m having trouble understanding where I went wrong. What is the right way to do? How to avoid this type problem?

Thanks for your precious help!

Store datetime in GMT timezone in database

How to debug Google APIs Client Library for PHP error ACCESS_TOKEN_SCOPE_INSUFFICIENT

We’re using Google APIs Client Library for PHP (https://github.com/googleapis/google-api-php-client) using authentication with Service Accounts.

The code is

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $google_api_key_file_path);
$client = new Google_Client();
$client->setApplicationName('Google Translate API');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Translate::CLOUD_TRANSLATION);
$service = new Google_Service_Translate($client);
$projects = $service->projects;
$postbody = new Google_Service_Translate_TranslateTextRequest();
$postbody->setContents($contents);
$postbody->setSourceLanguageCode($source_lang);
$postbody->setTargetLanguageCode($target_lang);
$result = $projects->translateText('projects/myproject', $postbody)->translations;

The code worked fine until about a month ago, but now returns this error:

{ "error": { "code": 403, "message": "Request had insufficient authentication scopes.", "errors": [ { "message": "Insufficient Permission", "domain": "global", "reason": "insufficientPermissions" } ], "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "metadata": { "service": "translate.googleapis.com", "method": "google.cloud.translation.v3.TranslationService.TranslateText" } } ] } }

Nothing has changed at the code level or at the account settings level on Google.

The API are enabled and the same Service Account works fine with other APIs.

enter image description here

We tried disabling and re-enabling the API again.

Delete button inside my action column not functioning

I have a code for retrieving question data inside my database and I have a action column for delete and edit, I dont have a code for edit but in delete, I want the delete to be function dynamically in all tables inside my database, and its not working, if I click delete and ok the page output is the else which is Invalid ID or table provided, anyone can help?

CODE FOR DELETE

<!DOCTYPE html>
<html lang="en"
<body>

    <?php
    $servername = "localhost";
    $username = "root"; // Replace with your MySQL username
    $password = ""; // Replace with your MySQL password
    $dbname = "question_databank"; // Replace with your database name

    if (isset($_GET['table']) && !empty($_GET['table'])) {
        $table = $_GET['table'];
    } else {
        die("Table name not provided.");
    }

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM $table";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        echo "<table>";
        $row = $result->fetch_assoc();
        echo "<tr>";
        foreach ($row as $key => $value) {
            echo "<th>$key</th>";
        }
        echo "<th>Action</th>";
        echo "</tr>";

        do {
            echo "<tr>";
            foreach ($row as $value) {
                echo "<td>$value</td>";
            }
            echo '<td class="action-column">';
            echo '<a class="edit" href="#" onclick="confirmEdit(' . $row['id'] . ')"><i class="fas fa-edit"></i></a>'; // Edit icon
            echo '<a class="delete" href="#" onclick="confirmDelete(' . $row['id'] . ')"><i class="fas fa-trash-alt"></i></a>'; // Delete icon
            echo '</td>'; // Delete icon
            echo '</td>';
        } while ($row = $result->fetch_assoc());

        echo "</table>";
    } else {
        echo "0 results";
    }

    $conn->close();
    ?>

    <script>
        function confirmDelete(id) {
            var result = confirm("Are you sure you want to delete this record?");
            if (result) {
                window.location.href = 'action/delete.php?id=' + id;
            }
        }

        function confirmEdit(id) {
            var result = confirm("Are you sure you want to edit this record?");
            if (result) {
                window.location.href = 'action/edit.php?id=' + id;
            }
        }
    </script>
</body>

</html>

CODE FOR delete.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "question_databank";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_GET['id']) && isset($_GET['table']) && !empty($_GET['id']) && !empty($_GET['table'])) {
    $id = $_GET['id'];
    $table = $_GET['table'];

    // Use mysqli_real_escape_string to prevent SQL injection
    $id = mysqli_real_escape_string($conn, $id);
    $table = mysqli_real_escape_string($conn, $table);

    // Create a SQL query to delete the record
    $sql = "DELETE FROM $table WHERE id = $id";

    if ($conn->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record: " . $conn->error;
    }
} else {
    echo "Invalid ID or Table provided";
}

$conn->close();
?>

For my delete button to function dynamically in all of the tables inside my database

ubuntu www-data group member delete file permission problem

I created this folder in php with

mkdir($folder, 0770, true)

my user

sudo usermod -a -G www-data my_user

folder permissions

ls -l /var/www/html/test/1/ 

-rwxrwx--- 1 www-data www-data

After that i can’t delete this folder with my_user in ftp or ssh connection in vs code.

“permission denied” error returned.

if i change the folder owner to my_user then i can delete the folder. my_user also member of www-data. with 770 attributes, shouldn’t it be possible to delete the file as a group member without being the owner?

Is there a way i can solve Error 405 after trying to connect php to mySQL?

I experienced error 405 after trying to connect php with mySQL database.Below is my code snippet;

`<?php
$mysqli = new mysqli('localhost', 'root', 'password', 'dexnetworks');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$userName = $_POST['userName'];
$phoneNumber = $_POST['phoneNumber'];
$email = $_POST['email'];
$password = $_POST['password'];

$stmt = $conn->prepare("INSERT INTO register (userName, phoneNumber, email, password) VALUES (?, ?, ?,   ?)");
$stmt->bind_param("ssss", $userName, $phoneNumber, $email, $password);

if ($stmt->execute() === TRUE) {
    echo "Record added successfully";
} else {
    echo "Error: " . $conn->error;
}

$stmt->close();
}
$conn->close();
?>`

I wrote a php code for connecting database to my website where my registartion tab is register.html ,afterwards i tried registering a new user expecting the registration to be successful i was redirected to Error 405 page.

Wrong result when checking if an email address exists in the database

I have database with table ‘users’ which does not contain any records. I want to check if an email address exists.

When I apply query SELECT COUNT(user_id) FROM users WHERE email = 'mm@mmm' in phpMyAdmin, result is ‘0’.

When I use code below in a file, result is ‘1’, although table does not contain any records.

$sql = 'SELECT COUNT(user_id) FROM users WHERE email = :email';
$query = $conn->prepare($sql);
 $result = $query->execute([':email' => 'mm@mmm']);
 
 print_r($result); // 1

When I use code below in a file, result is ‘0’.

$sql = 'SELECT (user_id) FROM users WHERE email = :email';
    
$query = $conn->prepare($sql);
$query->execute([':email' => 'mm@mmm']);
    $result = $query->rowCount();
    print_r($result); // 0

My question is, what is wrong with the first code.

Different horizon configs based on server

In config/horizon.php you can define how many processes you want to dedicate to each Horizon queue. If I have a second server that isn’t used for processing requests, and is just going to be used to process certain jobs and tasks, how can I set it so that ONLY this second server looks at one queue and the other main server doesn’t look at that queue?

Eg I have a queue called Webhooks, and I want the second server to process Webhooks only and the main server not to process any jobs from the Webhooks queue at all. What’s the right way to go about that?

Do I just have a different horizon.php file on each server, one with 0 processes assigned to Webhooks and one with, say, 20 processes assigned?

Woocommerce Cart VAT

I would like to show my woocommerce tax amount on each of the products rather that a total

I tried a few different hooks however I am quite new to a hooking system

I have also checked a few other questions but it does not seem like this has been raised on a newer version of woocommerce

login with php but the user data comes from a csv file

I want to extract my user data from a csv file, pack it into an array and then check whether the user’s input matches data from the csv file

This is my previous code:

<?php
session_start();

$handle = fopen('users.csv', 'r');
while (($csv_array = fgetcsv($handle, NULL)) !== false) {
    foreach ($csv_array as $index) {
    }
    if (isset($_POST['vorname']) && isset($_POST['nachname']) && isset($_POST['mail']) && isset($_POST['passwort'])) {
        $vorname = $_POST['vorname'];
        $nachname = $_POST['nachname'];
        $mail = $_POST['mail'];
        $pw = $_POST['passwort'];

        if ($vorname == $index['vorname'] && $nachname == $index['nachname'] && $mail == $index['mail'] && $pw == $index['passwort']) {
            $_SESSION['vorname'] = $vorname;
            $_SESSION['nachname'] = $nachname;
            $_SESSION['mail'] = $mail;
            $_SESSION['passwort'] = $pw;
            header("Location: account.php");
        }
    }
}

fclose($handle);

?>

ps: i dont use a database for this

Warning Undefined array key”user_image”in path:user_reg.php on line124 Trying to access array offset on value of type null inuser_reg.php on line124 [duplicate]

enter image description here

enter image description here

Warning: Undefined array key “user_image” in C:xampphtdocsEcomusers_areauser_registration.php on line 124

Warning: Trying to access array offset on value of type null in C:xampphtdocsEcomusers_areauser_registration.php on line 124

Warning: Undefined array key “user_image” in C:xampphtdocsEcomusers_areauser_registration.php on line 125

Warning: Trying to access array offset on value of type null in C:xampphtdocsEcomusers_areauser_registration.php on line 125

<!-- Image field -->

<div class="form-outline mb-4">
<label for="user_image" class="form-label">User Image</label>
<input type="file" id="user_image" class="form-control" required="required" name="user_image" />

<?php
if (isset($_POST['user_register'])) {
$user_username = $_POST['user_username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
$conf_user_password = $_POST['conf_user_password'];
$user_address = $_POST['user_address'];
$user_contact = $_POST['user_contact'];
$user_image = $_FILES['user_image']['name'];
$user_image_tmp = $_FILES['user_image']['tmp_name'];
$user_ip = getIPAddress();
//insert query
move_uploaded_file($user_image_tmp, "./user_images/$user_image");
$insert_query = "insert into `user_table` (username,user_email,user_password,user_image,user_ip,user_address,user_mobile) values ('$user_username','$user_email','$user_password','$user_image','$user_ip','$user_address','$user_contact')";
$sql_execute = mysqli_query($con, $insert_query);
if ($sql_execute) {
echo "alert('Data inserted succesfully.')";
} else {
die(mysqli_error($con));
}
}
?>

i change multipart spelling too after posting this question