Auto print pdf with pdf.js in kiosk

I need to build automatic kiosk, where people will get their pdf’s printed. I will use firefox with silent.print mode on, but I have trouble getting pdf to print in a page that will be a popup (so creating a popup will print pdf inside).

The thing is, that printing is printing white page because print occurs before pdf is loaded, so I tried adding function that will make printing wait. Results is the same, because waiting function will make generating pdf wait also.

Any ideas how to make this work or find workaround?

<!DOCTYPE html>
<html>
  <head>
    <title>Pdf Result</title>
  </head>
  <body>

    <p>Loading resources....</p>
<-- loading pdf -->
    <div>
        <div>
            <iframe onload="window.print()" id="pdf-js-viewer" src="lib/pdfjs/web/viewer.html?file=test.pdf" title="webviewer" frameborder="0" width="500" height="600"></iframe>
        </div>
    </div>


    <script>
//making script wait
    function wait(ms){
       var start = new Date().getTime();
       var end = start;
       while(end < start + ms) {
         end = new Date().getTime();
      }
    }

    wait(5000);

//printing itself
    document.getElementById("pdf-js-viewer").contentWindow.print(); 
    
    </script>
  </body>
</html>

Web Scraping using curl in php [closed]

I tried to scrape the products details from the website but i got an output as blank page
Here is my code :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.samsung.com/in/smartphones/galaxy-s/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);


curl_close($ch);

$dom =  new DOMDocument();
@ $dom->loadHTML($result);

$xpath = new DOMXPath($dom);


$name_elements = $xpath->query('//p[@class="pd03-product-card__product-name-text"]');
$price_elements = $xpath->query('//p[@class="pd03-product-card__price-main"]');

$name_array = array();
$price_array = array();


foreach ($name_elements as $name){
    $product_name = $name->textContent;
    echo "Product Name : " .  $product_name . "<br>";
}



foreach ($price_elements as $price){
    $product_price =  $price->textContent;
    echo "Product Price :" . $product_price . "<br>";
}



can anyone help me out how can i resolve this problem

curl_setopt() command using multipart/form-data with 2 boundary

i have to create a POST request using CURL with this parameters:

  1. The header must be: Content-Type:multipart/form-data
  2. 2 Boundary
  3. first: Content-Disposition: form-data; name="fileName" Content-Type: application/json {"fileName":[filename],"codFornitore":205900}
  4. Second: Content-Disposition: form-data; name="file"; filename="[filename]" Content-Type: [based on type of file] [byte array of file content]

How can i create a string that define this type of post body and its curl call?

How to Hide fields left empty for both subject group and subject – phpmyadmin? [closed]

here’s bit of background.

I’ve recently took over the IT for a school. They are currently using a student grading report system a previous IT manager made in myphpadmin.

The problem with the report system is that a lot of subjects are shown, even for classes which don’t need it on the website. For example, class 1 (ages 5-6) will show subjects like woodworking?

The previous IT manager made an option to ‘hide a subject if blank’ used in the subject table however because there are columns with in columns (subject group and then subjects), if the table has a sub subject then it’s impossible for the hide feature to work.

I was wondering how I can make it so that subjects and sub subject can be hidden if left empty?

For example, English as subject group, I want to be able to hide the subject group (english), Writing and/or reading as subjects.

This is for the subject group

This is for the subject

this is what is shown in the report.

I’m sorry if I sound dumb, Although I have a computer science background, I have never used phpmyadmin before this and I don’t really know where I could find the bespoke code if they did use that to hide the fields either. Kind of confused on what to do. Any pointers would be greatly appreciated. Thanks so much!

WordPress Custom post type not available in REST API

Good day

I have now tried everything and read through the WordPress documentation and read every post here and on other websites, but I cannot figure out why my custom post is not available via the WordPress REST API.

Here is my code snippet I am using through WPCode Lite:

