How to use CryptoJS to decrypt string encrypted by Laravel

I am using this function to encrypt strings with a custom key in Laravel

use IlluminateEncryptionEncrypter;

public static function aes_256_cbc($str, $key){
   $Encrypter = new Encrypter($key, 'AES-256-CBC');
   return $Encrypter->encrypt($str);
}

Then, use CryptoJS to decrypt it, I have searched and used many ways but still getting this problem:

var encrypted_json = JSON.parse(Base64.decode(encrypted));

// JSON Parsed
// {
  // iv: xxx==,
  // value: xxx+5+bUEKbwGaUHB6…f2/xxx/qaphls6ybd/xxx==,
  // mac: xxx4c3aa002712ef5d7e80226bxxx,
  // tag:
// }

var key = CryptoJS.enc.Utf8.parse(mykey); 
var iv  = CryptoJS.enc.Utf8.parse(encrypted_json.iv);  
var decrypted = CryptoJS.AES.decrypt(encrypted_json.value, key, {
    iv : iv,
    mode: CryptoJS.mode.CBC
});
let res = decrypted.toString(CryptoJS.enc.Utf8)

Got this error:
Error: Malformed UTF-8 data

This problem can be easy to solve if I encrypt string by a custom function in Laravel, but it will be better if I can get a solution with CryptoJS. Can you help me?

License key verification one server to another server using ajax in wordpress

I am trying to develop a wooCommerce extension for verifying license key one wordpress server to another wordpress server.I wrote the following code for the verification. This code is not working perfectly. Please check the following script and correction it. After form submit console.log showing the following error

admin.php:1 Access to XMLHttpRequest at ‘https://server2.net/wp-admin/admin-ajax.php’ from origin ‘https://server1.net’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

wordpress server one.This is HTML form for submitting the license key.

        <tr>
          <td width="20%"><label>License Key</label></td>
          <td width="80%"> <input type='text' name='lincesekey' value=''> </td>
        </tr>    

        <tr>
          <td width="20%"><input type="submit" name="licensekey" id="licensekey" 
             class="button button-text" value="<?php esc_html_e('Active License', 'orange-smtp');?>"> </td>
          <td width="70%">&nbsp;</td>
        </tr>
     </table>               
</form>   

 jQuery(document).ready(function($) {
    jQuery('#licenseForm').submit(function(e) {
        e.preventDefault(); // Prevent the form from submitting normally

        //var licenseKey = jQuery('#licenseKey').val();
        var formData = jQuery(this).serialize();

        // AJAX request to host server
        jQuery.ajax({
            type: 'POST',
            url: 'https://ecom.lifestyleblogs.net/wp-admin/admin-ajax.php',
            data: formData + '&action=licensekey_process_received_data', // Include action parameter
            success: function(response) {
                console.log('Data sent successfully');
                // Handle success response
            },
            error: function(xhr, status, error) {
                console.error('Error sending data:', error);
                // Handle error response
            }
        });
    });
});

wordpress server two.I wrote the following code to receive the license code from wordress server one for verify the license key.

public function licensekey_process_received_data(){

     if(isset($_GET['licenseKey'])) {
        $licenseKey = $_POST['licenseKey'];
     
        // Sanitize the license key input (optional, but recommended)
        $licenseKey = sanitize_text_field($licenseKey);
     
        global $wpdb; 
        $table_name = $wpdb->prefix . 'license_key';
        $validLicenseKeys = $wpdb->get_col("SELECT glicense_key FROM $table_name"); 
     
        if (in_array($licenseKey, $validLicenseKeys)) {
           //return true; // License key is valid
           $response = array(
                 'status' => 'success',
                 'message' => 'License key is valid.'
           );
     
        } else {
           //return false; // License key is invalid
              $response = array(
                 'status' => 'error',
                 'message' => 'License key is invalid.'
           );
        }   
        header('Content-Type: application/json');
        echo json_encode($response);
        }
  }

I was try to fix various way but i failed to resolve this issue.

Solution for Unable to locate element based on text option of select on Selenium

Please help me. I’m struggling to create auto click using PHP Selenium for select2 dropdown based on text name, instead of value option because the value is random.

HTML Code like this

