When using DOMPDF to download pdf, page shown blank

When download DOMPDF using jquery ajax in WordPress php.The pdf downloaded but page its blank.

below code file is generatepdf.php

generatepdf file

test.php

Generate PDF


    $(document).ready(function() {
        $('#generatePdfButton').click(function() {
            // Make an AJAX request to generate.php
            $.ajax({
                url: 'generatepdf.php',
                type: 'GET',
                success: function(response) {
                    // Handle success
                    var blob = new Blob([response], { type: 'application/pdf' });
                    var url = window.URL.createObjectURL(blob);
                    var link = document.createElement('a');
                    link.href = url;
                    link.download = 'test.pdf';
                    link.click();
                    window.URL.revokeObjectURL(url);
                },
                error: function(xhr, status, error) {
                    console.error('Failed to generate PDF:', error);
                    // Optionally, display an error message to the user
                }
            });
        });
    });



Generate PDF

I want to render html properly when call jquery ajax to download pdf.

File is not downloading after redirecting to payment succes page

`I have integrate a payment gateway. I pass the project id in returning url(see below)
“return_url” => ‘http://127.0.0.1:8000/success/?order_id={order_id}&order_token={order_token}&project_id=’ . $request->input(‘project_id’)

I am trying to download the file on that id in the database. but the file is not downloading.
`

   public function Success(Request $request)
     {
        $url = $request->fullUrl();
        $parsedUrl = parse_url($url);
        $query = $parsedUrl['query'] ?? ''
        parse_str($query, $queryParams); 
        
        $project_id = $queryParams['project_id'] ?? null;
        
        $project = Project::find($project_id);
        
        if (!$project) {
            return back()->with('error', 'Project not found');
        }
        
            $filePath = $project->file;
            $filelocation = public_path("upload/files/$filePath");
          
            $response = response()->download($filelocation);

              } 

             

I tried every possible way. tried to dd($filelocation) the location is ok.

How to get the content off an JS variable to an input

Im having some problems with getting my content from an JS variable to transport it to an span html,in this variables are the name of the file and the size of the file,also i want it to be in a html tag cause whit that i can send it to php and store it in a database,here is the code:

<?php

    if(isset($_POST['submit_enviar_dados'])){    
    $flag=false;
    $flag_referencia=false;
    $material=$_POST['material'];
    $layers=$_POST['layers'];
    $camadas=$_POST['camadas'];
    $quantidade=$_POST['quantidade'];
    $dimensao_x=$_POST['dimensao_x'];
    $dimensao_y=$_POST['dimensao_y'];
    $cor=$_POST['cor'];
    $superficie=$_POST['superficie'];
    $slikscreen=$_POST['slikscreen'];
    $nome_produto=$_POST['nome_produto'];
    $tamanho=$_POST['tamanho'];
    

    
    /* Existiu um erro */
    if($flag==true){
    
    }else{
     $inserir="INSERT INTO produto_pcb                  (material,layers,camadas,quantidade,dimensao_x,dimensao_y,cor,superficie,slikscreen,nome_produto,tamanho) VALUES ('".$material."','".$layers."','".$camadas."','".$quantidade."','".$dimensao_x."','".$dimensao_y."','".$cor."','".$superficie."','".$slikscreen."','".$nome_produto."','".$tamanho."')";
        
        $result=mysqli_query($ligax,$inserir);
    }
    if($result==1){

?>
<script>
alert("Dados inseridos com sucesso.");
</script>
<?php } else {
?>
<script>
alert("Dados não inseridos!");
</script>
<?php
}
    
}
?>
<div class="tabela">
<div class="wrapper">
  <form action="#" enctype="multipart/form-data" method="post" id="file_form"  >
    <input type="file" class="file-input" name="fileToUpload" id="fileToUpload" accept=".zip"hidden>
    <span class="material-symbols-rounded">upload</span>
    <p>Add gerber file</p>
  </form>


<div class="file-info" style="display: none;">
<div class="let"><form action="" method="POST">
  <p>Nome do ficheiro: <span name="nome_produto" class="file-name" id="nome_produto" disabled></span> (<span name="tamanho" class="file-size" id="tamanho" ></span> KB)</p>
  
  </div> 
</div>
                <p><input required type="submit" name="submit_enviar_dados" value="Registar"></p>

</form>