function Custom_post_type() {
    $labels = array(
        'name'                => _x( 'Line Managers', 'Post Type General Name' ),
        'singular_name'       => _x( 'Line Manager', 'Post Type Singular Name'),
        'menu_name'           => __( 'Line Managers'),
        'parent_item_colon'   => __( 'Parent Line Manager'),
        'all_items'           => __( 'All Line Managers'),
        'view_item'           => __( 'View Line Manager' ),
        'add_new_item'        => __( 'Add New Line Manager' ),
        'add_new'             => __( 'Add New'),
        'edit_item'           => __( 'Edit Line Manager'),
        'update_item'         => __( 'Update Line Manager'),
        'search_items'        => __( 'Search Line Manager'),
        'not_found'           => __( 'Not Found'),
        'not_found_in_trash'  => __( 'Not found in Trash'),
    );
    
    $args = array(
        'label'                 => __( 'line'),
        'description'           => __( 'Line Manager news and reviews'),
        'labels'                => $labels,  
        'supports'              => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),     
        'taxonomies'            => array( 'workplace' ),     
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'show_in_nav_menus'     => true,
        'show_in_admin_bar'     => true,
        'menu_position'         => 5,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'rewrite'               => array( 'slug' => 'line' ),
        'capability_type'       => 'post',
        'query_var'             => true,
        'show_in_rest'          => true, 
        'rest_base'             => 'line',
        'rest_controller_class' => 'WP_REST_Posts_Controller'
    );
    //unregister_post_type('line');

    register_post_type( 'line', $args );
}
add_action( 'init', 'Custom_post_type' );

I can access the normal posts through the API, but not the custom post. Here are the links:
https://dev.freedomsoftware.co.za/wp-json/wp/v2/line

https://dev.freedomsoftware.co.za/wp-json/wp/v2/posts

I have made sure that the permalink structure is set to “Post name”, I have unregistered the post type and reregistered it several times, I made sure I have the "show_in_rest" => true, I have basically tried everything I could find online, unless I missed something and that is why I am asking here.

Any help would be greatly appreciated.

How do I get the contact form to work with phpmailer?

I need your help: my site has a form where the user can contact the company and, before the site was online, I edited php.ini and sendmail.ini (xampp’s file) and everything was fine on the localhost. Once the site has been uploaded to aruba hosting, the form has stopped working and reading online I must use phpmailer. Here is the code for the site to do its work on localhost:

<!-- HOMEPAGE -->

<div class="subscription"> <h2 class="registrati"> CONTATTACI</h2> </div>

<!-- container -->

<div class="container-fluid">

<form class="row g-3 justify-content-center" style="margin:0 auto; width:80%;" id="form" action="#">

<div class="col-md-6">

<label for="inputNome" class="form-label" id="labels">Nome</label>

<input type="text" name="nome" class="form-control" id="inputNome" required> </div>

<div class="col-md-6">

<label for="inputCognome" class="form-label" id="labels">Cognome</label>

<input type="text" name="cognome" class="form-control" id="inputCognome"> </div>

<div class="col-md-6">

<label for="inputEmail" class="form-label" id="labels">Indirizzo Email</label>

<input type="email" name="email" class="form-control" id="inputEmail" required> </div> <div class="col-md-6">

<label for="inputTelefono" class="form-label" id="labels">Telefono</label>

<input type="text" name="telefono" class="form-control" id="inputTelefono"> </div> <div class="col-12">

<label for="inputAzienda" class="form-label" id="labels">Azienda</label>

<input type="text" name="azienda" class="form-control" id="inputAzienda" placeholder="Atomic srl" required> </div>

<div class="mb-3">

<label for="exampleFormControlTextarea1" class="form-label" id="labels">Messaggio</label> <textarea class="form-control" name="messaggio" id="exampleFormControlTextarea1" rows="3"></textarea> </div>

<br>

<div class="col-12 buttonarea">

<button type="submit" class="btn btn-outline-dark" name="invia" id="invia">Invia</button> <span></span> </div>

</form>

</div>

