php append pdf to pdf and check the page template first

i have a form where people can upload pdfs

with fpdf I append those pdf and generate a new one.
this works ok, unless someone uploads a vertical aligned pdf.
is there a way I can determine which alignment a pdf has?
this is my code to append:

/* APPEND PDFs */
    $files = [];
    array_push($files, $upload_folder . '/' . $pdf_name);
    if($new_path != 0 & $ext == 'pdf'){
        array_push($files, $new_path);
    }
    if($new_path1 != 0  & $ext1 == 'pdf'){
        array_push($files, $new_path1);
    }
    if($new_path2 != 0  & $ext2 == 'pdf'){
        array_push($files, $new_path2);
    }
    if($new_path3 != 0  & $ext3 == 'pdf'){
        array_push($files, $new_path3);
    }
    if($new_path4 != 0  & $ext4 == 'pdf'){
        array_push($files, $new_path4);
    }
    if($new_path5 != 0 & $ext5 == 'pdf'){
        array_push($files, $new_path5);
    }
    if($new_path6 != 0  & $ext6 == 'pdf'){
        array_push($files, $new_path6);
    }

pdf = new setasignFpdiFpdi();

// iterate over array of files and merge
foreach ($files as $file) {
    $pageCount = $pdf->setSourceFile($file);
    for ($i = 0; $i < $pageCount; $i++) {
        $tpl = $pdf->importPage($i + 1, '/MediaBox');
        $pdf->addPage();
        $pdf->useTemplate($tpl);
    }
}

// output the pdf as a file (http://www.fpdf.org/en/doc/output.htm)
$pdf->Output('F',$upload_folder . '/' . $pdf_name);

thanks a lot

shortcode for product tags description in WooCommerce

I am looking for a way to call the product tags description as a shortcode which could then be added in page builder like elementor. hope to get help here to solve my problem.

I found this snippet but it shows on shop page not on product tag pages

add_action( 'woocommerce_after_shop_loop_item', woocommerce_product_loop_tags', 5 );

function woocommerce_product_loop_tags() {

global $post, $product;

$tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );

echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' );
}

Foreign keys not saved when trying to store data Laravel 8

I am trying to store store an author and genre into a Book. The way I’m trying to achieve this is by having an Author table, Genre table and a Book table. I want to store the foreign key for the author and genre into the books table.

I have created a form to store the needed information for the book. Within the form, there are two select tags and within them I loop through the authors and genres array. I use a store function in my BookController to validate the data that is being sent. After the validation, I store a new Book.

However, the foreign keys are not being stored in the database except for the primary key, title, blurb and timestamps.

Book Model

class Book extends Model
{
    use HasFactory;

    protected $fillable = [
        'author_id',
        'genre_id',
        'title',
        'blurb',
    ];

    public function authors()
    {
        return $this->BelongsTo(Author::class);
    }

    public function genres()
    {
        return $this->BelongsTo(Genre::class);
    }
}

Author Model

class Author extends Model
{
    use HasFactory;

    protected $fillable = [
      'name',
    ];

    public function book()
    {
        return $this->hasMany(Book::class);
    }
}

Genre Model

class Genre extends Model
{
    use HasFactory;

    protected $fillable = [
        'title'
    ];

    public function book()
    {
        return $this->hasMany(Book::class);
    }
}

BookController create()

    public function create()
    {
        $authors = Author::all();
        $genres = Genre::all();

        return view('admin.book.create', ['authors' => $authors, 'genres' => $genres]);
    }

BookController store()

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'authors' => 'required|array',
            'genres' => 'required|array',
            'blurb' => 'required',
        ]);

        Book::create($validatedData);

        return redirect()->route('admin.book.create');
    }

Books table migration

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->foreignId('author_id');
            $table->foreignId('genre_id');
            $table->string('title');
            $table->string('blurb');
            $table->timestamps();
        });
    }