<script>
const form = document.querySelector("form");
const fileInput = form.querySelector(".file-input");
const progressBar = document.querySelector(".progressbar");
const counter = document.querySelector(".counter");
const fileInfo = document.querySelector(".file-info");
const fileNameElement = document.querySelector(".file-name");
const fileSizeElement = document.querySelector(".file-size");
const wrapper = document.querySelector(".wrapper");
var nome_produto = document.getElementById("nome_produto");
var tamanho = document.getElementById("tamanho");


// Function to handle file input change
const handleFileInputChange = (file) => {
  const fileName = file.name;
  const fileSize = Math.round(file.size / 1024); // Convert bytes to KB

  // Display file info
  fileNameElement.textContent = fileName;
  fileSizeElement.textContent = fileSize;
    
    nome_produto.textContent = fileName;
    tamanho.textContent = fileSize;
</script>

I tried already to pick with the php the name and size when the form is called but dind´t work.

How to deep populate, eg turn JSON into entity?

I have the following (extremly simplified) example entity:

class Reseller {
    private ?Uuid $id;
    private string $name;
    private ContactInfo $contactInfo;
}
class ContactInfo {
    private string $defaultEmail;
}

I have JSON, I want to serialize into an existing $reseller:

{"name":"Changed name","contactInfo":{"defaultEmail":"[email protected]"}}

The documentation tells this:

When the AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE option is set to true, existing children of the root OBJECT_TO_POPULATE are updated from the normalized data, instead of the denormalizer re-creating them. Note that DEEP_OBJECT_TO_POPULATE only works for single child objects, but not for arrays of objects. Those will still be replaced when present in the normalized data.

So I’ve made this my serializer:

return $serializer->deserialize(
    $data, // this is the JSON
    Reseller::class,
    'json',
    [
        AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE => true,
        AbstractNormalizer::OBJECT_TO_POPULATE => $reseller,
        AbstractNormalizer::GROUPS => $groups,
    ]
);

However, this leads to a

AppEntityReseller::setContactInfo(): Argument #1 ($contactInfo) must be of type AppEntityContactInfo, array given, called in […]vendor/symfony/property-access/PropertyAccessor.php on line 509

What am I missing here? I’ve tried various locations and combinations to no avail. And Googling this just give endless examples how to serialize simple objects, without children.
The rest of my serializer config is pretty much the documentations version + a circular-reference-handler

Why the Xdebug function xdebug_get_code_coverage() return detail coverage information only once?

As the Xdebug documents, when set xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE | XDEBUG_CC_BRANCH_CHECK); . xdebug_get_code_coverage() will return value for each line whether -1,1,-2,and detail branch information. But it only return when the first request after the Apache server started.

Here is my test code:

<?php
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE|XDEBUG_CC_BRANCH_CHECK);

function bye(){
    echo "Bye Worldn";
}
function hello(){
    echo "Hello Worldn";
}
hello();

var_dump(xdebug_get_code_coverage());
?>

After the first request, the result is:

Hello World
array(1) {
  ["/var/www/html/index.php"]=>
  array(2) {
    ["lines"]=>
    array(6) {
      [5]=>
      int(-1)
      [6]=>
      int(-1)
      [8]=>
      int(1)
      [9]=>
      int(1)
      [10]=>
      int(1)
      [12]=>
      int(1)
    }
    ["functions"]=>
    array(2) {
      ["hello"]=>
      array(2) {
        ["branches"]=>
        array(1) {
          [0]=>
          array(7) {
            ["op_start"]=>
            int(0)
            ["op_end"]=>
            int(3)
            ["line_start"]=>
            int(8)
            ["line_end"]=>
            int(9)
            ["hit"]=>
            int(1)
            ["out"]=>
            array(1) {
              [0]=>
              int(2147483645)
            }
            ["out_hit"]=>
            array(1) {
              [0]=>
              int(0)
            }
          }
        }
        ["paths"]=>
        array(1) {
          [0]=>
          array(2) {
            ["path"]=>
            array(1) {
              [0]=>
              int(0)
            }
            ["hit"]=>
            int(1)
          }
        }
      }
      ["bye"]=>
      array(2) {
        ["branches"]=>
        array(1) {
          [0]=>
          array(7) {
            ["op_start"]=>
            int(0)
            ["op_end"]=>
            int(3)
            ["line_start"]=>
            int(5)
            ["line_end"]=>
            int(6)
            ["hit"]=>
            int(0)
            ["out"]=>
            array(1) {
              [0]=>
              int(2147483645)
            }
            ["out_hit"]=>
            array(1) {
              [0]=>
              int(0)
            }
          }
        }
        ["paths"]=>
        array(1) {
          [0]=>
          array(2) {
            ["path"]=>
            array(1) {
              [0]=>
              int(0)
            }
            ["hit"]=>
            int(0)
          }
        }
      }
    }
  }
}