and this is the the code I found online to make the form work with phpmailer :


    <?php
    use PHPMailerPHPMailerPHPMailer;
    use PHPMailerPHPMailerSMTP;
    use PHPMailerPHPMailerException;
    
    require 'phpmailer/src/Exception.php';
    require 'phpmailer/src/PHPMailer.php';
    require 'phpmailer/src/SMTP.php';
    
    $mail = new PHPMailer(true); //se true vengono sollevate eventuali eccezioni utili per il debugging
    
    try {
        //Impostazioni server
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                //Debug mode
        $mail->isSMTP();                                      //Invio tramite SMTP
        $mail->Host       = 'smtp.gmail.com';                 //Server SMTP
        $mail->SMTPAuth   = true;                             //Abilita autenticazione SMTP
        $mail->Username   = '[email protected]';                 //SMTP username
        $mail->Password   = 'lfpamoizwjsdhpfj';                //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;   //Abilita TLS implicito
        $mail->Port       = 587;                              //Porta SMTP
    
        //Recipients
        $mail->setFrom('[email protected]', 'User');
        $mail->addAddress('[email protected]', 'Dest');  //Indirizzo destinatario
        $mail->addReplyTo('[email protected]', 'User');          //Indirizzo di risposta
        $mail->addCC('[email protected]');                         //Campo CC  (Copia Carbone)    
        $mail->addBCC('[email protected]');                       //Campo BCC (Copia Carbone Nascosta)
    
        //Content
        $mail->isHTML(true);                                  //Abilita invio in HTML
        $mail->Subject = 'Oggetto';                           //Oggetto 
        $mail->Body    = 'This is the HTML message body <b>in bold!</b>'; //Corpo email
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //Testo alternativo
    
        $mail->send();
        echo 'Il messaggio è stato inviato con successo';
    } catch (Exception $e) {
        echo "Il messaggio non è stato inviato. Errore: {$mail->ErrorInfo}";
    }

?>

PHP HTML shopping cart – remove added, first product isn’t showing

I made a shopping cart for people to order products. The products are added perfect. So i made a ‘remove’ button. But since i implemented the ‘remove’ button, the first result is not showing. The second and third are showing up. If i comment out the remove form, everything is showing, but you cant remove..
What am I doing wrong?



<div style="clear: both"></div>
<h3 class="title 2">Shopping Cart Details</h3>
<div class="table-responsive">
  <table class="table table-bordered">
    <tr>
      <th width="30%">SKU</th>
      <th width="20%">Item Description</th>
      <th width="20%">Quantity</th>
      <th width="30%">Remove Item</th>
    </tr>


  
    <?php
    if (!empty($_SESSION['cart'])) {
      foreach ($_SESSION['cart'] as $key => $value) 
        {
    ?>


      <tr>
        <td><?php echo $value['SKU']; ?></td>
        <td><?php echo $value["item_description"]; ?></td>
        <td><?php echo $value['quantity']; ?></td>
          
        <!-- remove form  -->
            <!-- <form action="lijstweergave.php?action=remove&SKU=<?php  // echo $value['SKU']; ?>" method="post">
            <input type="hidden" name="remove_SKU" value="<?php // echo $value['SKU']; ?>">
            <input type="submit" name="remove_item" value="Remove">
        </form> -->
      </tr>

        <!-- end  remove form  -->

    <?php
        }
    }

    
    ?>
  </table>
  </div>
</div>`

I tried putting the code out of the loop, commenting out change the format.

How to auto post php form imported data



1.txt
 aaaaaaaaaa
 bbbbbbbbbb
 cccccccccc
 ......

Code:


`$post_data = array( 'user_data' => array(
'username' => $username,
'password' => $password,
'max_connections' => $max_connections,
'is_restreamer' => $restreamer,
'member_id' => $reseller,
'created_by' => $reseller,
'is_trial' => $is_trial,
'exp_date' => $expire_date,
'bouquet' => json_encode( $bouquet_ids ) ) );

