I want to save an client-created string on an apache2 website

I recently set up an apache2-server for a schoolproject I’m working on. I would like the user to be able, to save a variable directly onto the website, therefore altering this part of the website forever or until the user changes it again. I know Python3, html, php and a bit of js. I realize, the information I gave you is not necessarily enough to really understand what I mean, but I am open to further questions. Help would be greatly appreciated, due to the project being due in a week from now, with extra extra-work still unfinished.
Thanks in advance,
NotSoRealApache

PHP – Compare array and output found values

i have a problem trying to get some functionality to work in PHP which i am sadly not very fond of. I tried reading and wrapping my head around it but i guess i am just to unexperienced to find the correct solution myself. I was hoping that you could point me into the right direction.

The issue:

We have an image folder full of product pictures. Their naming conventions are like this :

  • EK016_9BL_P_1
  • EK016_9BL_P_2
  • EK016_9BL_P_3
  • EK016_I1T_P_1
  • EK016_I1T_P_3
  • EK022_GKC_P_1
  • EK022_GKC_P_2

and so on….

So first what i did to get a list of all the images in the folder is the following :

<?php

$dir = "C:/img";
$files = scandir($dir);
$shortcodes = [];

echo "<table>";

foreach ($files as $file){

// Trim the filename of "_-." so only the main product code remains for comparison
$trimmed= strtok($file, '_-.');

// Push cleaned filenames to a new array
array_push($shortcodes, $trimmed);

// Make each value unique so it doesn't repeat like 5x "EK016" etc
$filtered = array_unique($shortcodes);
}

foreach ($filtered as $shortArtCode) {
    echo 
        "<tr>
            <td>$shortArtCode</td>
        </tr>";
}
    
echo "</table>";

?>

This works so far – probably not the most elegant solution but it outputs the above example list but only the main product code (everything before the _) so for example, it lists unique values like

  • EK016
  • EK018
  • EK019
  • EK022

Now that i have separated the “Main Article Code” from the file list, i want to assign the images in the folder to its respective product code, so the output would look like :

  • EK016 => EK016_9BL_P_1.jpg

  •   => EK016_9BL_P_2.jpg
    
  •   => EK016_9BL_P_3.jpg
    
  •   => EK016_9BL_P_4.jpg
    
  • EK018 => EK018_2BY_P_1.jpg

  •   => EK018_2BY_P_2.jpg
    
  •   => EK018_2BY_P_3.jpg
    

of course, based on the existing files in the folder that match the “Product Code”.

I have tried “in_array” comparisons, and string comparisons but with no luck since I probably need to do everything in the same loop to get proper results. Does anyone have an idea what could be done to make this quick and dirty or maybe a completely different approach I haven’t thought of?

appreciate your help 🙂

HTML: getting selected datalist option value, and innerHTML, without using Jquerys

I have a situation where I want to let a user decide titles of books that I have on my db, using an input with a datalist (generated by php), after the user picked a title, he would click a submit button and the form would send the title in another file.

Everything worked fine but I didn’t realized that I needed to send the ID of the book that the user selected, because there can be more than one book with the same title.

What I would like to have is the option of the datalist, that no longer has the title of the book inside its “value” attribute, but I want that title inside its innerHTML, so that the title gets displayed, while having the ID inside the “value” attribute. My problem is that if I do that, when the user clicks on the datalist option, the ID gets inside the text input, so the user may not know what book he choose.

summing up: I would like to have the datalist that displays the title, when an option is chosen, that title gets displayed in the text input, when I submit, the Id of the book gets sent in “FindBook.php” inside $_POST.

isIn() checks if the title is inside the array of titles, I would need to change that so that it can check if the ID is inside the array of IDs.

before


   <form onsubmit="return isIn(document.getElementById('book').value);" action="FindBook.php" target="_blank" method="POST">
      <input id="libro" name="bookTitle" list="books" autocomplete="off" style="width: 200px;">
      <input type="submit" value="Find Book">
    </form>
...
   <datalist id="books">
    <? foreach ($books as $row) { ?>
      <option value="<? echo $row["title"]; ?>"></option>
    <? }; ?>
  </datalist>


after

   <form onsubmit="return isIn(*id of the book*);" action="FindBook.php" target="_blank" method="POST">
      <input id="libro" name="bookTitle" list="books" autocomplete="off" style="width: 200px;">
      <input type="submit" value="Find Book">
    </form>