create.blade.php (create Book page)

    <div class="flex justify-center">
        <div class="flex justify-center border lg:w-1/4">
            <div class="flex flex-col justify-center lg:w-2/4 gap-2">
                <form action="{{ route('admin.book.store') }}" method="post">
                    @csrf
                    <div class="mb-2">
                        <h1 class="text-xl">Add Book</h1>
                    </div>
                    <div>
                        <label class="" for="title">Title</label>
                        <input name="title" class="w-10 border border-gray-400 w-full py-1 px-2" type="text">
                    </div>
                    <div>
                        <label class="" for="author">Author</label>
                        <select name="authors[]">
                            @foreach($authors as $author)
                                <option value="{{ $author->id }}">{{ $author->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label class="" for="genre">Genre</label>
                        <select name="genres[]">
                            @foreach($genres as $genre)
                                <option value="{{ $genre->id }}">{{ $genre->title }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label class="" for="blurb">Blurb</label>
                        <textarea name="blurb" id="" cols="18" rows="10"></textarea>
                    </div>
                    <div>
                        <button class="py-2 px-4 border" type="submit">Save</button>
                    </div>
                </form>
            </div>

        </div>
    </div>

Auto import booking.com not working motopress

i have a problem with sync callendar in plugin motopress booking with bookin.com.
Automatic import works very well on the plugin, however it does not automatically import the booking.com calendar
Is it possible to perform an automatic import?

How to return only English value data from JSON

Ihave these data in json format i want to get only Engish value Data seperate. Like only need english data: (Center Bore (mm) : 66.6, Offset (mm) : 45, OEM Compatible : Yes).

I also try to decode data and seperate all data friquently but not get perfact result.

attributes: [
            {
                "thibertPartNumber": "081019",
                "attributeID": "ID_114",
                "attributeNames": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "Center Bore (mm)"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "Alésage (mm)"
                    }
                ],
                "attributeValues": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "66.6"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "66.6"
                    }
                ]
            },
            {
                "thibertPartNumber": "081019",
                "attributeID": "ID_115",
                "attributeNames": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "Offset (mm)"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "Décalage (mm)"
                    }
                ],
                "attributeValues": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "45"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "45"
                    }
                ]
            },
            {
                "thibertPartNumber": "081019",
                "attributeID": "ID_122",
                "attributeNames": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "OEM Compatible"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "EOM Compatible"
                    }
                ],
                "attributeValues": [
                    {
                        "languageCode": "EN",
                        "localizedValue": "Yes"
                    },
                    {
                        "languageCode": "FR",
                        "localizedValue": "Oui"
                    }
                ]
            },
] 

And i want output to be:

Center Bore (mm) : 66.6
Offset (mm) : 45
OEM Compatible : Yes

Forwarding to profileurl

I use WordPress / Peepso / Buddypress. I want to build a redirect on the user profile.

example domain.tld / redirect

Now I need a PHP code that reads the profilurl and then redirects the user to the profile.

I have this piece of code

<? php echo $ user-> get_profileurl ();?>

anyone any idea? Thanks!

PHP AJAX – Uncaught PDOException: SQLSTATE[HY093], what is this?

I looked around stackoverflow, there are lots of this kind of question. But I can’t seem to find what is missing in the code.

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:xampphtdocsbackendcasestraffictraffic-insert.php:95 Stack trace: #0 C:xampphtdocsbackendcasestraffictraffic-insert.php(95): PDOStatement->execute(Array) #1 C:xampphtdocsrouter.php(51): include_once('C:\xampp\htdocs...') #2 C:xampphtdocsrouter.php(9): route('/traffic-insert', '/backend/cases/...') #3 C:xampphtdocsroutes.php(24): post('/traffic-insert', '/backend/cases/...') #4 {main} thrown in C:xampphtdocsbackendcasestraffictraffic-insert.php on line 95

This error came after solving this:
PHP AJAX – data update/edit inserts as new data instead of updating

Here is the code:

<?php

include('./backend/config/connection.php');
include('./backend/config/function.php');

   if( isset($_POST["traffic_operation"]) ) {
       if( isset($_POST["traffic_operation"]) == "Add" ) {
              $traffic_doc = '';
       
              if( $_FILES["traffic_doc"]["name"] != '') {
                     $traffic_doc = upload_image();
              }
              $statement = $connection->prepare('INSERT INTO traffic_violations (
                     plateNumber,
                     carModel,
                     carColor,
                     violationType,
                     ownerGender,
                     violationDateTime,
                     violationLocation,
                     workingShift,
                     violationAction,
                     violationStatement,
                     cccEmployee
              ) VALUES (
                     :plate_number,
                     :car_model,
                     :car_color,
                     :violation_type,
                     :owner_gender,
                     :violation_date,
                     :violation_location,
                     :working_shift,
                     :violation_action,
                     :traffic_doc,
                     :ccc_employee
                     )
              ');
              $result = $statement->execute(
                     array(
                            ':plate_number' => $_POST["plate_number"],
                            ':car_model' => $_POST["car_model"],
                            ':car_color' => $_POST["car_color"],
                            ':violation_type' => $_POST["violation_type"],
                            ':owner_gender' => $_POST['owner_gender'],
                            ':violation_date' => $_POST['violation_date'],
                            ':violation_location' => $_POST['violation_location'],
                            ':working_shift' => $_POST['working_shift'],
                            ':violation_action' => $_POST['violation_action'],
                            ':traffic_doc' => $traffic_doc,
                            ':ccc_employee' => $_POST['ccc_employee']
                     )
              );
                     if( !empty($result) ) {
                            echo '<script>alert("Traffic Violation Added")</script>';
                     }
       }

       if( $_POST["traffic_operation"] == "Edit" ) {
              $traffic_doc = '';

              if( $_FILES["traffic_doc"]["name"] != '') {
                     $traffic_doc = upload_image();
              } else {
                     $traffic_doc = $_POST['hidden_user_image'];
              }

              $statement = $connection->prepare('UPDATE traffic_violations SET
                     plateNumber = :plate_number,
                     carModel = car_model,
                     carColor = car_color,
                     violationType = violation_type,
                     ownerGender = owner_gender,
                     violationDateTime = violation_date,
                     violationLocation = violation_location,
                     workingShift = working_shift,
                     violationAction = violation_action,
                     violationStatement = traffic_doc,
                     cccEmployee = ccc_employee,
                     WHERE id = :id'
                     );
                     $statement->execute(
                            array(
                                   'id' => $_POST["violation_id"],
                                   ':plate_number' => $_POST["plate_number"],
                                   ':car_model' => $_POST["car_model"],
                                   ':car_color' => $_POST["car_color"],
                                   ':violation_type' => $_POST["violation_type"],
                                   ':owner_gender' => $_POST['owner_gender'],
                                   ':violation_date' => $_POST['violation_date'],
                                   ':violation_location' => $_POST['violation_location'],
                                   ':working_shift' => $_POST['working_shift'],
                                   ':violation_action' => $_POST['violation_action'],
                                   ':traffic_doc' => $traffic_doc,
                                   ':ccc_employee' => $_POST['ccc_employee']
                            )
                     );
                     echo 'Traffic Violation Updated';
       }
   }