<div class="input-group-prepend">
<select name="target" id="target" class="form-control select2-hidden-accessible" data-select2-id="select2-data-acctarget" tabindex="-1" aria-hidden="true">
<option value="" data-select2-id="select2-data-4-lu1l">-- Please Select --</option>
<option value="hashrandom" data-select2-id="select2-data-5-i9za">Option1</option>
</select>
<span class="select2 select2-container select2-container--default" dir="ltr" data-select2-id="select2-data-3-0a3d" style="width: 360.312px;">
<span class="selection">
<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-acctarget-container">
<span class="select2-selection__rendered" id="select2-acctarget-container" role="textbox" aria-readonly="true" title="-- Please Select --">-- Please Select --</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span>
<span class="dropdown-wrapper" aria-hidden="true"></span></span>
<button type="button" class="btn btn-link btn-sm" data-toggle="tooltip" data-placement="top" title="" data-original-title="tooltips_accountstatement/viewreport/acctarget"><i class="fa fa-question-circle"></i></button>
</div>

I already try like this using PHP

if(!$this->wait('#target','visibilityOfElementLocated',5,500)) return $this->sendError('form not found');
if($this->executeScript("$('#target').click();"));
if(!$this->click('option[text='Option1']')) return $this->sendError('select error.');

But got error

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"option[text='Option1']"}

Undefined array key ‘password’ error in Laravel Auth::attempt

I’m encountering an “Undefined array key ‘password'” error when trying to log in a user using Laravel’s Auth::attempt method. Below is the relevant section of my code:

public function register_post(Request $request) {
    $request->validate([
        'nama_user' => 'required',
        'alamat_user' => 'required',
        'email_user' => 'required|email|unique:user,email_user',
        'notelp_user' => 'required',
        'password_user' => 'required|min:6',
    ]);

    $data['nama_user'] = $request->nama_user;
    $data['alamat_user'] = $request->alamat_user;
    $data['email_user'] = $request->email_user;
    $data['notelp_user'] = $request->notelp_user;
    $data['password'] = Hash::make($request->password_user);

    User::create($data);

    $login = [
        'email_user' => $request->email_user,
        'password_user' => $request->password_user
    ];

    if (Auth::attempt($data)) {  // <-- Error occurs here
        $request->session()->regenerate();
        return redirect()->intended('/login');
    }

    return redirect()->back()->withInput($request->only('email_user'))->withErrors([
        'login_failed' => 'Email atau password salah.',
    ]);
}

Error Message:
Undefined array key “password”
Additional Details:
The error points to the line where Auth::attempt($data) is called.
I’m using Laravel’s built-in authentication methods.
The User model uses email_user as the email field and password_user as the password field.
I tried to create a user registration and login system in Laravel. The registration part works fine, and the user is created successfully. However, when I attempt to log the user in immediately after registration using the Auth::attempt method, I encounter an “Undefined array key ‘password'” error.
Here’s what I did:
Validated the request inputs.
Created a new user with the provided data, hashing the password before saving it.
Tried to log in the user using the Auth::attempt method.
My expectation was that the user would be logged in and redirected to the intended URL if the credentials were correct. Instead, I got an error pointing to the line where Auth::attempt is called.

I double-checked the array keys I used for authentication. I expected the authentication attempt to succeed because the user’s credentials should match those stored in the database.

Any guidance on why this error is occurring and how to fix it would be greatly appreciated.

i want to find the same numbers from the following multidimensional array


    <?php
    declare(strict_types=1);
    
    $multiArr = [
        [
            [12, 32, 13, 34],
            [13, 12, 23, 41],
            [15, 23, 34, 45],
        ],
        [
            [122, 32, 133, 314],
            [123, 132, 23, 141],
            [155, 23, 334, 465],
        ],
        [
            [12, 342, 135, 234],
            [713, 712, 423, 431],
            [15, 23, 34, 45],
        ],
        [
            [12, 372, 913, 334],
            [13, 162, 243, 341],
            [175, 423, 34, 435],
        ],
    ];
    
    
    
    function pre(array $y)
    {
        echo "<pre>";
        print_r($y);
        echo "</pre>";
    }
    
    
    
    function same_value($multiArr, $index)
    {
        $row_index = $index; // 0
        $commonNumbers = [];
        $a = []; // per result 
       
        $firstSubarray = $multiArr[$row_index];
        // pre($firstSubarray );
       
        foreach ($firstSubarray as $subInnerkey => $innerArray) {
    
            //                        0        12  
            foreach ($innerArray as $key => $number) {
                $isCommon = false;
                // echo $number;
    
                // checking======================================
                for($i = 0; $i < count($multiArr); $i++) {
    
                    $found = false;
                    // pre($multiArr[$i]);
                    foreach ($multiArr[$i] as $subCheckKey => $subInnerArray) {
                       
                        //    pre($subInnerArray);
                                     1
                        // echo $subInnerkey ."__".$subCheckKey."<br>";
                        if ($subInnerkey != $subCheckKey) {
                            // echo $number. "<br>";
    
                            if (in_array($number, $subInnerArray)) {
                                $found = true;
                                 $a = [$number => $subInnerArray];
                                array_push($commonNumbers, $a);
                                break;
                            }
                        }
                    }
                }
            }
        }
    
        return $commonNumbers;
    }
    
    $result = same_value($multiArr, 1);
    pre($result);
    
    ?>

