curl can’t fill password input with autocomplete=off tag

I’m trying to login in to a site with curl, the password input inside the form has the autofill=”off” tag and curl can’t fill in the password.

<input autocomplete="on" name="password" type="password">

$data = array(
        'username' => 'user',
        'password' => 'pw'
));


function post($url, $data, $ch)
{
    curl_setopt ($ch, CURLOPT_URL,$url); 
    curl_setopt ($ch, CURLOPT_POST, 1); 
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $result= curl_exec($ch);
    return $result;
}
post();

I can’t figure out how to make this work. I would appreciate help.

Using mysql prepared statement to insert multiple rows from XML file

I am trying to parse through an XML file from an nmap scan to then save some details from that file to a mysql database. I am able to use foreach loops to display the required information (screenshot supplied) but the prepared statement will only insert the port information for the first port shown. I have looked at previous questions (namely 19271169) without success as this seems to use an array for the data. Any assistance or pointers on how I can save ALL the port information would be greatly appreciated.

Copy of the code:

foreach ($file->host as $host) {


    $ip = $host->address['addr'];
    echo $ip . "<br>";
    @$mac = $host->address[1]['addr'] ? : $mac = "Unknown";
    echo $mac . "<br>";
    $hostName = $host->hostnames->hostname['name'] ? : $hostName = "Unknown";
    echo $hostName . "<br><br>";

    foreach ($host->ports->port as $portid) {

        $port = $portid['portid'];
        $state = $portid->state['state'];
        $service = $portid->service['name'];



        echo "Port Info: " . $port . " " . $state . " " . $service . "<br>";

        $stmt = $conn->prepare("CALL insertPortInfo(?,?,?,?,?)");
        $stmt->bind_param("sssss", $ip, $port, $state, $service, $timestamp);
        $stmt->execute();

    }
    $stmt->close();


    echo "<br>";

}

Output display

Why I am getting Notice: Undefined index: CIRReportData JSON PHP

  <?php
  $response = '{
"CCRResponse": {
    "Status": "1",
    "CIRReportDataLst": [
        {
            "CIRReportData": {
                "IDAndContactInfo": {
                    "PersonalInfo": {
                        "Name": {
                            "FullName": "URMILA GUPTA ",
                            "FirstName": "URMILA ",
                            "LastName": "GUPTA "
                        },
                        " AliasName": {},
                        "DateOfBirth": "1951-11-05"
                    }
                }
            }
        }
    ]
}
    }';
   $r1 = json_encode(json_decode($response), JSON_PRETTY_PRINT);
  $obj = json_decode($response, true);
     foreach ($obj["CCRResponse"]["CIRReportDataLst"] as $key) {
     echo $fullname = $key["CIRReportData"]["IDAndContactInfo"]["PersonalInfo"]["Name"] 
   ["FullName"];
        }?>

Can any help me why I am getting Notice: Undefined index: CIRReportData error?
I am able to get a response from my code but still getting errors.
I want
Kindly help me.

How to generate (DOM) PDF in WordPress post editing screen?

Quite new to (WordPress) PHP and trying to generate a custom post invoice via an extra metabox and with the help of the Dompdf library. I found a fix for the front end, but now I’m trying to convert WordPress admin custom post editing screen and here I’m getting stuck.