But when do the second request and after requests, the result become:

Hello World
array(1) {
  ["/var/www/html/index.php"]=>
  array(2) {
    ["lines"]=>
    array(4) {
      [8]=>
      int(1)
      [9]=>
      int(1)
      [10]=>
      int(1)
      [12]=>
      int(1)
    }
    ["functions"]=>
    array(0) {
    }
  }
}

I wonder why the second request and after requests return not as the first request.

php: why form doesnt work when it’s in an include? [duplicate]

I don’t understand why any of my form doesn’t work if I appeal them in an include form

for example:

public function afficher_tache_veterinaire($id,$id_secteur){
        $emp=$this -> tab_employe();
        $e=$emp[$id];
        echo 'Bonjour employé numéro '.$id.": ".$e["fonction"]." ".$e["prenom"]." ".$e["nom"];
        echo ' vous etes affecté aux secteurs ';
        foreach($e["secteur"] as $sec){
            echo $sec["nom_secteur"].", ";
        }
        
        echo 'Que voulez-vous faire ?';
        ?>
                
        <!-- Bouton pour créer un médicament -->
        <form action="" method="post">
        <button type="submit" name="c_medicament">Créer un médicament</button>
        </form>
        <?php
        if (isset($_POST['c_medicament'])) {
            include 'c_medicament.php';
        }
    }


c_medicament.php :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inscription</title>
</head>
<body>
<h1> création medicament</h1>
    <form method="post">
        <input type="text" id="nom" name="nom" placeholder="nom" /><br/><br/>
        <button type="submit" name="bouton" id="bouton">VALIDER </button>
    </form>

<?php 

if(isset($_POST["bouton"])){
    
    if (isset($_POST['nom'])) {
        $nom=$_POST['nom'];
        
        include_once "DB.php";
        global $bdd;
        $medicament = new medicament();
        $medicament -> creer_medicament($nom);  
        
    }else{
        ?> <script> window.alert("merci de rentrer toutes les valeurs ")</script> <?php
    }
    
}

?>

and creer_medicament($nom) is a basic INSERT INTO sql function.

my problem is that the function c_medicament work by itself but not when I include it in an other form,
it instantly disapear when i click on it.
I’m pretty confident that it’s something about session or a thing like that but I dont know what to do

How to Track Email Status (Delivered, Opened, Bounced) When Sending Emails Using Laravel

I’m currently developing an email campaign portal using Laravel, and I’m looking for ways to track the status of emails sent through my platform. I’ve successfully implemented pixel tracking for email opens by embedding a single-pixel image in the email body. However, I’m now exploring options to track other email statuses, such as delivery, clicks, and bounces.

Is there a way to achieve this natively within Laravel, without relying on third-party email services like SendGrid or Mailgun? I’m interested in learning about techniques or best practices for tracking these email statuses efficiently within my Laravel application.

I am new to Laravel development so any insights or suggestions would be greatly appreciated!

My Code Snippet for email open tracking

public function generateTrackingId(int $id): string
    {
        $randomString = Str::random();
        $time = time();
        $trackingId = Hash::make($id . $randomString . $time);

        return str_replace(['$', '/', '.'], '', $trackingId);
    }

public function generateUrl(string $trackingId): string
    {
        $baseUrl = URL::to('/');
        $trackingUrl = $baseUrl . '/track/' . $trackingId;
        return $trackingUrl;
    }

How I get to know there is data exist with this make,model,year range or not

i am taking make,model and fromyear and toyear from user i want to restrict if data with give fromyear and toyear range exsist in db

Like there is record with make=toyota ,model=camry ,fromyear=2015 ,toyear=2020 in db and then user enter then ranges like

2016-2017 or 2016-2018 or 2019 to 2022 or 2013 to 2016 so its restrict

and there is no fromyear and toyear is falling in range then its fine

DB columns name are make,model,fromyear,toyear

$has_range = PartsList::where('make', $request->make)
                        ->where('model', $request->model)
                        ->where(function ($query) use ($request) 
                                {
                                    $query->whereBetween('fromyear', [$request->fromyear, $request->toyear])
                                    ->orWhereBetween('toyear', [$request->fromyear, $request->toyear]);
                })
            ->exists();
