How do I fix this curl deepl code is not working

I have the following code and it is not working, I just get string(0) “”
This code is a copy of a DeepL curl script that creates a glossary which works perfect, I just changed the url and options in DATA. I’m also not getting any errors if I change the auth. code.

<?php
$text = 'Hi there';
$source_lang = "en";
$target_lang = "de";
$glossary_id = "";
$tag_handling = "xml";
$ignore_tags = "x";
$formality = "";
$url = "https://api.deepl.com/v2/translate";
$authKey = "hidden";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Authorization: DeepL-Auth-Key .$authKey",
   "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = <<<DATA
text=$text&source_lang=$source_lang&target_lang=$target_lang&tag_handling=$tag_handling&ignore_tags=$ignore_tags&formality=$formality&glossary=$glossary_id
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);

// Check for errors and display the error message
if($errno = curl_errno($curl)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):n {$error_message}";
}

curl_close($curl);
var_dump($resp);
?>

I’m not getting any errors.

Update count on fancybox previous or next button click

I am using Fancybox for photo gallery. and using following code to update photo views on click with php mysql and ajax.

I want to update views for images when previous or next button in opened fancybox is clicked.

Current code :

Javascript :

<script>
$('document').ready(function(){
  $('.updatecount').click(function(){
    var unique_id = $(this).parent().data('id');
        $.ajax({ 
            url: 'photo-gallery-count-update.php',
            data: {"uniqueid": unique_id},
            method: 'post'
        });
  });
});
</script>

HTML Part :

<div class="card " data-id="<?php  echo $pdata['unique_id'];?>">
    <div class="card-image updatecount">
        <a href="<?php echo $img_url;?>" data-fancybox="gallery" data-caption="<?php echo $caption_final;?>">
       <img src="<?php echo $img_url;?>" alt="Image Gallery">
        </a>
    </div>
    <div class="c1"><?php echo $subtitle_final;?></div>
</div>

photo-gallery-count-update.php :

<?php
include("db.php");

if(isset($_POST['uniqueid'])){
   $unique_id = $database->filter($_POST['uniqueid']);

   $query= "select * from $photo_gallery_table where unique_id='$unique_id'";
   $numrow = $database->num_rows($query);

   if ($numrow != 0){
      $result = $database->get_results($query);

      foreach ($result as $data){
         $viewed = $data['viewed'];
         $viewed_new = $viewed + 1;
         $viewed_on = date("Y-m-d H:i:s");
         $unique_id_db = $data['unique_id'];
         
         $insertdata = array (          
            'viewed' => $viewed_new,
            'viewed_on' => $viewed_on,          
         );
         $where = array (
            'unique_id' => $unique_id_db
         );
         $database->update($photo_gallery_table, $insertdata, $where);
    }
  }
 }
?>

This code is working when Photo is clicked directly.

When photo is clicked, fancybox get opened showing photo.

I want to update views for next or previous photos when clicked on Next / Previous button in opened fancybox.

I tried adding class names .fancybox-slide--next, .fancybox-slide--previous in javascript click event, but it didn’t work.

Authenticating with OAuth 2.0 Application-Only error when curl/php posting

I have gathered the following code in an attempt to post to X:

$api_key='xx';
$api_secret='yy';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$api_secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');

$response = curl_exec($ch);

curl_close($ch);

$response=json_decode($response);
$access_token=$response->access_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/2/tweets');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer '.$access_token,
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"text":"Hello, world!"}');

$response = curl_exec($ch);

curl_close($ch);

print_r($response);

I’m getting the access_token but in the end I’m presented the following error: “Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint. Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context].”

Any idea to what I’m doing wrong?

Assistance Required for Migrating to FCM HTTP V1 in Symfony 2.8 Project

Currently I am working on a project which was created with Symfony 2.8 and have some problems when trying to migrate to the FCM HTTP V1 API. I have no idea what is the procedure and would be very grateful for your help in solving this problem. Here are the relevant code snippets for the current FCM implementation:

class HomeController extends Controller
{
function send_notificationToken ($tokens, $message,$key)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
        'registration_ids'  => $tokens,
        'data'   => $message

        );
    $headers = array(
        'Authorization:key = '.$key,
        'Content-Type: application/json'
        );
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   $result = curl_exec($ch);           
   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}