$opts = array( 'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query( $post_data ) ) );

$context = stream_context_create( $opts );
$api_result = json_decode( file_get_contents( $panel_url . "api.php?action=user&sub=create", false, $context ) );
// $obj = $api_result;
// $name = $obj->{'username'};
// $pass = $obj->{'password'};
print_r($api_result);
// print_r($post_data);    
?>

</div>
<div class="content">
<?php
$path = "1.txt";
$file = fopen($path, 'r');
$data = fread($file, filesize($path));
fclose($file);

$lines =  explode(PHP_EOL,$data);
foreach($lines as $line) {
  echo '<form id="submit" action="#add1.php" method="post" >

<div class="form-group">
<div style="width:100%; background:#eeeeee;">
<button type="multiselect" id="submit" class="btn btn-primary" name="submit">ENTER</button>
<input type="hidden" name="macadress" id="macadress" value= '. $line.'>'.$line.'';

  echo '</form>';
}
?>
</div>
<script>
window.onscroll = function() {myFunction()}; // sleep(1);
var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

</script>

Hello all.

I use below code and many data listed when run php. (1000-1500 pcs) need to click one by one for submit lines.

imported data from txt (1.txt) file and listed line by line. all lines have submit button and send by click submit button. How to auto post created lines with 1 second delay.

How to get arrays into phpchart

I am trying to create a chart with phpChart, that will show a value based on its date.
The data for the array is retrieved from a mySQL DB and put into a variable (eventually as $chrt).
If I echo the array they are showed right, but if I pass them on to the phpChart function, nothing happens. The chart stays empty.
However, if I copy and paste the very values of the **array ** into the phpChart function, the chart is show correctly.

Here is a snippet of the code:

 $db = mysqli_select_db($connection, "stockreport") or die("Error " . mysqli_error());
$item = $_GET["item"];
   $sql = mysqli_query($connection, "SELECT * FROM import2 where itemcode=$item");

   while($row = mysqli_fetch_array($sql)) {
   $stock[] = $row['stock'];
   $date[] = $row['impdate'];
   
   $data = strtotime($row[0]);
   $date2 = date('Y-m-d', $data);   
   
   $vals = 'array("' . $date2 . '",' . $row[3] . '),';    
   
   **$chrt** = array($vals);
    print_r($chrt);    
       
       }
    
     
    
$pc = new C_PhpChartX(array(**$chrt**),'chart1');

And here the array:

array(“2022-11-18”,250),array(“2022-11-21”,250),array(“2022-11-28”,250),array(“2022-12-05”,230),array(“2022-12-12”,226),array(“2022-12-19”,226),array(“2022-12-26”,226),array(“2023-01-02”,226),array(“2023-01-09”,226),array(“2023-01-16”,226),array(“2023-01-23”,172),array(“2023-01-30”,172),array(“2023-02-06”,127),array(“2023-02-13”,117),array(“2023-02-27”,117),array(“2023-03-06”,77),array(“2023-03-13”,72),array(“2023-03-20”,32),array(“2023-04-03”,12),array(“2023-04-10”,12),array(“2023-04-17”,12),array(“2023-04-24”,2),array(“2023-05-01”,2),array(“2023-05-08”,2),

I tried putting the data into a file with JSON, and get them back into the function, but it won’t also work.

Customer Notes in vendor order email

I try to be short: I manage a multivendor woocommerce with WCFM plugin. When a new order is placed, a new order email in sent both to admin and to stores; the “issue” is that the store email doesn’t include the Customer Order Notes added during checkout (i.e. notes for courier).
I compared the admin-new-order.php template where I find this piece of code * @hooked WC_Emails::order_meta() Shows order meta data. */ do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email ); with the store-new-order.php template where I find instead this code if( apply_filters( 'wcfm_is_allow_wc_default_email_order_meta', true ) ) { do_action( 'woocommerce_email_order_meta', $order, 0, 0, $email ); }
How can I modify the store email template?

How can i change stripe subscription payment page design?

The subscription payment page is aligning in one line i need to show it like a normal payment form show card number , cvv and expiry on multiple lines rather than one line
i m attaching an image to show how it looks
stripe image before,
how it should look