if($has_range)
{
    $msg = 'year range already exists for this make and model';
}

Deleting WordPress posts and media file based on author in MYSQL database

I would like to delete some of the posts in WordPress between a period based on the author via MYSQL database. I have difficulty identifying the WordPress tables and their relationships to perform the following delete operation. The below query is just an example(table and column names could be wrong). Appreciate your help.

Delete from wp-posts where post-author = 'name' AND published-date BETWEEN 01/01/2024 AND 20/03/2024

How can I determine the cause of a failed webservice connection in PHP? [duplicate]

I have a PHP code that allows me to connect to a webservice and retrieve the response.

If I run this code locally on my computer without any particular configuration, it works. But as soon as I run it on my web server, I get this error:

The PHP version currently running is :

PHP 7.1.5 (cli) (built: May 9 2017 19:48:36) ( NTS MSVC14 (Visual C++ 2015) x64 ) Copyright (c) 1997-2017 The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies 

SOAP Fault: WSDL, SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl' : failed to load external entity "https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl"
  • I had an old version of PHP in 5.3.9, I modified to run one in 7.1.5, same error.
  • I can connect to the webservice from Postman with my credentials.
  • I tried to disable SSL verification in my code, same error.
  • I can open the url from a server browser.
  • The firewall doesn’t block anything in particular.
  • I’ve managed to connect without error using nuSOAP, but I can’t retrieve the response returned by the webservice.

I’ve already done what is indicated in this answer: SOAP PHP fault parsing WSDL: failed to load external entity? and the result is the same. That’s why I’m asking this question.

How can I determine the cause of the problem?
Thanks for your help,

My code:

<?php

// Specify the full path to the PHP executable
$chemin_php = "C:\php\php7.1.5\php.exe";

// Execute the command to obtain the PHP version
$version_php = shell_exec("$chemin_php -v");

// Display PHP version
echo "The PHP version currently running is : <br>";
echo $version_php;

// URL du service WSDL
$wsdlUrl = 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl';

$requestUrl = 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS';

  // the soap operation which is called
$action = 'euExpressRateBook_providerServices_ShipmentHandlingServices_Binder_createShipmentRequest';
  // the xml input of the service
  $xmlrequest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cxf="http://cxf.shipping.soap.chronopost.fr/">
  <soapenv:Header/>
  <soapenv:Body>
//rest of the code
</soapenv:Body>
</soapenv:Envelope>';

try {
    $options = array();
    $options['wrapper'] = array(
        
        'soap_version' => 'SOAP_1_1',
        'encoding' => 'UTF-8',
        'user_agent' => 'PHPSoapClient',
        
        // The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.
        'exceptions' => true,
        
        // The trace option enables tracing of request so faults can be backtraced.
        'trace' => true
    );
    
    
    $context = stream_context_create($options);
    // create the soapclient and invoke __doRequest method
    //WSDL URL is called on init
    $client = new SoapClient($wsdlUrl, $options);
    //Here we call REQUEST URL
    $output = $client->__doRequest($xmlrequest, $requestUrl, $action, 1);

    // Affichez la réponse SOAP
    echo "Réponse SOAP :<br>";
    echo htmlentities($output);
}
catch (SoapFault $fault) {
    var_dump($fault);
    echo "<h2>SOAP Fault!</h2><p>";
    echo "FaultCode: {$fault->faultcode} <br/>";
    echo "FaultString: {$fault->faultstring} <br/>";
    echo("</p/>");
}

Laravel Auth attempt, after db switch

I manually authenticate users on login, here is my full Login function

    public function Login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $email_host = explode('@', $credentials['email'])[1];
        $company = Companies::where('email_host', $email_host)->first();

        if ($company) {
            try {
                // Set up dynamic database configuration
                Config::set("database.connections.$company->email_host", [
                    'driver' => $company['db_driver'],
                    'host' => $company['db_host'],
                    'port' => $company['db_port'],
                    'database' => $company['db_name'],
                    'username' => $company['db_user'],
                    'password' => $company['db_password'],
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci',
                    'prefix' => '',
                    'strict' => true,
                    'engine' => null,
                ]);
                Config::set("database.default", $company->email_host);

                DB::purge();
                DB::reconnect();

                $user = User::where('email', $credentials['email'])->first();

                if (Auth::attempt($credentials)) {
                    $request->session()->regenerate();

                    $user = Auth::user();

                    session([
                        'username' => $user->username,
                        'company_id' => $user->company_id,
                        'warehouse' => $user->warehouse,
                        'company_database' => serialize($company),
                    ]);

                    if ($user->role == 'basic') {
                        return redirect('/users/vaccations/set-vaccation');
                    }

                    return redirect()->intended('/');
                }

            } catch (Exception $e) {
                // Error occurred while configuring the database connection
                return back()->withErrors([
                    'email' => 'Error occurred while configuring the database connection: ' . $e->getMessage(),
                ])->onlyInput('email');
            }
        } else {
            // Company not found
            return back()->withErrors([
                'email' => 'The provided email does not belong to a valid company.',
            ])->onlyInput('email');
        }
    }

