Undefined Variable global conn | php [duplicate]

Hi I have class that this codes :

$conn = mysqli_connect($host,$username,$password,$dbname);

And I need call $conn that function in users.php ; code :

include("db.php");

function getUsers()
{
    $sql = "...";

    global $re;

    $re = mysqli_query($conn ,$sql);
}

My Error :

Undefined Variable: conn in users.php

`debug_backtrace()` reports abstract classes in trace rather than concrete classes. Is there a fix?

I wrote the following code which turns the result of debug_backtrace() into a string:

function debug_backtrace_string($skip = 1)
{
    try
    {
        $calls = debug_backtrace();
        $calls = array_slice($calls, $skip);
        $str = [];
        foreach ($calls as $call)
        {
            if (isset($call['args']))
                foreach ($call['args'] as $k => $v)
                    $call['args'][$k] = gettype($v).' '.'"'.substr($v, 0, 100).'"';
            else
                $call['args'] = [];
            $str[] = ($call['file']??'')
                    .(isset($call['line'])?' ('.$call['line'].')':'')
                    ." ".($call['class']??'').($call['type']??'').$call['function']
                    .'('.implode(', ', $call['args']).')';
        }
        return implode("n", $str);
    }
    catch (Throwable $e)
    {
        return "debug_backtrace_string($skip) failed: ".$e;
    }
}

The problem is I’m trying to debug quite a lot of code in an abstract class, and it’s extended by 3 classes. But more often than not, the above code spits out the name of the abstract class rather than the concrete class, and it’s really making life difficult because I’m having trouble differentiating which concrete class is doing what.

Is there a way round this?

My dropdown menu does not drop down when tapped , here is my code

JavaScript function

document.addEventListener("DOMContentLoaded", () => {
  enableDropDowns();
});

const enableDropDowns = () => {
  const dropdownElementList = [].slice.call(
    document.querySelectorAll(".dropdown-toggle")
  );
  dropdownElementList.map((dropdownToggleEl) => new Dropdown(dropdownToggleEl));
};

My block Body of Base.html.twig

<nav class="py-2 bg-dark border-bottom">
            <div class="container d-flex flex-wrap">
                <div class="dropdown">
                    <a class="nav nav-link dropdown-toggle" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                    Mon Blog
                    </a>
                    <ul class="dropdown-menu" aria-labelledby ="dropMenuButtonAdmin">
                        <li><a class="dropdown-item" href="#">Tableau de bord</a></li>
                        <li><a class="dropdown-item" href="#">Menus</a></li>
                        
                    </ul>
                </div>
            </div>
        </nav>

I have no error in my console.

How can i make the dropdown menu drop down ?

PHP Warning: Undefined array key 0 in /wp-content/themes/HighendWP/functions/breadcrumbs.php on line 208

I’m getting this error, and an unknown file keeps appearing on cPanel no matter how many times I delete it. I have changed all passwords (WordPress and cPanel), and I have tried everything possible to stop this, but I don’t have any idea where this malicious activity is coming from. I am wondering if it could be from a plugin. All my plugins are up to date!

The issue type is: Suspicious:PHP/stringors.5592
Description: Suspicious code often used to obfuscate malicious activity.

The malicious file names are as follows: .b305d934.mo, .0a313496.mo, .f49fcca7.mo.

I have checked with the Bluehost support team, and they informed me that all the files are protected with host permissions, so the issue should not repeat. However, it is still happening every day. They also confirmed that the problem is not caused by a plugin, but they did not provide any information regarding the root cause of the problem.

How to properly include acf in wordpress search?

I have a custom post type called “servizio” which can have a list of “doctor” (cpt) associated. These doctors are linked to the “servizio” using the acf “medici”, infact if I inspect the table postmeta I will get this situation:

enter image description here

as you can see the “servizio” meta_key has “medici” which contains a list of references of the linked “doctor” (cpt)

So I wrote this code in the functions.php to extend the wp search functionalities:

function add_acf_in_search($query)
{
    if ($query->is_search() && $query->is_main_query()) {
        $s = $query->query_vars['s'];
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => 'medici',
                'value' => '"' . $s . '"',
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'medici',
                'value' => '%:' . $s . ';%',
                'compare' => 'LIKE'
            )
        );
        $query->set('meta_query', $meta_query);
    }
}
add_action('pre_get_posts', 'add_acf_in_search');

This code is supposed to return the “servizio” if I search for a “doctor” associated as acf repatable field, but it doesn’t.

Example:

servizio: "lorem ipsum"
linked doctors "mario rossi" "john travolta"

If I search for “travolta” I should get the servizio “lorem ipsum”.

Displaying metadata for multiple authors in Elementor’s “widget posts”

I’m facing a little issue with WordPress, and I could really use your help. You see, I’m not very experienced with coding, so I’m hoping you can lend me a hand in the right direction.

I’m using the PublishPress Authors plugin to have multiple authors on my website, and Elementor as my page builder. But here’s the catch: when I create a page with the latest posts using Elementor’s “widget posts” feature, it only displays metadata for one author. However, I want to show metadata for all the authors associated with the posts.

Now, here’s where I’m struggling. I think the problem lies in the code, but I’m not sure which file to look at or where exactly to make the changes. It would be fantastic if you could guide me on this!

I’ve heard that the PublishPress Authors plugin has this cool “get_coauthors” function that can fetch an array of co-authors for a post. That sounds like the key to the solution! But I could use some assistance in locating the code that needs modification and making the necessary changes.

Thank you so much for your kind assistance and support. I truly appreciate your patience with a beginner like me!

Attempted: Multiple author metadata display.
Expected: All authors’ metadata.
Actual: Single author displayed.

PHP exit message as bubble alert [closed]

I have a registration form and when someone not filling some row correctly it gets an error message, but it redirects to another page. I don’t want that. I want to display this message as a bubble next to the field.

if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
    exit('Your password must be between 5 and 15 characters!');
}

How should I modify the exit() line?

Thank you!

Can i send push notification to opera mobile browser using php mysql ajax like facebook

I am using this code it only word desktop browser and when i still this page, i want to puse remotly to a briwser.

I want to send push notification to opera mobile browser like hiw facebook send. Please help me

enter image description here
Suggest me javascript php mysql code