my code is as follow

  var stripe = Stripe('Publishable Key');


 var elements = stripe.elements();
  
  var style = {
 base: {
      color: '#32325d',
      fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
      fontSmoothing: 'antialiased',
      fontSize: '16px',
      '::placeholder': {
          color: '#aab7c4'
      },
      display:'block'
  },
  invalid: {
      color: '#fa755a',
      iconColor: '#fa755a'
  }
  };

        
      // Create an instance of the card Element.
      var card = elements.create('card', {style: style});
      card.mount('#card-element');

please advice

How can I resolve the issue of not being able to log in using Google identity services on my website?

Im trying to implement the new google Google Identity Service google login in my website, however I ran into some issues. Basically I have two types of creating account on my page, one is by manually filling out details and the other one is through google, however I can’t seem to make it work.

this is the exact error : Uncaught Error: Class ‘Google_Client’ not found in myfolder/accountCreation/create-account-google.php:19

I basically want to get the google account data and then insert it into my database where I store account details…

This is the html

<div id="g_id_onload"
      data-client_id="My-Client-ID(I have it here).apps.googleusercontent.com"
      data-callback="handleCredentialResponse"
      data-context="signin"
      data-ux_mode="popup"
      data-auto_prompt="false">
</div>
<div class="g_id_signin" 
        data-type="standard"
        data-shape="rectangular"
        data-theme="outline"
        data-text="signin_with"
        data-size="large"
        data-logo_aligment="left">
                
 </div>

This is the function

function handleCredentialResponse(response){
                    const responsePayload = decodeJwtResponse(response.credential);
                      console.log("ID: " + responsePayload.sub);
                      console.log("Full Name: " + responsePayload.name);
                      console.log("Given name: " + responsePayload.given_name);
                      console.log("Family name: " + responsePayload.family_name);
                      console.log("Email: " + responsePayload.email);

                      $.ajax({
                          type: "POST",
                          url: "myfolder/accountCreation/create-account-google.php",
                          data: { 
                              id_token: response.credential,
                              id: responsePayload.sub,
                              full_name: responsePayload.name,
                              given_name: responsePayload.given_name,
                              family_name: responsePayload.family_name,
                              email: responsePayload.email
                          },
                          success: function(response) {
                              console.log(response);
                          },
                          error: function(response) {
                              console.log(response);
                          }
                      });

                    //decode JWT
                    function decodeJwtResponse(data){
                      var tokens = data.split(".");
                      return JSON.parse(atob(tokens[1]));
                    }
                  }

This is my php script

<?php

include(dirname(__FILE__) . '/../connection.php');

if(isset($_POST['id_token'])) {
  $id_token = $_POST['id_token'];
  // Get user information from the ID token
  $client = new Google_Client(['client_id' => 'My-Client-ID(I have it there).apps.googleusercontent.com']);
  $payload = $client->verifyIdToken($id_token);
  if ($payload) {
    $email = $payload['email'];
    $firstName = $payload['given_name'];
    $lastName = $payload['family_name'];
    
    // Check if the email already exists in the database
    $sql = "SELECT * FROM loginregister WHERE email='$email'";
    $result = $con->query($sql);
    if($result->num_rows > 0) {
      echo "Email already exists. Please choose a different email address.";
    } else {
      // Insert the new user information into the database
      $sql = "INSERT INTO loginregister (email, firstname, lastname) VALUES ('$email', '$firstName', '$lastName')";
      if ($con->query($sql) === TRUE) {
        echo "Account created successfully. You can now login.";
      } else {
        echo "Error: " . $sql . "<br>" . $con->error;
      }
    }
  }
}
 else {
    echo "Invalid ID token.";
  }

?>

I tried watching tutorials on youtube but unfortunately they are in react or are just not sufficient enough to fix my problem. Cant ask chatGPT because its outdated on this topic as its 2023, and chatGPT uses 2021 info.

Issue when i uploading files named in greek characters in production env, but not in the localhot env

I am using a php framework called Scriptcase, so in this framework i have a simple form and a file input in order to upload my files into the server.

Localhost when i am uploading greek named files from my pc (jpg, png etc..) everything works fine.
For example if have a file named ελλαδα0123.png it is uploaded correctly into to my server.