This is the output

 Array
(
    [0] => Array
        (
            [23] => Array
                (
                    [0] => 15
                    [1] => 23
                    [2] => 34
                    [3] => 45
                )

        )

[1] => Array
    (
        [23] => Array
            (
                [0] => 155
                [1] => 23
                [2] => 334
                [3] => 465
            )

    )

[2] => Array
    (
        [23] => Array
            (
                [0] => 15
                [1] => 23
                [2] => 34
                [3] => 45
            )

    )

[3] => Array
    (
        [23] => Array
            (
                [0] => 13
                [1] => 12
                [2] => 23
                [3] => 41
            )

    )

[4] => Array
    (
        [23] => Array
            (
                [0] => 123
                [1] => 132
                [2] => 23
                [3] => 141
            )

    )

[5] => Array
    (
        [334] => Array
            (
                [0] => 12
                [1] => 372
                [2] => 913
                [3] => 334
            )

    )
)

can anyone tell me where I made a mistake in this code ??

firstly I select one value of the subarray skip that array selected value of the array and compare all other elements if that element repeats in any other subarrays in checking loops then it will push that array with that element into a new array

then problem appears it may skip some value which is also repeated in subarrays

I don’t know where I made a mistake can someone help me

function same_value($multiArr, $index)

this function is selected index whome have three subarray then one by one

select value and check all other siblings arrays also

function pre($a) this function just print array at the end of the result

the algorithm i mostly use here selection and sort but I only used selection part in this program

this is array inside is subarrays

[
        [12, 32, 13, 34],
        [13, 12, 23, 41],
        [15, 23, 34, 45],
]

Beanstalkd library Version 1.13+1+g91c54fc

Im using beanstalks 1.13+1+g91c54fc and i getting problem to get private storage array from this out pur ‘PheanstalkResponseArrayResponse Object
(
[name:PheanstalkResponseArrayResponse:private] => OK
[storage:ArrayObject:private] => Array
(
[name] => ‘transaction_processing’
[current-jobs-urgent] => 0
[current-jobs-ready] => 1
[current-jobs-reserved] => 0
[current-jobs-delayed] => 0
[current-jobs-buried] => 0
[total-jobs] => 1
[current-using] => 0
[current-watching] => 0
[current-waiting] => 0
[cmd-delete] => 0
[cmd-pause-tube] => 0
[pause] => 0
[pause-time-left] => 0
)
) ‘

i want to get data from [storage:ArrayObject:private] => Array

php connect to mysqlDatabse

Error creating tableYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL)’ at line 1Error inserting record : Table ‘crud_db.users’ doesn’t existError inserting record : Table ‘crud_db.users’ doesn’t exist
Fatal error: Uncaught TypeError: mysqli_num_rows(): Argument #1 ($result) must be of type mysqli_result, bool given in C:xamppXampphtdocsCrudindex.php:79 Stack trace: #0 C:xamppXampphtdocsCrudindex.php(79): mysqli_num_rows(false) #1 {main} thrown in C:xamppXampphtdocsCrudindex.php on line 79

i dont know how to fix it

Split text by in PHP scraping result

I am writing a PHP scraping program. The program works smoothly for me but I found the scraping result slightly differs from my expectation.