?>

Symfony – migration update set to null if empty

I want to update every field in a specific table when running a migration that if it is '' to be updated with NULL.

I have set one of the fields in db to '' so I can test it.

I am getting an error when running that specific migration:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘DoctrineMigrationsVersion20211129141541’ for key ‘PRIMARY’

And my migration file:

    final class Version20211129141541 extends AbstractMigration
{
    public function getDescription(): string
    {
        return '';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('UPDATE post SET context=NULL WHERE context=""');
        $this->addSql('UPDATE post SET info=NULL WHERE info=""');
    }

    public function down(Schema $schema): void
    {

    }
}

Is this anyway the right approach?

Dynamic redirect from header.php

I have a structure like this:

myproject
    layout
        header.php
    user
        user.php
    index.php
    login.php
    logout.php

header.php is included in both index.php and user.php

index.php include code:

require_once(__DIR__ . 'layoutheader.php'); 

user.php include code:

require_once(__DIR__ . '..layoutheader.php');     

In header.php I check if the user is logged in. If not logged in, The user is redirected to login.php:

if(!logged_in()){
    header('Location: ./login.php');
}

This works fine, If I visit index.php. But not working with user.php, As the URL becomes /user/login.php which doesn’t exist.

And I can’t change header('Location: ./login.php'); to header('Location: ../login.php');, Because it won’t work with index.php.

So how to make this dynamic or make the header.php directory the place where it goes back from?

How to match the SESSION username with the written username?

So I’m creating this test Website and I’m trying to make an edit profile page by user and I want to make the username unchangeble and the user is only able to edit thier profile if they type in thier username in editprofileHTML.php I have this input:

<input type="text" class="form-control" id="username" name="username" value="<?php echo  $username; ?>">

I tried to make it disabled but it didn’t work.

editprofile.inc.php:

 $updatedData = [
    "firstname" => $_POST["firstname"],
    "lastname" => $_POST["lastname"],
    "phoneNr" => $_POST["phoneNr"],
    "username" => $_POST["username"],
    "gender" => $_POST["gender"],
];

if (matchingUsername($updatedData["username"]) === true) {
    $error = '<p class="error" > Please write your Username correctly </p>';
}
updateUser($updatedData);

$_SESSION["loggedInUser"] = loadUserByUsername($_POST["username"]);
header('Location: ../profile.php');
}

And I also have these functions:

function updateUser($updatedData) {
    $dataToUpdate = [];
    foreach ($updatedData as $key => $value) {
        if ($updatedData[$key] !== "" ) {
            $dataToUpdate[$key] = $value;
        }
    }
if (!empty($dataToUpdate)) {
    $sql = 'UPDATE login SET ';
    $arrayLength = count($dataToUpdate);
    $i = 0;
    foreach ($dataToUpdate as $key => $value) {
        $sql .= $key . ' = "'.$value.'"';
        if (++$i !== $arrayLength) {
            $sql .= ', ';
        }
    }
    $sql .= ' WHERE username = "'.$updatedData["username"].'"';
    global $conn;
    $conn->query($sql);

    if ($conn->error){
        throw new Exception("Error updating user: " . $conn->error);
    }
}

function matchingUsername($username) {
    $user = loadUserByUsername($username);
    if ($username === $user) {
        return true;
    } return false;
}
function invalidUsername($username) {
    $user = loadUserByUsername($username);
    if (!empty($user)) {
        return true;
    }
}
function loadUserByUsername($username) {
global $conn;
$sql = 'SELECT * FROM login WHERE username = "'.$username.'"';
$result = $conn->query($sql);

return $result->fetch_assoc();
}

Laravel mix issue: datepicker does not work

The datepicker works on my bootstrap folder. However, when I move everything into laravel, it does not work. I don’t really understand that how css and js work in laravel, so that is why I am here :).