the problem is in Auth::attempt(). First, i select db credentials, from master db, than i switch db, and procced to login user, but Auth seem to be using first(default, master) db. How do i fix this? In env i only have one db credentials(master), other db credentials are stored in master db as mentioned above.

.htaccess redirecting to GET variable does not working on mobile

I have the code in .htaccess:

RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{ENV:REDIRECT_STATUS} !=200 RewriteRule ^([a-z,0-9,A-Z,_-]+)/?(.*)$ $2?type=$1&%{QUERY_STRING} [NC,L,QSA]

The get variable “type” needs be redirect to regarding type.

On desktop browser it´s working normally, but it does not working on mobile. Any solution?

How to display a webservice response with nuSOAP php?

I’m using an old version of PHP, 5.3.9. To get around TLS problems, I’m using nuSOAP to connect to a webservice.

The connection is ok but the response returned by the webservice is empty and I get no error.

With a more recent version of PHP I do this:

    $client = new SoapClient($wsdlUrl, $options);
   //Here we call REQUEST URL
    $output = $client->__doRequest($xmlrequest, $requestUrl, $action, 1);

    // Affichez la réponse SOAP
    echo "Réponse SOAP :<br>";
    echo htmlentities($output);

And I get the displayed response.

With nuSOAP I do this but the response is empty:

$response = $client->send($xmlrequest, $action, '', $requestUrl);

echo "Réponse de la méthode SOAP : ";
echo htmlentities($response);

How can I get the same result?

My entire code:

<?php

// Include the NuSOAP file
require_once('nusoap-0.9.5/lib/nusoap.php');

// Define the URL of the Web service
$wsdlUrl = 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl';
$requestUrl = 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS';

// Create a NuSOAP client
$client = new nusoap_client($wsdlUrl, true);

// Check if there was an error during client creation
$err = $client->getError();
if ($err) {
    // If there was an error during client creation, display the error message
    echo "Error creating client: " . $err;
    exit();
} else {
    // If no error was detected, display "connection successful"
    echo "Connection successful";
}

// Define the SOAP action and the content of the request
$action = 'euExpressRateBook_providerServices_ShipmentHandlingServices_Binder_createShipmentRequest';
$xmlrequest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cxf="http://cxf.shipping.soap.chronopost.fr/">
<soapenv:Header/>
<soapenv:Body>
//rest of the code
</soapenv:Body>
</soapenv:Envelope>';

// Send the SOAP request
$response = $client->send($xmlrequest, $action, '', $requestUrl);

// Display the SOAP request response
echo "SOAP method response: ";
echo htmlentities($response);

Thanks for your help,

firebase cloud messaging does not play sound

I have my backend in php sending firebase cloud message and I am receiving the message to my frontend without a problem but for some reason I’m not getting the custom sound.

this is the request:

$url = "https://fcm.googleapis.com/fcm/send";

$notification = array(
'title' => $title,
'body' => $body,
'click_action' => 'https://ww.google.com/',
'icon' => 'default',
'sound' => 'path-to-sound',

);

$arrayToSend = array(
'to' => $token,
'notification' => $notification,
'priority' => 'high'
);
$json = json_encode($arrayToSend);
$headers = array(
'Content-Type: application/json',
'Authorization: key=' . $serverKey
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === FALSE) {
echo 'FCM Send Error: ' . curl_error($ch);
return 0;
}
curl_close($ch);

And this is the payload in the frontend:

{
"from": "243712765598",
"priority": "high",
"notification": {
"title": "title test",
"body": "body test",
"icon": "default",
"click_action": "https://www.google.com/"
},
"fcmMessageId": "2e674039-9920-4bcb-9f6b-da9e6e103cb9"
}

I am not getting the sound in my object (I’ve made sure the path to the sound is correct).