I’ve found a question on here that basically describes the same question and answer – but for the frontend.
[https://stackoverflow.com/questions/38723772/how-to-use-dompdf-with-wordpress]

My question is: would the same approach – suggested by Matteo Enna – work for the custom post type editing screen in wp admin?

Thanks all, have a great day.

I’ve found a question on here that basically describes the same question and answer – but for the frontend.
[https://stackoverflow.com/questions/38723772/how-to-use-dompdf-with-wordpress]

ImageIntervention & Laravel 9: file_put_contents ERROR Failed to open stream: No such file or directory

I’m using Laravel 9 and Image Intervetion to resize uploaded images:

public static function resize($file, $fileName)
    {
        $path = self::route();
        foreach (self::size() as $key => $value) {
            $resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
            Image::make($file->getRealPath())
                ->resize($value[0], $value[1], function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->save(storage_path($resizePath));
            $urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
        }
        self::$urlResizeImage = $urlResizeImage;
    }

But the line ->save(storage_path($resizePath)); returns this error:

Can’t write image data to path

So in the Image Facade of Intervention, there’s a @file_put_contents:

public function save($path = null, $quality = null, $format = null)
    {
        $path = is_null($path) ? $this->basePath() : $path;
        // dd($path);

        if (is_null($path)) {
            throw new NotWritableException(
                "Can't write to undefined path."
            );
        }

        if ($format === null) {
            $format = pathinfo($path, PATHINFO_EXTENSION);
        }

        $data = $this->encode($format, $quality);
        $saved = @file_put_contents($path, $data);

        if ($saved === false) {
            throw new NotWritableException(
                "Can't write image data to path ({$path})"
            );
        }

        // set new file info
        $this->setFileInfoFromPath($path);

        return $this;
    }

And I tried removing @ from @file_put_contents to see what’s going wrong here, but then I got this:

file_put_contents(C:xampphtdocsprojectstorageupload/1401/11/images/questions/107200x200_1671289517402.jpg): Failed to open stream: No such file or directory

So it basically says that it can not find the $path and when I uncomment dd($path), this is the output:

C:xampphtdocsprojectstorageupload/1401/11/images/questions/108200x200_1671289517402.jpg

So what’s going wrong here?

How can I properly save the resized images into this directory?

Please I beg you to help me with this because it’s been a week that I’m struggling with this error and got headache!


UPDATE #1:

Here is the route():

public static function route()
    {
        return "upload/" . jdate()->format('Y') . "/" . jdate()->format('m') . "/" . self::$typeFile . "/" . strtolower(self::$catType)."s" . "/" . self::$objId;
    }

And I changed it to this:

public static function route()
    {
        return "upload".DIRECTORY_SEPARATOR.jdate()->format('Y').DIRECTORY_SEPARATOR.jdate()->format('m').DIRECTORY_SEPARATOR.self::$typeFile.DIRECTORY_SEPARATOR.strtolower(self::$catType)."s".DIRECTORY_SEPARATOR.self::$objId;
    }

But still the same error occurs 🙁

update title in laravel

public function updateMovie(Request $request, $id)
{
    $request->title;
    $movie = DB::connection('mysql2')->select('UPDATE cb_video SET title='.$request->title.' WHERE videoid=' . $id);
    return response()->json(['status' => 'success', 'data' => $movie]);
}

I am trying to update title in db but its throwing me error of

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 ‘WHERE
videoid=1449’ at line 1 (SQL: UPDATE cb_video SET title= WHERE
videoid=1449)

what can I do?

file_get_contents() has suddenly stopped working [closed]

I’m using simple_html_dom and when I get to the file_get_contents line, I get a null response. The URL is correct and this was working yesterday but not today. the code is as follows:

$sym = $symbol;       
$yahooURL="https://finance.yahoo.com/quote/$sym/history?p=$sym";
//get stock name
$data = file_get_contents($yahooURL);
//at this stage $data is returning empty
$title = preg_match('/<title[^>]*>(.*?)</title>/ims', $data, $matches) ? $matches[1] : null; 
$title = preg_replace('/[[a-zA-Z0-9. ]* | /','',$title);
$title = preg_replace('/ Stock - Yahoo Finance/','',$title);
$name = $title;
 
//get price data - use simple_html_dom.php 
$body=file_get_html($yahooURL);
if (!empty($body)) {
    $tables = $body->find('table');
 
    $dom = new DOMDocument();
    $elements[] = null;
    $dom->loadHtml($tables[0]); 
    $x = new DOMXpath($dom);
 ...

allow_url_fopen is On

Any suggestions?

I’ve checked the URL is correct. I’ve checked the $data file which comes out as blank. The $sym is correct each time.I can’t think of anything else to try.

Guzzle send request : error 7 Failed to connect to “URL : connection refused

I’m using Guzzle within my app to make a request to /connect/token/ to get a token but I got this error :

cURL error 7: Failed to connect to <url> : Connection refused

there is my code :

           $this->client = new Client([
            'base_uri' => $this->settings['apiUrl']
        ]);
        $headers = [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ];
        $options = [
            'form_params' => [
                'grant_type' => 'client_credentials',
                'client_id' => 'myclientId',
                'client_secret' => 'myclientsecret',
                'scope' => 'my.api.website'
            ]];

        try {
            $response = $this->client->request('POST', 'connect/token', $options);
            var_dump($response->getStatusCode());
            var_dump($response->getBody());
        } catch (RequestException $e) {
            var_dump(Message::toString($e->getRequest()));
            if ($e->hasResponse()) {
                var_dump(Message::toString($e->getResponse()));
            }
        }

There is the response of the catch :

"POST /connect/token HTTP/1.1
Content-Length: 166
User-Agent: GuzzleHttp/6.5.5 curl/7.74.0 PHP/7.4.32
Content-Type: application/x-www-form-urlencoded
Host: MyBaseUrl

grant_type=client_credentials&client_id=rMyClientId&client_secret=MyClientSecret&scope=my.api.website"

I got this from my working postman request, I get the code with the “code” tab on postman

Someone have an idea about this error ? thanks

Yii2 backticks cause error in activerecord query for JSON field

The following SQL query works fine:

mysql> SELECT `id`, `created`, `type`, `saved`->>"$.total" AS `total` FROM `invoices` LIMIT 20;

The saved field is in JSON datatype.
However, when I try to use activerecord query for Gridview widget’s search model:

$query = Invoices::find()->select(['id','created','type','`saved`->>"$.total" AS total']);

the generated SQL statement is going to be faulty due to adding backticks surrounding the JSON key total

SELECT `id`, `created`, `type`, `saved`->>"$.`total"` AS `total` FROM `invoices` LIMIT 20

I have tried several formats for saved fields like:

$query = Invoices::find()->select(['id','created','type','saved->>"$.total" AS total']);
//
mysql> SELECT `id`, `created`, `type`, `saved->>"$`.`total"` AS `total` FROM `invoices` LIMIT 20 
// Unknown column error

 $query = Invoices::find()->select(['id','created','type','`saved`->>`"$.total`" AS total']);

mysql> SELECT `id`, `created`, `type`, `saved`->>`"$.total`" AS `total` FROM `invoices` LIMIT 20
//Syntax error or access violation

I could not able to manage how to let activerecord query to deliver correct SQL statement?!

How to remove lcoation icon from browser jquery

I am working on jquery,Right now i am getting user location after click on “button” but if user select “block” option then page is redirecting but but but “block location icon” not removing until i refresh page manually, in other words i want whenever i click/select “block” option then page should redirect and “location icon should remove from browser as well”,Here is my current code

 $(".in").click(function () {
            const options = {
                      enableHighAccuracy: true,
                      timeout: 5000,
                      maximumAge: 0
                    };

                    function success(pos) {
                      const crd = pos.coords;
                      var lats = crd.latitude;
                      var longs = crd.longitude;
                     $.ajax({
                            type: "POST",
                            url: "insert.php",
                            data: {
                                lats :lats,
                                longs :longs,
                            },
                            success: function (data) {
                                //further code
                            }
                        });
                    }

                    function error(err) {
                        var pathname = window.location.href;
                        alert('Please refresh page and select allow to continue for location');
                        window.location = pathname;
                     }
            navigator.geolocation.getCurrentPosition(success, error, options);
           });

Using guzzle to post to Facebook Conversions API [duplicate]

I am trying to send events to the Facebook conversion api. I have it working OK using cURL but would rather use guzzle. However, when i try to do the same with guzzle I get an error in the response.

Can anyone assist with getting this to work with guzzle?

Here is the event data

$data = array(
            "data" => array(
                "test_event_code" => "TEST22801",
                "event_name" => $eventName,
                "event_time" => $this->time,
                "action_source" => $this->actionSource,
                "event_source_url" => $this->eventUrl,
                "event_id" => $eventID,
                "user_data" => array(
                    "em" => $email,
                    "ph" => $phone,
                    "fn" => $firstName,
                    "ln" => $surname,
                    "client_ip_address" => $this->ip,
                    "client_user_agent" => $this->browser,
                    "fbp" => $this->fbp,
                    "fbc" => $this->fbc,
                ),
            ),
            "access_token" => {accessToken},
        );

        $body = json_encode($data);

This cURL request works:

        $ch = curl_init('https://graph.facebook.com/v15.0/{Pixel}/events');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($body))
        );
        $response = curl_exec($ch);

But this guzzle request doesn’t:

$client = new GuzzleHttpClient([
            'timeout' => 1.5,
        ]);

        // this doesn't work with guzzle
        $client->request('post', 'https://graph.facebook.com/v15.0/{Pixel}/events', [
            'body' => $body,
            'headers' => [
                'Content-Type' => 'application/json',
                'Content-Length' => strlen($body)
            ]

        ]);

and returns this error in the response:

{"error":{"message":"(#100) param data must be an array.","type":"OAuthException","code":100,"fbtrace_id":"A79KkZQwrNIUK}}

Search and summation of array elements [duplicate]

There is an array

`Array (
 [0] => Array (
     [item] => Array (
           [id] => 55 
           [count] => 4 
           )
     )
 [1] => Array (
     [item] => Array (
           [id] => 15 
           [count] => 1 
           )
     )
 [2] => Array (
     [item] => Array (
           [id] => 55 
           [count] => 12 
           )
     )
 [3] => Array (
     [item] => Array (
           [id] => 15 
           [count] => 6 
           )
     )
)`

You need to iterate over the array in php. Find duplicates by id and add the count column in them

For example, you need to make it work

`Array (
 [0] => Array (
     [item] => Array (
           [id] => 55 
           [count] => 16 
           )
     )
 [1] => Array (
     [item] => Array (
           [id] => 15 
           [count] => 7 
           )
     )
)`

I can’t figure out how to do it. I hope for the help of experts!

Symfony couldn’t autowire Response service into controller method

Trying to inject SymfonyComponentHttpFoundationResponse into controller method

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpKernelAttributeAsController;
use SymfonyComponentRoutingAnnotationRoute;

#[AsController]
class TestController extends AbstractController
{
    #[Route(path: 'test', name: 'test', methods: ['GET'])]
    public function test(Request $request, Response $response) : Response
    {
        return $response->setContent("Hello!");
    }
}

But get an error

Could not resolve argument $response of &quot;AppControllerTestController::test()&quot;, maybe you forgot
        to register the controller as a service or missed tagging it with the controller.service_arguments;?
        (500 Internal Server Error)

Debug php bin/console debug:autowiring --all shows, that container have Response

...
 Request represents an HTTP request.
 SymfonyComponentHttpFoundationRequest

 Response represents an HTTP response.
 SymfonyComponentHttpFoundationResponse
...

Why request injected, but Response not?