<script>
function pushNotify() {
    if (!("Notification" in window)) {
        alert("Web browser does not support desktop notification");
    }
    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        $.ajax({
        url : "push-notify.php",
        type: "POST",
        success: function(data, textStatus, jqXHR) {
            // if PHP call returns data process it and show notification
            // if nothing returns then it means no notification available for now
            if ($.trim(data)){
                var data = jQuery.parseJSON(data);
                console.log(data);
                notification = createNotification( data.title,  data.icon,  data.body, data.url);
                setTimeout(function() {
                    notification.close();
                }, 5000);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {}
        });
    }
};

function createNotification(title, icon, body, url) {
    var notification = new Notification(title, {
        icon: icon,
        body: body,
    });
    notification.onclick = function() {
        window.open(url);
    };
    return notification;
}
</script>

PHP request not running

I am trying to call a PHP endpoint to simulate an activation. The form requires a x-token for authentication. I am running this using mamp in localhost and the form refuses to run (it returns 200 so it does find the form but just does not ping the endpoint do anything). Does anyone know what I’m doing wrong here? I believe its something to do with the localhost but I’m unsure.

<?php
// this requests a new site to be made when run. 

$islive = 1;

$companyname = 'TestCompany';
$memberFirst = 'Luke';
$memberLast = 'J';
$email = '[email protected]';
$phone = "07375182757";
$memberlocation = 'United Kingdom';
$town = 'Roford';
$county = 'assak';
$theme = 'dark';
$colour1 = "880808";
$colour2 = "880808";
$companytype = 'Carpentry';
$services = 'Carpentry';
$box1 = 'We specialise in all types of **COMPANY_TYPE** services';
$box2 = 'We specialise in all types of **COMPANY_TYPE** services';
$cta = 'Do you want to start a new Building Or Renovation project in **COMPANY_COUNTY**?';
$data = array(
    "memberName" => $companyname,
    "firstName" => $memberFirst,
    "lastName" => $memberLast,
    "memberEmail" => $email,
    "memberPhone" => $phone,
    "memberAddress" => $memberlocation,
    "memberTown" => $town,
    "memberCounty" => $county,
    "theme" => $theme,
    "colour1" => $colour1,
    "colour2" => $colour2,
    "companyType" => $companytype,
    "services" => $services,
    "box1" => $box1,    
    "box2" => $box2,
    "cta" => $cta,
);
$headers = array(
    'X-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    // 'Content-Type: multipart/form-data'  
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "MYURL");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

if($islive == 0) {
    curl_setopt($ch, CURLOPT_CAINFO, "LOCALLOCATION/cacert.pem");
}

$response = curl_exec($ch);
$responsecode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if(curl_error($ch)) {
    $error = curl_error($ch);
}

curl_close($ch);

I have tried to change the code but it appears to be correct syntactically and produces no errors. Its like the request isnt reaching the endpoint file.

Finding echo’s content

Hi – I am trying to edit the nav on this page of our site:
https://staging.tamilhousing.org.uk/resident-community/

The dev who built the site is no longer available and instead of using wordpress content management tools he has built it in custom php – which we don’t get (thanks dev btw!)

We have been able to use some native wit to edit most things but this nav as defeated us. The page template contains this bit of markup:

<div class="sidebar">
<nav>
<?php echo $sideBarNav; ?>
</nav>
</div>
 

We were hoping to find a file called sideBarNav but we can’t! No amount of ftp or database searches will reveal where the markup for this nav is hidden. Can anyone point us to where we might look?

Thanks in advance

Did full ftp and DB search for sideBarNav

Failed to Send Emails From My Laravel Application Using Cpanel

I’m trying to send 2 emails when user will submit the contact form.
1 should be sent to the user email & the other should be sent to my own email.
My .env file look like this:

MAIL_MAILER=sendmail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=m.s***********@gmail.com
MAIL_PASSWORD='************'
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=m.s***********@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

I’m sending the emails from controller like this:

dd($request->email);
Mail::to($request->email)->bcc('[email protected]')->send(new ContactSubmit($contact));

I’m receiving all the emails on [email protected] but not receiving on any other domain.
dd($request->email); is showing me correct emails.

Before I was trying to send emails from my own domain:

[email protected]

But I was receiving this error in my inbox:

SMTP error from remote mail server after end of data:
552 5.2.0 xkfupRYgo20R2xkfupkpjt :CPANEL: Access to this mail system has been blocked for xh******** due to spam activity. Spam was
seen coming from this account, and possibly other scripts running in
it. For help resolving the issue, see http://x.co/spamclean. Once the
compromise has been cleaned, please contact customer support to remove
the block.

Post Data not showing in DLR url

Hi im still trying to understand why i didnt receive anything from the sms API, i just write some code for saving the data inside the db and put a view for the users for see the error, but i got some problems , i see the error in logo but not in DLR url

im not sure i can post it something about API, in case im sorry.

thats’ my code:

DeliverReport Controller

<?php

namespace AppHttpControllers;

use AppDeliveryReport;
use IlluminateHttpRequest;

class DeliveryReportController extends Controller
{
    public function index() {
        $delivery_reports = DeliveryReport::all();
        return view('reports.index', compact('delivery_reports'));
    }

    public function store(Request $request){
        $data = $request->all();
        try {
            $report = [];
            if(!empty($data['custom'])) {
                $report['contact_id'] = $data['contact_id'] ?? "";
                $report['msg'] = $data['msg'] ?? "";
                $report['contact_no'] = $data['contact_no'] ?? "";
            }
            $report['message_id'] = $data['msgId'];
            $report['status'] = $data['event'];
            $report['message'] = $data['errorMessage'] ?? "";
            $report['error_code'] = $data['errorCode'] ?? "";
            DeliveryReport::create($report);
        } catch (Exception $e) {
            info('something went wrong in webhook');
            info($data);
            info($e->getMessage());
        }
    }
}

My Commontrait

<?php
namespace AppHttpTraits;

use AppSmsHistory;
use SMSGateClient;
use SMSGateSMSRequest;
use CarbonCarbon;
use DB;

trait CommonServices {
    public function sms_gate_request($number, $msg, $contact_id){
        $gate = new Client(env('SMS_GATE_SUBMIT_URL'));
        $sms = new SMSRequest;
        $sms->setType(Client::TYPE_TEXT)
            ->setAuthUsername(env('SMS_GATE_USERNAME'))
            ->setAuthPassword(env('SMS_GATE_PASSWORD'))
            ->setSender(env('SMS_GATE_SENDER'))
            ->setReceiver($number)
            ->setText($msg)
            ->setCustom(['contact_id' => $contact_id, 'msg' => $msg, 'contact_number' => $number])
            ->setDlrUrl(route('sms.delivery.store'))
            ->setDlrMask(Client::DLR_MASK_STANDARD);
        try {
            $gate->send($sms);
            SmsHistory::create([
                'phone_number' => $number,
                'message' => $msg,
                'contact_id' => $contact_id
            ]);
        } catch (Exception $exc) {
            info("Error sending SMS with code: " . $exc->getCode() . " and message: " . $exc->getMessage());
            return false;
        }

        return true;
    }


    public function checkMessageCooldown($phone_number, $message) {
        $days = env('DUPLICATE_SMS_COOLDOWN_DAYS');
        $last_sent = Carbon::now()->subDays($days)->toDateTimeString();

        $sent_before = DB::table('sms_histories')
            ->where('phone_number', $phone_number)
            ->where('message', $message)
            ->where('created_at', '>', $last_sent)
            ->exists();

        
        return $sent_before;
    }
}

my view

@extends('layouts.app')

@section('content')
    <head>
        <meta name="_token" content="{{ csrf_token() }}">
        <title>Kontaktliste</title>
        <link rel="stylesheet" href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" ></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-md-6">
                            <h3>Delivery Reports</h3>
                        </div>
                    </div>
                </div>

                <div class="panel-body">
                    <table id="reports-table" class="table table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>Message ID</th>
                            <th>Contact</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Reason (if any error)</th>
                        </tr>
                        </thead>
                        <tbody>
                        @foreach($delivery_reports as $report)
                            <tr>
                                <td>{{ $report->message_id }}</td>
                                <td>{{ $report->contact_id }}</td>
                                <td>{{ $report->message }}</td>
                                <td>{{ $report->status }}</td>
                                <td>{{ $report->error_message }}</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <script src="//cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js" defer></script>
    <script type="text/javascript">
        $(function () {
            $('#reports-table').DataTable();
        });
    </script>
    <script type="text/javascript">
        $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
    </script>
    </body>

@endsection


my route:
Route::get(‘/delivery_reports/store’,’DeliveryReportController@store’)->name(‘sms.delivery.store’);

if i go to the page (url sms.delivery.store)
i got a blank page, and obviously no data are saved in Db neither in view

Other than the opcache what can require php-fpm to be restarted to see changes?

I have opcache setup as follows:

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=0

When deploying changes, I find that I still need to restart php-fpm to see them.

What other settings should I be investigating?

Can’t send multiple values from HTML form

I’m trying to create a page where data is being displayed from database where data was inserted by other page. My data is displayed and i made checkboxes for it to select and a button to delete them. i can select them and when i press delete i made echo when it says that record deleted. Cant figure out why it doesnt actually delete from database.
My index:



<?php
session_start();
    require_once 'connection.php';
    $sql = "SELECT * FROM test";                       
    $all_product = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
    <div class="productList">
        <div class="title">
            <h1>Product List</h1>
        </div>
            <div class="button-container">
            <a href="add-product.html">
                <input type="button" class="addButton" value="ADD">
            </a>
                <input type="submit" form="list-check-box" name="delete" id="#delete-product-btn"  value="MASS DELETE" method="post">
            </div>
    </div>
    <hr class="divLine">
    <div class="show-list">
    <?php
    while($row = mysqli_fetch_assoc($all_product)){
?>
        <form class="grid-item" id="list-check-box" action="submit-copy.php" method="post">
            <div class="list" >
            <p class="sku">
                <input type="checkbox" id=".delete-checkbox" class="delete_checkbox" name="delete-product-btn[]" value="<?php $row['id'];?>">
            <?php echo $row["sku"];?></p>
            <p class="name"><?php echo $row["name"];?></p>
            <p class="price"><?php echo $row["price"];?></p>
            </div>
            <div class="size">
            <p class="size"><?php echo $row["size"];?></p>
            </div>
            <div class="weight">
            <p class="weight"><?php echo $row["weight"];?></p>
            </div>
            <div class="furniture">
            <p class="height"><?php echo $row["height"];?></p>
            <p class="width"><?php echo $row["width"];?></p>
            <p class="length"><?php echo $row["length"];?></p>
            </div>
    </form>     
<?php
    }
?>
    </div>
    <div class="footer">
        <hr class="divLine">
        <h4>Scandiweb Test assignment</h4>
    </div> 
</body>
<?php
    include_once 'submit.php';
?>
</html>


I tried OOP method to delete multiple selections from database using checkbox and a button. Can’t figure out why nothing happens. It shows that record has been deleted but no action has been applied to database. My PHP:

<?php 
    session_start();
    $id = $_POST["id"];
    $host = "localhost";
    $dbname = "productData";
    $username = "root";
    $password = "root";
    $conn = mysqli_connect($host, $username, $password, $dbname);   
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM test WHERE id IN($id)";
if(isset($_POST['delete'])){
    $all_id = $_POST['delete-product-btn'];   
  echo "Record deleted successfully";
} else {
  echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>