/resources/sass/app.scss

//css
@import url('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css');

//js
@import url('https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js');
@import url('https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js');
@import url('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js');

              <!--DatePicker-->
              <div class="col-md-4">
                <h4 class="">Prefer Date</h3>
                <form>
                    <div class="">
                        <!-- <label for="date" class="col-sm-1 col-form-label">Date</label> -->
                        <div class="">
                            <div class="input-group date" id="datepicker">
                                <input type="text" class="form-control">
                                <span class="input-group-append">
                                    <span class="input-group-text bg-white">
                                        <i class="fa fa-calendar"></i>
                                    </span>
                                </span>
                            </div>
                        </div>
                    </div>
                </form>
              </div>
              <script type="text/javascript">
                $(function() {
                    $('#datepicker').datepicker();
              });
              </script>

Error SQLSTATE[HY093]: Invalid parameter number: in php PDO statement

im a newbie in php and im facing this problem…i get with it 3 days and im going mad… ;). Im trying to implement a table with users of a web application. So i have to check that the user doesnt exist.

My sql table:

DROP TABLE users;
CREATE TABLE users (
    idUser INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    mail VARCHAR(45) NOT NULL UNIQUE,
    name VARCHAR(45) NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    role enum ("admin", "user"), 
    state BOOLEAN,
    forgotpass VARCHAR(32) NOT NULL
);

Also this code works ( test if the user already exists in the table):

//$query="SELECT mail FROM proba.users WHERE mail='{$correu}'";
   $sql = 'SELECT  * FROM users WHERE mail = :mailparam';
    //$sql = 'SELECT  * FROM users';
    $stmt = $con->prepare($sql);

  // 2. execute to insert a row 
  // with an associative array
  $stmt->execute(
      array(':mailparam'=>$correuFormulari)
      );

  // 3. get all rows
  $rows = $stmt->fetchAll();
  foreach ($rows as $rowActual) {
    echo $rowActual['mail'] . "<br>";
   echo $rowActual['password'] . "<br>";
 }

But following the same logic i cant insert an element:

 if(count($rows) > 0){

        echo "L'usuari ja existeix";
        echo "<p><a href='registreUsuari.php'>Torna</a></p>";

    } else{
        echo "Usuari no trobat. Passem a insertar";
        //INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES ("[email protected]", "pepe","user", "pepito", current_Time,"forgotpass");
        $user="admin";
        $sqlinsert = 'INSERT INTO users (mail, password, role, name,forgotpass) VALUES (:mail, :passwordform,:usuari, :nomFormulari,:forgotpass)';
    //$sql = 'SELECT  * FROM users';
        $stmtinsertar = $con->prepare($sqlinsert);
       // $stmt = $con->prepare("INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES (:mail, :password,:user, :nomFormulari, :data,:forgotpass)");
      /*  $stmtinsertar->bindParam(':mail', $correuFormulari);
        $stmtinsertar->bindParam(':password', $passwordFormulari);
        $stmtinsertar->bindParam(':user', $user);
        $stmtinsertar->bindParam(':nomFormulari', $nomFormulari);
        //$stmt->bindParam(':data', $data);
        $stmtinsertar->bindParam(':forgotpass', "forgotpass");

        INSERT INTO users (mail, password, role, name,forgotpass) VALUES ("hola@g,aoñ", "pepe","user", "pedro","forgot")
        */
        try
            { 
                //$stmtinsertar->execute();
                $stmt->execute(
                    array(':mail'=> "$correuFormulari",
                    ':passwordform'=>  "$passwordFormulari",
                    ':usuari'=>  "$user",
                    ':nomFormulari'=> "$nomFormulari",
                    ':forgotpass'=> "forgotpass")
                    );
            }
        catch(PDOException $e)
        {
            handle_sql_errors($selectQuery, $e->getMessage());
        }
        

        echo "S'ha creat l'usuari";
        //header('Location: '.'login.php');

//        $stmt->close();
       

    }  

I enter in the correct if, but i cant insert into the table….
The error shows something like:

[email protected] : object(PDO)#2 (0) { } hoola0Usuari no trobat. Passem a insertar

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

As you can read in the code i also tried to use bind->Params….

Any help would be apreciated.

Also would like to know, which form of executing PDO is preferred, using bindParameter or using an array.

Thanks in advance