function send_notification ($tokens, $message,$key)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
        'to'  => '/topics/Flixo',
        'data'   => $message
        );
    $headers = array(
        'Authorization:key = '.$key,
        'Content-Type: application/json'
        );
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   $result = curl_exec($ch);           
   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}
  public function privacypolicyAction() {
    $em = $this->getDoctrine()->getManager();
    $setting = $em->getRepository("AppBundle:Settings")->findOneBy(array(), array());
    return $this->render("AppBundle:Home:privacypolicy.html.twig", array("setting" => $setting));
}
public function apprefundpolicyAction() {
    $em = $this->getDoctrine()->getManager();
    $setting = $em->getRepository("AppBundle:Settings")->findOneBy(array(), array());
    return $this->render("AppBundle:Home:apprefundpolicy.html.twig", array("setting" => $setting));
}
public function notifChannelAction(Request $request)
{
    $imagineCacheManager = $this->get('liip_imagine.cache.manager');
    $em=$this->getDoctrine()->getManager();
    $defaultData = array();
    $form = $this->createFormBuilder($defaultData)
        ->setMethod('GET')
        ->add('title', TextType::class)
        ->add('message', TextareaType::class)
        ->add('object', 'entity', array('class' => 'AppBundle:Channel'))           
        ->add('icon', UrlType::class,array("label"=>"Large Icon","required"=>false))
        ->add('image', UrlType::class,array("label"=>"Big Picture","required"=>false))
        ->add('send', SubmitType::class,array("label"=>"Send notification"))
        ->getForm();
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $selected_channel = $em->getRepository("AppBundle:Channel")->find($data["object"]);
        $message = array(
              "type"=> "channel",
              "id"=> $selected_channel->getId(),
              "title"=> $data["title"],
              "message"=>$data["message"],
              "image"=> $data["image"],
              "icon"=>$data["icon"]
            );

        $setting = $em->getRepository('AppBundle:Settings')->findOneBy(array());            
        $key=$setting->getFirebasekey();
        $message_image = $this->send_notification(null, $message,$key); 
        $this->addFlash('success', 'Operation has been done successfully ');
    }
    return $this->render('AppBundle:Home:notif_channel.html.twig',array(
      "form"=>$form->createView()
      ));
}

Thanks in advance.

How can I submit a form without breaking dynamic content in PHP with JavaScript? [duplicate]

I have a webpage with a navbar menu. When a user clicks on a menu item, it dynamically loads the corresponding PHP file into the home dynamic content section using JavaScript, and the content updates without reloading the page.

One of the menu options displays a message form within the dynamic content area. However, when I submit the form, it redirects to the form.php file, causing the entire page to reload and breaking the dynamic content.

I want to submit the form data without causing a page reload, while keeping the dynamic content intact. I would like to display the success or failure message after submission, without reloading the page.

How can I achieve this using JavaScript to submit the form and display the result without breaking the dynamic content?

home.php

<li class="nav-item m-2"><a href="message.php" id="message" class="nav-link text-white px-3 py-2">message</a></li>

js

const massage = document.getElementById("message");

function loadPage(event, page) {
    if (event) event.preventDefault();

    fetch(page) // Fetch the PHP page
        .then(response => response.text())
        .then(data => {
            mainContent.innerHTML = data;
        })
        .catch(error => console.error("Error loading page:", error));
}

if (message) makeTimetable.addEventListener("click", (event) => loadPage(event, "../message.php"));

Magento 2.4.7 Cloud – Product attribute value exceed 500

I have a Magento Cloud Commerce project running on version 2.4.7. Currently, we display all products on the homepage with pagination. We have created multiple attributes for configurable products, and one of these attributes, ‘reports,’ has over 500 values. According to Magento, the number of attribute values should not exceed 100, which has led to slow site performance. As per client, they cannot limit the optionas value.
I am bit confuse from where should I start.
Can anyone recommend a solution for this issue?

How to verify and prevent unintended changes when modifying specific parts of an HTML document using PHP DOMDocument?

I got a task to update specific parts of HTML elements across all pages of a web project. Given the size and complexity of the project, I prefer using DOM manipulation over methods like regex to ensure more structured changes. However, as I’m a beginner in DOM manipulation and am handling real data, I have some concerns.

My main concern is ensuring that only the intended parts of the HTML are modified, while other parts of the document remain unchanged. I want to verify and prevent if any unintended changes are made implicitly by the DOM parser during manipulation. This is crucial for data integrity and preventing accidental modifications in the rest of the document.

So far, I’ve also noticed that PHP’s DOMDocument class converts all HTML tag names to lowercase by default when parsing HTML, which is fine.

$html = '
<!DOCTYPE html>
<html>
<head>
    <title>My Web Page</title>
</head>
<body>
    "This Line Non Tag TextNode Before header"
    <h1 id="main-header" class="header">Main Header</h1>
    <div class="content">
        <h1 class="nested-header">Nested Header 1</h1>
        <p>Some content under nested header.</p>
        <a href="https://example.com">Example Link</a>
    </div>
    <h2 id="sub-header-1">Sub Header 1</h2>
    <h3>Sub Header 2</h3>
    <h1>Another Main Header</h1>
    <p>This is a paragraph outside the header tags.</p>
    <footer>Some footer text with <span>inline text</span>.</footer>