...
  <datalist id="books">
    <? foreach ($books as $row) { ?>
      <option value="<? echo $row["id"]; ?>"><? echo $row["title"]; ?></option>
    <? }; ?>
  </datalist>


Since I don’t understand JQuerys i would really prefer a solution that doesn’t imply that.
Sorry for my bad english, let me know if I need to clarify something.

Html auto writes =”” after an attribute with php

Well, I’ve been trying to put a “required” attribute in an html text input with php but I can`t.
I’ve a php function that creates automatically a form with all the data you give to it, but that is not the problem.
The problem is that I’ve a boolean parameter in which you choose if some of the inputs are required or not, and when one of them is true, the input must have the “required” attribute on it.
Something like…

function make_form(..., $required,...) {
   ...
   echo "<input type='...' name='...' value='...' ".($required?"required":"").">";
   ...
}

What I want is that when the $required variable is true, the input has “required” on it, but instead, this is what the server sends to the client:

<input type='...' name='...' value='...' required="">

And I don’t want those =”” after the “required” cause then it doesn’t validate that the input is not empty.
I want this:

<input type'...' name='...' value='...' required>

Without the =””

I’ve tried using htmlentities(“required”), htmlspecialchars(“required”), adding an &nbsp after the “required”, using print instead of echo, using a variable instead of plain text, changing the position of the “required” inside the tag, etc. and the =”” still appears.
I hope you can help me; I’m using php 8.
Thank you very much.

submit form dependent dropdown to a table and show in the table the name instead of id issue

Hello stackoverflow community, i have a doubt on how to do this:
-im making a country city state like , dependent dropdown, and im trying to insert into a table in database the form submission.. i’m having an issue on how to submit into the table, the country_name. i have the following in the php form (alredy submitting the id’s instead of names of the countries:

<form method="POST" action="">
<div class="form-group">
<label for="distrito">Distrito</label>
<select class="form-control" name="distrito" id="distrito_name">
<option value="">Seleccione o distrito</option>
<?php
require_once "db.php";
$result = mysqli_query($conn,"SELECT * FROM distrito");
while($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row["distrito_name"];?></option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="concelho">Seleccione o concelho</label>
<select class="form-control" name="concelho" id="concelho_name">
</select>
</div>                        
<div class="form-group">
<label for="freguesia">Freguesia</label>
<select class="form-control" name="freguesia" id="freguesia_name">
</select>
</div>
</div>
</div>
</div>
</div> 
</div>
<script>
$(document).ready(function() {
$('#distrito_name').on('change', function() {
var distrito_id = this.value;
$.ajax({
url: "concelho-by-distrito.php",
type: "POST",
data: {
distrito_id: distrito_id
},
cache: false,
success: function(result){
$("#concelho_name").html(result);
$('#freguesia_name').html('<option value="">Seleccione o concelho primeiro</option>'); 
}
});
});    
$('#concelho_name').on('change', function() {
var concelho_id = this.value;
$.ajax({
url: "freguesia-by-concelho.php",
type: "POST",
data: {
concelho_id: concelho_id
},
cache: false,
success: function(result){
$("#freguesia_name").html(result);
}
});
});
});
</script>
<button type="submit" name="submit" class="btn btn-primary">Save Event</button>

and i have the following in the data submission code wich is in a separate page: the connection to the database and this:

<?php
  if (isset($_REQUEST['distrito_id'])) {
    $i=implode(',', $_REQUEST['distrito_id']);
      $query = "SELECT distrito_name FROM distrito where id IN ($i)";
$result = $db_name->query($query);
if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo $row["distrito_name"]."<br>";
  }
} else {
  echo "0 results";
}
$db_name->close();
 }

?> 
<?php
if(isset($_POST['submit']))
{
 
$distrito = $_POST['distrito']; 
$query = "INSERT INTO table (distrito) VALUES '$distrito' 
$query_run = mysqli_query($con, $query);
}

if someone can, please help me make this, thanks in advance

PHPUnit – test query func

I have part of the php code I am writing test for:

$_image_file = db_get_field('SELECT image_path FROM ?:images WHERE image_id = ?i', $image_id);

When duping it, it return: image_1.jpg

And I want to write it in PHPUnit test:

FunctionMocker::replace('db_get_field', function () {
        return FnImagesFunctionsTest::$functions->db_get_field();
    });

    self::$functions
        ->shouldReceive('db_get_field')
        ->times(2)
        ->andReturn('image_1.jpg');

Which is okay, but I want to call it with sql call as I have multiple db_get_field methods with different sql queries.

So, like ->withArgs('SELCET ...', $image_id = 190)

Can someone please help, I am new with PHPUnit tests..

Thanks

Create an appointment in Zimbra calendar using IMAP PHP library

I would like to create an appointment in my Zimbra calendar using IMAP. The final goal would be to create a cron job that doing it recurrently but for the moment I only managed to connect to the server and now I’m stuck here :


    <?php
    
    $server_host = '{zimbra:7143/imap/novalidate-cert}';
    $server_username = '[email protected]';
    $server_password = 'mypassword';
    
    $imap = imap_open($server_host, $server_username, $server_password);
    
    if ($imap) 
    {
        //create an appointment
    } 

    ?>

I’ve searched through the whole internet there is no IMAP function in PHP to do that, I’ve only found out some Zimbra API on git which could do this but I need to use IMAP.

Can’t attach an EventlLstener to a form in jquery/php

I stuck with a problem for almost one week now.
I’m working on a website that allow people to check the availability of vehicle spare parts and order them if available.
for that, the user has to select the make then the model, then the year and submit the request, the application tells whenever it’s available or not and displays the form for preordering.
Until here nothing special.
i use jquery.post() method to send elements to a backend.php file and to generate the form regarding those elements without refreshing the page.
Every thing work fine except for my last form, I’m not able to add an eventlistener (onSubmit) …
Could someone help please !!
Here’s my code:

  1. jquery
$(".form").on("submit", function(e) {
                e.preventDefault();
                var marque = $("#marque").val();
                var model = $("#model").val();
                var year = $("#year").val();
                if (typeof year != "undefined") {
                    year = year;
                } else {
                    year = "0";
                }

                $.post("backEnd.php", {
                    "references": [marque, model, year]
                }, function(data5) {
                    $(".result").html(data5);
                    $('html,body').animate({
                        scrollTop: $(".result").offset().top
                    }, 'slow')
                })
            })

            $("#mail_form").on("submit", function(e) {
                e.preventDefault();
                alert("test");
            })
  1. backend.php
if (isset($_POST["references"])) {
    $marque = $_POST["references"][0];
    $model = $_POST["references"][1];
    $year = $_POST["references"][2];

    $req = $connexion->prepare("SELECT * FROM suspension WHERE marque = ? AND model = ? AND year_range = ?");
    $req->execute(array($marque, $model, $year));
    $results = $req->fetchAll();

    $front = $results[0]["front"] + $results[0]["both_sides"];
    $rear = $results[0]["rear"] + $results[0]["both_sides"];
    $modelYear = ($year != "0") ? " - modèle " . $year : "";

    $message1 = ($front > 0) ? "<span>Disponibles</span>" : "Non disponible";
    $message2 = ($rear > 0) ? "<span>Disponibles</span>" : "Non disponible";
?>
    <h2 class="main_result_title"><?php echo $marque . " - " . $model . $modelYear . " :"; ?></h2>
    <h3 class="main_result_subtitle"><?php echo "Amortisseurs Avants : " . $message1; ?></h3>
    <h3 class="main_result_subtitle"><?php echo "Amortisseurs Arrières : " . $message2; ?></h3>

    <p class="main_result_text">Vos amortisseurs sont disponibles chez <span>Algérie Pièces</span>, pour avoir plus de détails ou pour une précommande, utilisez le formulaire de contact ci-dessous pour nous contacter, un agent commercial prendra attache avec vous très rapidement pour vous prendre en charge</p>

    <div class="form2">
        <form action="" method="post" id="mail_form">
            <input type="text" name="id" id="ref" value="<?= $results[0]['id']; ?>" hidden="true">

            <label for="user_name">Vos noms et prénoms <small style="font-style: italic">(obligatoire)</small>
                : </label><input type="text" name="user_name" id="user_name" placeholder="Nom et prénom" required><br />

            <label for="user_mail">Votre Adresse mail : </label><input type="email" inputmode="email" name="user_mail" id="user_mail" placeholder="Adresse mail"><br />

            <label for="user_tel">Votre numéro de téléphone : </label><input type="tel" name="user_tel" id="user_tel" placeholder="Numéro de téléphone" inputmode="tel"><br />

            <label for="user_msg">Message <small style="font-style: italic">(facultatif)</small> :
            </label><textarea name="user_msg" id="user_msg" cols="30" rows="10" placeholder="Remarque ou besoin d'informations supplémentaires"></textarea><br />

            <div class="buttons2" style="text-align: right">
                <input type="submit" value="Envoyer" class="btn2" />
                <input type="reset" value="Effacer" class="btn2" />
            </div>
        </form>
        <div class="state_message"></div>
    </div>


<?php
}

the function works fine, everything is ok except the last eventlistener

Multitenant View bookings for external users

I can only seem to view bookings for users in my group.

When I try create an access token for a user external with a Microsoft account, I can’t access it using “users/[email protected]” but when I change it back to “users/[email protected]” it starts working?

I have enabled multitenant in settings. Is the problem with the token?

How I generate token

 $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'scope' => 'https://graph.microsoft.com/.default',
            'client_id' => '####################',
            'client_secret' => '###################',
            'grant_type' => 'client_credentials',
        ],
    ])->getBody()->getContents());

press + to active input text label field in form

i have normal form like this :

<form class='modal-content animate' action='' method='post'>

Goods name : <input type='text' name='goods-name' style='width:100%; height: 40px; ' autocomplete='off'> <br>

Goods count : <input type='text' name='goods-count' style='width:100%; height: 40px; ' autocomplete='off'>

</form>

i need : – if i press key (+) any where on page active the label of goods name to write . thanx

Sql list unregistered classroom

There is one student. This student is enrolling in classes. What I want is to list the classes where this student is not registered. My SQL query is like this, where am I going wrong?

SELECT * FROM class, userClass WHERE class.id <> userClass.class AND userClass.user<>$userid

Not being able to get data from an API in Javascript

I wrote an API that has manages a database, and that on get requests it has to send a JSON file with the data from the database. Also, from the frontend I want to call this API using fetch(), but I get a null response. What should I do?

The api code:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    
    include_once '../Model/database.php';
    include_once '../Model/verifiedEvents.php';

    $db = new database();
    $event = new verifiedEvents();

    $result = $event->read();
    $count = $result->num_rows; 
    if ($count > 0){
        $outputArray = array();
        while($row = $result->fetch_assoc()){
            array_push($outputArray, $row);
        }
        echo json_encode($outputArray);
    } else {
        echo json_encode(
          array('message' => 'No events found')
        );
    }

?>

The clientside Javascript code:

const events_api_url = 'http://localhost/Proiect/API/getVerifiedEvents.php';
            const user_locations_api_url = 'http://localhost/Proiect/API/getUserLocations.php';
            
            async function getEvents(){
                const response = await fetch(events_api_url, {method: 'GET', mode: 'cors', cache: 'default', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}});
                console.log(response);  
                const data = await response.json;
                console.log(data);  
                const {description, title, longitude, latitude} = data;
                console.log(description);
                console.log(title);
                console.log(longitude);
                console.log(latitude);
                console.log(" ");
            }
            getEvents();

PHP giving specific item access to admins

So I have this food ordering system where each admin uploads his or her food from the backend and users can browse through those food from the frontend, a simple program. But what I want is that an admin should not be able to view or update the food from another admin as right now any of the admins can view and update all the food that are uploaded on the backend. What I want is only a specific admin only viewing and updating his or her added food items.
Attached below is the snippet and picture of the food view and update page where it displays all foods and can update them.
FYI the code is in PHP and the backend is SQL in phpMyAdmin
Please do let me if there are any confusions in my explanation.

<?php include('partials/menu.php'); ?>

<div class="main-content">
    <div class="wrapper">
        <h1>Manage Food</h1>

        <br /><br />

                <!-- Button to Add Admin -->
                <a href="<?php echo SITEURL; ?>admin/add-food.php" class="btn-primary">Add Food</a>

                <br /><br /><br />

                <?php 
                    if(isset($_SESSION['add']))
                    {
                        echo $_SESSION['add'];
                        unset($_SESSION['add']);
                    }

                    if(isset($_SESSION['delete']))
                    {
                        echo $_SESSION['delete'];
                        unset($_SESSION['delete']);
                    }

                    if(isset($_SESSION['upload']))
                    {
                        echo $_SESSION['upload'];
                        unset($_SESSION['upload']);
                    }

                    if(isset($_SESSION['unauthorize']))
                    {
                        echo $_SESSION['unauthorize'];
                        unset($_SESSION['unauthorize']);
                    }

                    if(isset($_SESSION['update']))
                    {
                        echo $_SESSION['update'];
                        unset($_SESSION['update']);
                    }
                
                ?>

                <table class="tbl-full">
                    <tr>
                        <th>S.N.</th>
                        <th>Title</th>
                        <th>Price</th>
                        <th>Image</th>
                        <th>Featured</th>
                        <th>Active</th>
                        <th>Actions</th>
                    </tr>

                    <?php 
                        //Create a SQL Query to Get all the Food
                        $sql = "SELECT * FROM tbl_food";

                        //Execute the qUery
                        $res = mysqli_query($conn, $sql);

                        //Count Rows to check whether we have foods or not
                        $count = mysqli_num_rows($res);

                        //Create Serial Number VAriable and Set Default VAlue as 1
                        $sn=1;

                        if($count>0)
                        {
                            //We have food in Database
                            //Get the Foods from Database and Display
                            while($row=mysqli_fetch_assoc($res))
                            {
                                //get the values from individual columns
                                $id = $row['id'];
                                $title = $row['title'];
                                $price = $row['price'];
                                $image_name = $row['image_name'];
                                $featured = $row['featured'];
                                $active = $row['active'];
                                ?>

                                <tr>
                                    <td><?php echo $sn++; ?>. </td>
                                    <td><?php echo $title; ?></td>
                                    <td>$<?php echo $price; ?></td>
                                    <td>
                                        <?php  
                                            //CHeck whether we have image or not
                                            if($image_name=="")
                                            {
                                                //WE do not have image, DIslpay Error Message
                                                echo "<div class='error'>Image not Added.</div>";
                                            }
                                            else
                                            {
                                                //WE Have Image, Display Image
                                                ?>
                                                <img src="<?php echo SITEURL; ?>images/food/<?php echo $image_name; ?>" width="100px">
                                                <?php
                                            }
                                        ?>
                                    </td>
                                    <td><?php echo $featured; ?></td>
                                    <td><?php echo $active; ?></td>
                                    <td>
                                        <a href="<?php echo SITEURL; ?>admin/update-food.php?id=<?php echo $id; ?>" class="btn-secondary">Update Food</a>
                                        <a href="<?php echo SITEURL; ?>admin/delete-food.php?id=<?php echo $id; ?>&image_name=<?php echo $image_name; ?>" class="btn-danger">Delete Food</a>
                                    </td>
                                </tr>

                                <?php
                            }
                        }
                        else
                        {
                            //Food not Added in Database
                            echo "<tr> <td colspan='7' class='error'> Food not Added Yet. </td> </tr>";
                        }

                    ?>

                    
                </table>
    </div>
    
</div>

<?php include('partials/footer.php'); ?>

Attached is a picture of this
Here

How to fix error: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

Yes. I read about this error a lot of info. Nothing helps me.
My server Ubuntu with Apache2, PHP.
My website has to start a video from video.onnetwork.tv. But I get an error
“Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true”

I updated .htaccess:
Header set Access-Control-Allow-Origin "video.onnetwork.tv"

Same error.

Header set Access-Control-Allow-Origin "https://video.onnetwork.tv"

Same error.

Header set Access-Control-Allow-Origin "onnetwork.tv"

Same error.

Header add Access-Control-Allow-Origin "video.onnetwork.tv"

Same error.

Header add Access-Control-Allow-Origin "video.onnetwork.tv"

Header set Access-Control-Allow-Credentials true

Same error.

SetEnvIf Origin "http(s)?://(.+.)?onnetwork.tv(:d{1,5})?$" CRS=$0

Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS

Header merge Vary "Origin"

Same error.

Apache2 has enabled .htaccess.
headers enabled.

In PHP added
header("Access-Control-Allow-Origin: https://video.onnetwork.tv");

Same error.

Added these settings to apache Virtual Directory, restarted Apache2 – same error.

enter image description here

I don’t know what to do. How I can fix this error?