Here is my script

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $eng_SCCW_array["Here is my website"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $html = curl_exec($ch);

    $doc = new DOMDocument();
    @ $doc->loadHTML($html);
    $elements_content = $doc->textContent; 
    echo $elements_content."</br>"."</br>";

And here is the scraping result:
enter image description here

The problem is, some white space is missed as any ‘br’ will not be read by the script. However, this would make the data process later become very complicated. I want to split the scraping result as if the image below. But how shall I do it?

enter image description here

Child class can’t find Parent class in PHP8.3?

This is the Fatal Error message I receive after trying to instantiate an object of the Child class ‘Client’ which extends the Parent class ‘GenericObject’

Fatal error: Uncaught Error: Class “GenericObject” not found in D:AdminCMSGenericclassesClient.class.php:2
Stack trace:
#0 D:AdminCMSGenericindex.php(21): include()
#1 {main}
thrown in D:AdminCMSGenericclassesClient.class.php on line 2

This is after the script for the Generic Object that cannot be found has been dumped , in it’s entirety, on the screen.

This is part of the GenericObject class:

<?
class GenericObject
{

    protected $loaded;
    protected $modifiedFields
    protected $actionFlag;
    protected $arAmends;
    protected $extractedDataObject;
    protected $objDB;

    public function __construct(protected string $tableName, protected ?int $entityID = null, protected ?object $inputDataObject = null)
    {
        // dB connection
        $this->objDB = new dBAccess();
        // set flag & initiate appropriate method
        if(is_int($this->entityID))

& the Client class (no properties or methods defined as at the moment I just want the Parent functionality):

<?php
class Client extends GenericObject
{

}
?>

& the calling script:

<?php
// auto load any required classes
function myAutoloader($class)
{
  include __DIR__ . '/classes/' . $class . '.class.php';
}
spl_autoload_register('myAutoloader');

$objClient = new Client(entityID: 2, tableName: 'client');

In addition to using the autoloader I have also tried using hardcoded ‘include’ & ‘require’ statements – the only difference with these is the GenericObject script doesn’t get dumped to the screen, otherwise the result is the same.

Any help with this would be much appreciated as it’s stumping me.

Thanks

MySQL is rejecting connection when using WordPress in XAMPP

I was developing a website locally on WordPress without any problems until today, when I got an error from MySQL stating, “Error establishing a database connection.” Then, I checked the phpMyAdmin console, and it showed, “phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username, and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.”

I browsed similar answers here on Stack Overflow but only found answers that required typing in the correct credentials; my problem is that I haven’t tampered with any config files in PHP to get this error, and I was accessing it fine before. I only used WordPress to store data in the database, which I did not do before, but I doubt this could be an issue.

The error by WordPress SS:
WordPress Error

The error by phpMyAdmin SS:
phpMyAdmin Error

I checked other Q&As similar to this one, such as entering the correct credentials and changing the config file to 127.0.0.1, but these both did not work.

Compile Error: Declaration of SymfonyBridgeMonologHandlerConsoleHandler::handle(array $record): bool must be compatible

I am upgrading symfony 4.4 to 5.4 after run composer update then i am facing this issue. in composer.json we are using PSR-4.

ERROR: Compile Error: Declaration of SymfonyBridgeMonologHandlerConsoleHandler::handle(array $record): bool must be compatible with MonologHandlerAbstractProcessingHandler::handle(MonologLogRecord $record): bool.

Composer.json
“config”: {
“sort-packages”: true,
“allow-plugins”: {
“php-http/discovery”: false
}
},
“require” : {
“php”: “>=8.2”,
“ext-json”: ““,
“aws/aws-sdk-php-symfony”: “^2.6”,
“doctrine/persistence”: “^3.3.2”,
“exercise/htmlpurifier-bundle”: “^3.0”,
“incenteev/composer-parameter-handler”: “^2.0”,
“knpuniversity/oauth2-client-bundle”: “^2.8”,
“laminas/laminas-soap”: “^2.10”,
“lexik/jwt-authentication-bundle”: “^2.x-dev”,
“microsoft/microsoft-graph”: “^1.102”,
“myclabs/php-enum”: “^1.8”,
“phpoffice/phpspreadsheet”: “^1.29.0”,
“phpoffice/phpword”: “^1.2.0”,
“propel/propel”: “~2.0.0-beta2”,
“sensio/framework-extra-bundle”: “^6.0”,
“sentry/sentry-symfony”: “4.x-dev”,
“skyfox/propel-bundle”: “^5.1.x-dev”,
“spipu/html2pdf”: “^5.2”,
“spyrit/propel-datagrid-bundle”: “^4.0.11”,
“symfony/monolog-bundle”: “^3.x-dev”,
“symfony/swiftmailer-bundle”: “~3.0”,
“symfony/symfony”: “^5.0”,
“twig/extra-bundle”: “^3.0”,
“twig/intl-extra”: “^3.0”,
“twig/string-extra”: “^3.3”,
“twig/twig”: “^3.0”
},
“autoload”: {
“psr-4”: {
“”: “src/”
},
“classmap”: [
“app/AppKernel.php”,
“app/AppCache.php”
]
},
“scripts”: {
“post-root-package-install”: [
“SymfonyStandardComposer::hookRootPackageInstall”
],
“post-install-cmd”: [
“IncenteevParameterHandlerScriptHandler::buildParameters”
],
“post-update-cmd”: [
“IncenteevParameterHandlerScriptHandler::buildParameters”
]
},
“extra”: {
“symfony-app-dir”: “app”,
“symfony-bin-dir”: “bin”,
“symfony-var-dir”: “var”,
“symfony-web-dir”: “web”,
“symfony-assets-install”: “symlink”,
“incenteev-parameters”: {
“file”: “app/config/parameters.yml”
},
“symfony”: {
“allow-contrib”: false,
“require”: “5.4.

}
},
“require-dev”: {
“friendsofphp/php-cs-fixer”: “^3.57.1”,
“phpstan/phpstan-symfony”: “^1.0”,
“phpunit/phpunit”: “^9.0”,
“rector/rector”: “^0.12”
}

Please help me in this out it would be great help.

Thanks

run composer update

RangeException error during payload encryption with PHP JWT Framework

I’m trying to encrypt the payload using JWT Framework v2.2 as follow

$jws_payload = "sdvsd.....";
$kid = "AH1111";

$keyEncryptionAlgorithmManager = new AlgorithmManager([
    new RSAOAEP256(),
]);
$keyEncryptionAlgorithmManager = new AlgorithmManager([
    new RSAOAEP256(),
]);
$compressionMethodManager = new CompressionMethodManager([]);
$jweBuilder = new JWEBuilder(
    $keyEncryptionAlgorithmManager,
    $contentEncryptionAlgorithmManager,
    $compressionMethodManager
);

$jwk = new JWK([
    'kty' => 'RSA',
    'n' => $public_key_plain,
    "kid" => $this->kid
]);

$jwe = $jweBuilder
    ->create()              // We want to create a new JWE
    ->withPayload($jws_payload) // We set the payload
    ->withSharedProtectedHeader([
        'alg' => 'RSA-OAEP-256',        // Key Encryption Algorithm
        'enc' => 'A256GCM', // Content Encryption Algorithm
        'kid' => $kid            // We enable the compression (irrelevant as the payload is small, just for the example).
    ])
    ->addRecipient($jwk)    // We add a recipient (a shared key or public key).
    ->withAAD($aad)
    ->build(); 

but following fatal error thrown:

RangeException: Base64::decode() only expects characters in the correct base64 alphabet in ...jwt-framework-2.2.xvendorparagonieconstant_time_encodingsrcBase64.php on line 229

I found it thrown when trying to decode each 4-chars block of public key including slash character like fbf/

Why is my form only displays once in my loop

I have a loop that allows me to display my visitors’ information from a JSON variable. I want to test if a visitor is in “depart” state (i.e. if the value of “depart” in my visitors JSON variable is not null). If this value is null, I display a “checkbox” type input. Otherwise, I display a form and an icon.

However, I have a problem: when the @else is triggered, the first iteration never displays the form, although the icon appears correctly. This problem occurs both when I have a single iteration and with multiple iterations.

@for($i = 0; $i < count($vt->visiteurs); $i++)
    <div>
        <span class="text-4xl font-bold
        @if ($vt->arrivee < date('Y-m-d H:i', strtotime(date('Y-m-d H:i'). ' - 11 hours')))
            text-red-500
        @elseif($vt->depart != null)
            text-black
        @else
            text-yellow-500
        @endif">
        {{$vt->badge[$i]->numero}}
        </span>
    </div>
    
    <div class="col-span-3">
        <span class="font-bold">Visiteur :</span> {{$vt->visiteurs[$i]['name']}} {{$vt->visiteurs[$i]['firstname']}} / <span class="font-bold">Société :</span> 
        @php
            $societe = $vt->getSocieteForVisiteur($i);
        @endphp
        @if($societe)
            {{$societe->name}}
        @endif
    </div>

    <div>
        @if($vt->visiteurs[$i]['depart'] != null)
            <span class="text-red-500 font-bold">Départ</span>
        @else
            <span class="text-green-500 font-bold">Sur site</span>
        @endif
    </div>
    
    <div>
        @if($vt->visiteurs[$i]['depart'] == null)
            <input type="checkbox" class="form-check-input" name="vis[]" value="{{$i}}">
        @else
            <form action="{{ route('visite.cancelsortie') }}" method="POST" class="cancel">
                @csrf
                <input type="number" name="visite_id" value="{{ $vt->id }}" hidden>
                <input type="number" name="index" value="{{ $i }}" hidden>
                <i class="fa-solid fa-xmark text-red-500 text-xl"></i>
            </form>
        @endif
    </div>
@endfor

Why is the form not appearing on the first iteration even though the icon is showing correctly, and how can I fix this?

I tried to put a class on each of my forms, give them a different id, check the “depart” value with a dump. However nothing worked.

Fix WooCommerce Order Detail: Link to Shop Product, Not Edit

In WooCommerce, the product links in order details currently lead to the product edit page instead of the product page in the webshop. I tried adding some code to fix this and using

$product_link = $product ? get_permalink( $product->get_id() ) : '';

but it doesn’t work and it also duplicates the product title on the order details form.

Related question:
Change product url in woocommerce order detail

add_action( 'woocommerce_before_order_itemmeta', 'custom_order_item_product_link', 10, 3 );
function custom_order_item_product_link( $item_id, $item, $product ) {
    if ( ! is_a( $product, 'WC_Product' ) ) {
        return;
    }
    $product_link = $product->is_visible() ? $product->get_permalink() : '';
    if ( $product_link ) {
        printf( '<a href="%s">%s</a>', esc_url( $product_link ), esc_html( $product->get_name() ) );
    } else {
        echo esc_html( $product->get_name() );
    }
}

php mail attachment encoded

I’m facing a problem with the attachments in my php mail system.
I get all the data correctly but the attachments it’s in encoded format.

my html:

<form action="lavora-con-noi-process-form.php" method="POST" id="lavora-con-noi" enctype="multipart/form-data">
        
        <input type="file" id="pdf-upload" name="pdf_file" accept=".pdf" style="border: none;" required>
          
    </form>

and the php part:

<?php
$showThankYou = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Retrieve form data
  $recipient_email = "[email protected]"; 
  $name = htmlspecialchars($_POST["nome"]); 
  $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL); // Validate email format
  $message = htmlspecialchars($_POST["messaggio"]);


  // Check if PDF file was uploaded
  if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
    $file_name = $_FILES['pdf_file']['name'];
    $file_tmp = $_FILES['pdf_file']['tmp_name'];
    $file_type = $_FILES['pdf_file']['type'];
    $file_size = $_FILES['pdf_file']['size'];

    // Validate file type
    if ($file_type != "application/pdf") {
      echo "Errore: solo file PDF sono consentiti.";
      exit;
    }

    // Read the uploaded file content
    $file_content = file_get_contents($file_tmp);

    // Create a boundary string for the multipart email
    $boundary = md5(uniqid());

    // Prepare the email headers
    $headers = "From: [email protected]";
    $headers .= "Reply-To: $emailrn";
    $headers .= "Content-Type: multipart/mixed; boundary="PHP-mixed-".$boundary.""rn";

    // Create the email body
    $mail_body = "--PHP-mixed-" . $boundary . " rn";
    $mail_body .= "Content-Type: text/plain; charset="UTF-8"rn";
    $mail_body .= "Content-Transfer-Encoding: 7bitrnrn";
    $mail_body .= "Nome: $namenEmail: $emailnMessaggio:n$message";

    // Attach the PDF file
    $mail_body .= "--PHP-mixed-" . $boundary . " rn";
    $mail_body .= "Content-Type: application/pdf; name="$file_name"rn";
    $mail_body .= "Content-Disposition: attachment; filename="$file_name"rn";
    $mail_body .= "Content-Transfer-Encoding: base64rnrn";
    $mail_body .= chunk_split(base64_encode($file_content)) . "rn";

    $mail_body .= "--$boundary--rn"; // Closing boundary for the email


    // Send the email
    if (mail($recipient_email, "Nuovo messaggio da $name", $mail_body, $headers)) {
      $showThankYou = true;
    } else {
      // Get the error message
      $errorMessage = error_get_last()['message'];
      echo "Ci sono stati problemi con l'invio dell'email: $errorMessage";
    }
  } else {
    echo "Errore durante il caricamento del file";
  }
}
?>

<?php if ($showThankYou): ?>
  <p>Grazie per averci inviato un messaggio! Ti contatteremo in tempi brevi per rispondere alle tue domande.</p>
<?php endif; ?>

and this is what I get in my email:
I’ve been trying to change my php different times. Could it be something on the sever that causes the problem?

enter image description here