</body>
</html>';

// Load HTML content
$doc = new DOMDocument();
@$doc->loadHTML($html);

// Create a TextNode to be inserted before the first <h1>
$textNode = $doc->createTextNode('This Line Non Tag TextNode Before header');

// Insert the TextNode before the first <h1> element
$firstHeader = $doc->getElementsByTagName('h1')->item(0);
if ($firstHeader) {
    $firstHeader->parentNode->insertBefore($textNode, $firstHeader);
}

// Remove the first <h1> element
if ($firstHeader) {
    $firstHeader->parentNode->removeChild($firstHeader);
}

// Check if other headers or elements are modified unintentionally
$modifiedHtml = $doc->saveHTML();
echo $modifiedHtml;

What and how are the best practices for handling and managing memory storage to ensure stability? [closed]

Our website handles file uploads, averaging 100-500 client uploads daily. Each file is validated to be under 3MB. We need to stabilize and optimize our storage to handle this continuous influx of data, with a requirement to retain all files for 15 years. What are the best practices for managing this storage, How can we ensure long-term scalability and efficiency?

We have been making efforts to remove some duplicate files uploaded by users. Are there any good methods, such as algorithms, for handling these files to reduce their size? What are your thoughts on the best practices? Is it necessary to use a compressor?

We have try remove some file

How to Define a money Data Type in Laravel Migrations for SQL Server?

I’m working with Laravel migrations and need to define a money column type in SQL Server. However, Laravel’s schema builder does not provide a direct money type.

I’ve considered two approaches:

Using raw SQL:

Schema::table('your_table', function (Blueprint $table) {
    DB::statement("ALTER TABLE your_table ADD price MONEY");
});

Using decimal as an alternative:

Schema::table('your_table', function (Blueprint $table) {
    $table->decimal('price', 19, 4);
});

I prefer a solution that works natively with Laravel’s schema builder. Is there a way to register a custom column type for money, or is raw SQL the only option?

Any recommendations for best practices in Laravel with SQL Server are appreciated!

Why do my session variables disappear after calling session_regenerate_id(true)?

I have a method createSession() that calls session_regenerate_id(true); to prevent session fixation:

class Session {
    public string $id;
    public string $username;
    public string $role;

    public function __construct(){
        session_start();
        $this->id = $_SESSION['id'] ?? 0;
        $this->role = $_SESSION['role'] ?? 'guest';
        $this->username = $_SESSION['username']  ?? 'Guest User';
    }

    public function updateSession(array $user){
        $this->createSession($user);
    }

    public function createSession(array $user){
        session_regenerate_id(true);
        $_SESSION['id'] = $user['id'];
        $_SESSION['username'] = strstr($user['email'], '@', true);
        $_SESSION['expire'] = time() + 30 * 60;
        $_SESSION['role'] = $user['role'];
    }

    public function destroySession(){
        $_SESSION = [];
        $cookie_data = session_get_cookie_params();
        setCookie(session_name(), '', time() - 42000, $cookie_data['path'], $cookie_data['domain'], $cookie_data['httponly']);
        session_destroy();
    }
}

After calling this function, all previous session data seems to be lost.

Is this behavior normal?
How can I securely regenerate the session without losing existing data?

Do I need to manually copy session values before regenerating?

I’m using PHP 8.2 and storing sessions in the default file-based handler. Could the session storage settings affect this ?

Model Observer issue in nested transaction update of model

class Service A { 

public function approve($user, $data) { 

$apporvedUser = DB::transaction(function () use ($user, $data) {
        if($data['approve_by_admin'] == 1){
            $this->updateAdminStatus($user);
        }

        $user->update(['approved'] => 1); // This fires updated event 
    })
 }

 public function updateAdminStatus($user){
    $user = DB::transaction(function () use ($user, $data) {

        //Some Logic

        $user->update(['status'] => 5); // This doesnt fire event 
    })
 }
}

I have Scenario like above where same model gets updated in nested transactions but observer get only changes of last transaction, i want to get all updates in observer for same model.

How to submit a form through a confirmation modal with no or minimal JavaScript in PHP? [closed]

I am trying to implement a confirmation modal in my PHP page that will submit a form when the user confirms an action (like deletion). I want to avoid using custom JavaScript for the submission and rely mainly on HTML and PHP to handle the form submission.