But in the Production env, if i go to upload the exact same file named “ελλαδα0123.png” it’s uploaded like that ΕΥΔΑΠ ΠΕΙΡΑΙΞ0123.png.

I think is a problem with the encoding, but this is only happeping when it comes to uploading greek named files into the production environment. If i upload files named in english characters everything works fine everywhere (localhost and production env).
Note: I have never had a problem with the database (sql) utf-8 characters.

Do anyone know why is this happening in the production environment only?
Thank you.

`// This is my code

sc_api_download([
'settings' => [
'gateway' => 'dropbox',
'api_key' => {apikey},
'api_secret' => {apisecret},
'access_token' => {accesstoken},
],
  'file' => $usersFile,
  'destination' => tmp/files/,
]);

// At the end of the script the framework itself is doing the execution (uploading the file)`

Linking two iteration loops in WordPress (edited)

I had previously asked this question in the following link, but I did not get any answer:

enter link description here

This time I edited my question so that you can better understand what I mean.

I’m going to use a slider that consists of two parts on my wordpress site and on my single product page.

For this purpose, I need to use two repetition loops to call the desired product in the slider.

I used a normal repeat loop that I have used a lot in my website design for this slider, which works correctly, and my only problem is that the two slides do not match, which can be seen in the image of the previous question.

Is there a way to make both loops call the same product at the same time?

The very simplified code of the slider along with the repeating loop that I have used is as follows:

<div class="slider-main">
        <div class="mini-slide">

            <ul>


            <?php
        $args = array(
          'post_type' => 'product',
          'posts_per_page' => '-1',
          'offset' => 0,
          'order' => 'DESC',
          'post_status' => 'publish',
        );
        $my_query = new WP_Query( $args );
        while ( $my_query->have_posts() ):
          $my_query->the_post();
        $do_not_duplicate = $post->ID;
        ?>

                <li>
                    <a class="mini-slide_img" href="<?php echo get_the_post_thumbnail_url( $post->ID ); ?>"></a>
                </li>

                <?php endwhile; wp_reset_postdata(); ?>

            </ul>

        </div>

        <div class="max-slide">

           <ul>

           <?php
        $args = array(
          'post_type' => 'product',
          'posts_per_page' => '-1',
          'offset' => 0,
          'order' => 'DESC',
          'post_status' => 'publish',
        );
        $my_query = new WP_Query( $args );
        while ( $my_query->have_posts() ):
          $my_query->the_post();
        $do_not_duplicate = $post->ID;
        ?>

              <li>
                <a class="max-slide_img" href="<?php echo get_the_post_thumbnail_url( $post->ID ); ?>"></a>
              </li>

         <?php endwhile; wp_reset_postdata(); ?>

           </ul>

          
        </div>

    </div>

PHP best way to store multiple user database passwords

My app stores data in a mysql database called mainDatabase that is accessed using credentials in a config.php. For example:

$mainDatabaseUsername = "abc";
$mainDatabasePassword = "123";

There are 5 admin accounts on the app that each have their own clients to manage. For data segregation requirements, each admin’s clients must be stored in a separate database with a unique username and password. This requires 5 more usernames and passwords, for example:

//Admin1 (database called databaseAdmin1)
$userNameAdmin1 = "admin1";
$pwdAdmin1 = "...";

//Admin2 (database called databaseAdmin2)
$userNameAdmin2 = "admin2";
$pwdAdmin2 = "...";

...

//Admin5 (database called databaseAdmin5)
$userNameAdmin5 = "admin5";
$pwdAdmin5 = "...";

What is the best practice for storing the passwords for each admin database?

Some possible solutions:

  • Add the 5 passwords directly to the config.php file with no encryption
  • Store the passwords in mainDatabase in a new mySql table (with no encryption)
  • Store the passwords in mainDatabase in a new mySql table (with some kind of salt or encryption that I can decode later when I access the client database)

Please note – here in this example, there are 5 admin users. In reality their are likely to be 20 rising to 50.

Thank you