Here’s the flow I want:

  1. User clicks a button to open the modal.
  2. The modal asks for confirmation with two options: Cancel and Yes, Submit.
  3. Clicking “Yes, Submit” should submit the form and trigger PHP logic, without using JavaScript to handle the submission.

Here’s the sample code I am working with:

<form id="generic_form" method="post">
    <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#confirm_modal">
        **Delete Item**
    </button>
</form>

<!-- Confirmation Modal -->
<div class="modal fade" id="confirm_modal" tabindex="-1" role="dialog" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">**Are you sure?**</h4>
            </div>
            <div class="modal-body">
                **This action will remove the item permanently.**
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">**Cancel**</button>
                <button type="submit" class="btn btn-danger" name="btn_confirm_delete" value="submit" data-dismiss="modal">
                    **Yes, Submit**
                </button>
            </div>
        </div>
    </div>
</div>

// HERE : This code is Not Executing 
if (isset($_POST["btn_confirm_delete"])) {
    // Call the function to handle the deletion
    **handle_deletion_function**();
}

As far as I know, when a submit button is clicked, the form containing the button is submitted, and its $_POST data is sent to the server. However, in this case, we are not directly submitting the form, so the page does not reload, which is the default behavior when a form is submitted. Also I do not want a separate JavaScript function to handle this submission.

Parsing an .odt content.xml with PHP results in an empty object [closed]

I’m trying to parse a libre office writer content.xml file on my server with php simplexml_load_file.

$xml = simplexml_load_file("https://ff-webdesigner.com/erechnung/content.xml");
print_r($xml);

But it always results in an empty object SimpleXMLElement Object ( ). Why?
Checked with file_get_content, setting namespaces and much more. All in vain.
With other xml files it’s working flawlessly…i checked for xml validity and also fixed all minor warnings.

php export data to excel / csv with dynamic column names [duplicate]

Currently I am using following code to export mysql data to csv file

<?php
 include("db.php");
 $query = "SELECT * FROM my_table";

 $delimiter = ","; 
 $filename = "MY-LIST-" . date('d-F-Y-H-i-s') . ".csv";
 
 $f = fopen('php://memory', 'w'); 

 $fields = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');
 fputcsv($f, $fields, $delimiter); 
 
 $result = $database->get_results($query);
  foreach($result as $row){ 
     $lineData = array($row['id'], $row['first_name'], $row['last_name'], $row['email'], $row['gender'],$row['country'], $row['date_created'], $row['member_status']);
     fputcsv($f, $lineData, $delimiter);      
 } 

 fseek($f, 0);

 header('Content-Type: text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";'); 
 
 //output all remaining data on a file pointer 
 fpassthru($f); 

?>

Above Code is working ok ! and creating csv as expected.

Now I have another mysql table with around 89 columns and I want to export it to csv.

To reduce time consuming typing work, I need to fetch column names and put their values in array.

Current code I am trying is as follows :

<?php
 include("db.php");

 $result1 = $database->list_fields_name_serially('my_table');  
 // Getting all column names as comma separated list as id, first_name, last_name, email, gender, country, date_created, member_status, column_1, column_2, ......, column_89... (there is space after comma and before each column name)

 $result2 = strtoupper(str_replace("_", " ", $result1)); // removing underscore
 $result = strtoupper(str_replace(",", "' , ' ", $result2)); // replacing comaa with comma nad single quotes

 $delimiter = ","; 

 $filename = "MY-LIST-" . date('d-F-Y-H-i-s') . ".csv";
  
 $f = fopen('php://memory', 'w'); 

 $fields = array($result); // output = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS');

 fputcsv($f, $fields, $delimiter); 

 $field_name = explode(",", str_replace(" ", "", $result1));

 $resultdata = $database->get_results("select * from my_table");
    foreach($resultdata as $row){
        foreach($field_name as $k => $v){ 
            $lineData[$k] = array($row[$v]);
        }
    
    fputcsv($f, $lineData, $delimiter); 
  }

  fseek($f, 0); 
 
// Set headers to download file rather than displayed 
header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="' . $filename . '";'); 
 
//output all remaining data on a file pointer 
fpassthru($f); 
?>

BUT IT IS NOT WORKING….. SCRIPT RUNS FOR FEW MINUTES AND THEN CREATES A CSV WITH ERRORS IN IT – Warnig : Array to string conversion on line 54 i.e. fputcsv($f, $lineData, $delimiter);

Which PHP ICal libary should i use? [closed]

I Want to publish a ICal feed from my webserver. The content is stored in a remote server so i make a api call to get a JSON file with the data.

I want to phrase/map the data trough the libary and publish the feed.

Which libary should i use?

It should support timzones and automaticly add the VTimezone object to the Calendar feed if it is used in a DSTART or DEND.