PHP relative paths

suppose that I am working on a similar server PHP, with more projects, each of them with multiple subfolders and includes. Let’s concentrate on proj1:

/var/www/html
    /proj1
        /inc
            header.php
       /assets
            styles.css
            script.js
        page1.php
        index.php
   /proj2
    ...

Now, I want to include the css and the js with a relative path (not absolute) from header.php, but if I use $_SERVER["DOCUMENT_ROOT"] it returns to /var/www/html.
What do you think it could be the better solution to echo "script.js" in such scenario, without relying on absolute paths?
Thanks

PS: For the sake of clarity, we work on nested directories and structures, so I am searching for a way in which the relative path can change on these different folders, so it needs to be dynamic.

Sort the array with same element at same index PHP

So I have two arrays with some ids. I want to sort the arrays in a way that same value elements in array2 must be at the same index as in array1.
For example:

array1 = ['b','a','c','d'];
array2 = ['d','a','c','b'];

After the sort array2 should become like array1 => ['b','a','c','d']
Is there any function in Php? Thanks in advance 🙂

After sending email to reset password using PHP many info lines appear to user

I am using the code below to send a link to the user email to reset the password, the code works fine and sends the link. The problem is after sending the link the page will show many lines of information and a success message at the end.

What is wrong with the code below to avoid these lines? Here is the code:

<?php
    use PHPMailerPHPMailerPHPMailer;
    use PHPMailerPHPMailerSMTP;
    use PHPMailerPHPMailerException;

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';

    require 'database.php';

    if(isset($_POST["email"])){
        $emailTo = $_POST["email"];

        $code = uniqid(true);
        $sql = "INSERT INTO reset(code, email) VALUES('$code', '$emailTo');";
        $run = mysqli_query($conn, $sql);
        if(!$run){
            exit("Error");
        }

        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->isSMTP();
            $mail->SMTPDebug = 2;
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'myEmail.com';
            $mail->Password   = 'xxxxxxxxx';
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;

            //Recipients
            $mail->setFrom('myqmial.com', 'Hello');
            $mail->addAddress($emailTo);
            $mail->addReplyTo('[email protected]', 'No reply');

            // Content
            $url = "http://" .$_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword.php?code=$code";
            $mail->isHTML(true);
            $mail->Subject = 'Reset Password';
            $mail->Body    = "<h1>You asked to reset your passwordŘŚ </h1>
                                Click <a href='$url'>this link</a> Please click on the link";
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
            echo 'The link has been successfully sent to your email';
            
        } 
        catch (Exception $e) {
            echo "Message could not be sent. Mail Error: {$mail->ErrorInfo}";
        }
        exit();
    }
    
?> 
<form method='POST'>
    <input type='text' name='email' placeholder='Email'>
    <input type='submit' name='submit' value='Reset password'>
</form>

I am attaching an image with the results:
enter image description here

I do not know what mistake I am doing, so how can I just show the message (The link has been successfully sent to your email) without all these lines?

Heroku / PHP / MVC > Requested URL not found

I have a very simple MVC project (no DB) that works very well when I launch it with a local server (“php -S localhost:8000 -t public”).

I use my routing this way:

require "Controllers/AppController.php";

$parsed_url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$appController = new AppController();

switch ($parsed_url) {
    case '/':
    case '/home':
        $appController->home();
        break;
    case '/about':
        $appController->about();
        break;
    case '/achievements':
        $appController->achievements();
        break;
    case '/contacts':
        $appController->contacts();
        break;
    default:
        $appController->pageNotFound();

I deployed it with Heroku, adding a Procfile, as specified in the official documentation, but now I can only get the homepage of my portfolio. All my other links throw me a “Not Found – The requested URL was not found on this server.”.

Here’s my Heroku log, if that can help:

2022-10-30T09:26:48.666806+00:00 heroku[router]: at=info method=GET path="/about" host=alexis-boucherie-devweb.herokuapp.com request_id=0dd695f8-8252-4cd4-8d3d-e012daf06130 fwd="86.213.16.43" dyno=web.1 connect=0ms service=1ms status=404 bytes=360 protocol=https

What I don’t understand, is that if I try to var_dump my “$parsed_url”, it does return a “/”, for the homepage. So I think it means the program goes through my Switch Case and that my Controller is ok. Also, because I have my homepage showing in the first place.

I tried to modify the page my $appController object calls for, and by doing so, I can access another page. But then again, if I click on any link or manually type the address of one of my pages (for instance “/contacts”), it doesn’t work.

In the end, I tried and searched for other topics related to this, found two here on StackOverflow, about adding an .htacess file, but I’m not sure I’m getting how that really works. Could this be the real source of my problem?

Remove extra generated td values from the table

I’m trying to fill table with values which I’m getting from the database but when I loop though array some values are getting out of the table.

DB values image:
enter image description here

DB structure with dump:
https://www.db-fiddle.com/f/9gTDRBFnguHtagJC4YNnRg/5

Code:

$query = "SELECT * FROM monthly_report";
$result = $this->db->query($query)->result_array();

$data['data'] = $result;
<table class="table table-hover table-striped">
    <thead>
        <tr>
            <th style="text-align:center;">Month</th>
            <th style="text-align:center;">Total Register</th>
            <th style="text-align:center;">January</th>
            <th style="text-align:center;">February</th>
            <th style="text-align:center;">March</th>
            <th style="text-align:center;">April</th>
            <th style="text-align:center;">May</th>
            <th style="text-align:center;">June</th>
            <th style="text-align:center;">July</th>
            <th style="text-align:center;">August</th>
            <th style="text-align:center;">September</th>
            <th style="text-align:center;">October</th>
            <th style="text-align:center;">November</th>
            <th style="text-align:center;">December</th>
        </tr>
    </thead>

    <tbody>
        <?php
        $num = 0;
        for ($m = 1; $m <= 12; $m++) {
            $month = date('F', mktime(0, 0, 0, $m, 1, date('Y')));
            echo "<tr style='text-align:center;'>";
            echo "<td>" . $month . "</td>";


            $short_month_name = date('M', strtotime("2022-$m-01"));

            if (isset($data[$num]['month']) && $data[$num]['month'] == $short_month_name) {

                $decode_data = json_decode($data[$num]['data'], true);
                $decode_isset = isset($decode_data[$short_month_name]) ? $decode_data[$short_month_name] : '';

                echo "<td>" .  $decode_isset . "</td>";
            }

            $num_1 = 0;
            for ($day = 1; $day <= 12; $day++) {

                $short_month_name_1 = date('M', strtotime("2022-$day-01"));

                if (isset($data[$num]['month']) && $data[$num]['month'] == $short_month_name_1) {

                    $decode_data_1 = json_decode($data[$num]['data'], true);
                    $decode_isset_1 = isset($decode_data_1) ? $decode_data_1 : [];

                    foreach ($decode_isset_1 as $v) {

                        if (!empty($v)) {
                            echo "<td>" .  $v . "</td>";
                        } else {
                            echo "<td>0</td>";
                        }
                    }
                } else {
                    echo "<td>0</td>";
                }

                $num_1++;
            }

            echo "</tr>";
            $num++;
        }
        ?>
    </tbody>
</table>

And output is:

enter image description here

I want to remove extra generated td (Marked in red box).

POST an array multidimensional of objects

Submitting for booked time. Add 5 variable at once. Each time has idVenue, idField, date, time and price.

Question: How can we get all of the times selected in an array of arrays?

booked[0] => Array (
  ["idVenue"] => "id Venue",
  ["idField"] => "id Field",
  ["date"] => "date selected",
  ["time"] => "time selected",
  ["price"] => "price selected"
),
booked[1] => Array (
  ["idVenue"] => "id Venue",
  ["idField"] => "id Field",
  ["date"] => "date selected",
  ["time"] => "time selected",
  ["price"] => "price selected"
), 
... 

Code

<input type="hidden" name="idVenue" value="<?=$getTimes['idVenue']?>">
<input type="hidden" name="idField" value="<?=$getTimes['idField']?>">
<input type="hidden" name="date" value="<?=date('Y-m-d',strtotime($getTimes['date']));?>">
<input type="hidden" name="price" value="<?=$getTimes['price']?>">
<input name="time" value="<?=$getTimes['start']?>" type="checkbox">

example
enter image description here

selected 4 nov but the result of values array is always like this

enter image description here

and my goals if selected item and send it to post php and array showed selected value

Exception: Class Not Found in PHP

I get the error:

Exception – Class ‘sitesoutputtab_gamify’ not found when load an edit page.

I have a file named sites/classes/output/edit.php with something like:

<?php

namespace sitesoutput;

class edit extends tabs {

      public function __construct(array $attributes = []) {
             parent::__construct($attributes);

             ...
             ...
             $this->add_tab(new tab_gamify($attributes));
      }

}

And a file named sites/classes/output/tab_gamify.php with something like:

<?php

namespace sitesoutput;

class tab_gamify extends tab {
      ...
      ...
}

I get the previous error message and and i not able to locate my error. Any suggestion or clue will be very appreciated.

Thanks in advance for your time.

I’ve revised namespaces, also reloaded and restarted docker container.

How the primitive type ‘String’ is implemented in PHP? Which character encoding does PHP use? Explain with suitable and easy to understand example

Today, I was trying to understand how the primitive type ‘String’ is implemented in PHP. In search of the same I come across following text from the PHP Manual

The string in PHP is implemented as an array of bytes and an integer
indicating the length of the buffer. It has no information about how
those bytes translate to characters, leaving that task to the
programmer. There are no limitations on the values the string can be
composed of; in particular, bytes with value 0 (“NUL bytes”) are
allowed anywhere in the string (however, a few functions, said in this
manual not to be “binary safe”, may hand off the strings to libraries
that ignore data after a NUL byte.)

After reading above text from the PHP Manual following questions come to my mind :

  1. What does it actually mean by an array of bytes and an integer indicating the length of the buffer? What does actually mean by the term ‘buffer’ in this case?

  2. Why does PHP not handle the task of translating those bytes to characters by itself? Why and what programmer supposed to do in this case of translation?

  3. According to the PHP Manual, there are no limitations on the values the string can be composed of. Does it mean that PHP uses Unicode(utf-8) for the purpose of character encoding?

  4. Do string and byte(a unit of digital information that most commonly consists of eight bits) mean the same thing in PHP?

Someone please clear my above doubts with the help of suitable and easy to understand example/s.

Thank You.

how upload capture image file to sever in java script html php

i working on a project where user capture photo from camera and show capture photo, but I want upload That Photo to server . How we can upload that image file to server . i am new please help me.
please help me how we upload image file to server. i Tried much but can not upload successfully.

<html>
<head>
<title>NigraniSof</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">

</head>

<body>

<button id="start-camera">Start Camera</button>
<video id="video" width="320" height="240" autoplay></video>
<button id="click-photo">Click Photo</button>
<div id="dataurl-container">
    <canvas id="canvas" width="320" height="240"></canvas>
    <div id="dataurl-header">Image Data URL</div>
    <textarea id="dataurl" readonly></textarea>
</div>

<script>

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");
let dataurl = document.querySelector("#dataurl");
let dataurl_container = document.querySelector("#dataurl-container");

camera_button.addEventListener('click', async function() {
    let stream = null;

    try {
        stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    }
    catch(error) {
        alert(error.message);
        return;
    }

    video.srcObject = stream;

    video.style.display = 'block';
    camera_button.style.display = 'none';
    click_button.style.display = 'block';
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg');
    
    dataurl.value = image_data_url;
    dataurl_container.style.display = 'block';
});

</script>  

</body>
</html>

How do I send mail using a php contact form? [duplicate]

So this contact form used to work, however now it loads and says mail sent when someone clicks submit but I never get any emails, what am I missing out?

<?php

// Replace this with your own email address
$siteOwnersEmail = '[email protected]';


if($_POST) {

   $name = trim(stripslashes($_POST['contactName']));
   $email = trim(stripslashes($_POST['contactEmail']));
   $subject = trim(stripslashes($_POST['contactSubject']));
   $contact_message = trim(stripslashes($_POST['contactMessage']));

   // Check Name
    if (strlen($name) < 2) {
        $error['name'] = "Please enter your name.";
    }
    // Check Email
    if (!preg_match('/^[a-z0-9&'.-_+]+@[a-z0-9-]+.([a-z0-9-]+.)*+[a-z]{2}/is', $email)) {
        $error['email'] = "Please enter a valid email address.";
    }
    // Check Message
    if (strlen($contact_message) < 15) {
        $error['message'] = "Please enter your message. It should have at least 15 characters.";
    }
   // Subject
    if ($subject == '') { $subject = "Contact Form Submission"; }


   // Set Message
   $message .= "Email from: " . $name . "<br />";
    $message .= "Email address: " . $email . "<br />";
   $message .= "Message: <br />";
   $message .= $contact_message;
   $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";

   // Set From: header
   $from =  $name . " <" . $email . ">";

   // Email Headers
    $headers = "From: " . $from . "rn";
    $headers .= "Reply-To: ". $email . "rn";
    $headers .= "MIME-Version: 1.0rn";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1rn";


   if (!$error) {

      ini_set("sendmail_from", $siteOwnersEmail); // for windows server
      $mail = mail($siteOwnersEmail, $subject, $message, $headers);

        if ($mail) { echo "OK"; }
      else { echo "Something went wrong. Please try again."; }

    } # end if - no validation error

    else {

        $response = (isset($error['name'])) ? $error['name'] . "<br /> n" : null;
        $response .= (isset($error['email'])) ? $error['email'] . "<br /> n" : null;
        $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;

        echo $response;

    } # end if - there was a validation error

}

?>
 

And this is the contact form:

<form name="contactForm" id="contactForm" method="post" action="mail/mail.php">
                <fieldset>

                   <div class="form-field">
                           <input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
                   </div>
                   <div class="form-field">
                       <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
                   </div>
                   <div class="form-field">
                           <input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
                   </div>
                   <div class="form-field">
                        <textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
                   </div>
                  <div class="form-field">
                      <button type="submit" name="submit" value="send"class="submitform">Submit</button>
                      <div id="submit-loader">
                         <div class="text-loader">Sending...</div>
                              <div class="s-loader">
                                    <div class="bounce1"></div>
                                    <div class="bounce2"></div>
                                    <div class="bounce3"></div>
                                </div>
                            </div>
                   </div>

                </fieldset>
            </form>

All the messages work, am I missing out on some SMPT information or something? Are there any alternatives to using phpmailer for this job?

List files from a directory or folder

Problem listing files from a directory

I am trying to list files in a directory I names jss by putting an index.php script in the same folder.
Unfortunately, I have not been able to succeed in doing this but got the error messages shared below after the main
Here is the error I got:
Warning : Undefined array key “submit digitallib/classnotes/jss/” in C:xampphtdocsdigitallibclassnotesjssindex.php on line 2

Warning : opendir(digitallib/classnotes/jss/): The system cannot find the path specifi (code: 3) in C:xampphtdocsdigitallibclassnotesjssindex.php on line 13

Warning : opendir(digitallib/classnotes/jss/): Failed to open directory: No such file or directory in C:xampphtdocsdigitallibclassnotesjssindex.php on line 13

Fatal error : Uncaught TypeError: readdir(): Argument #1 ($dir_handle) must be of type resource or null, bool given in C:xampphtdocsdigitallibclassnotesjssindex.php:15 Stack trace: #0 C:xampphtdocsdigitallibclassnotesjssindex.php(15): readdir(false) #1 {main} thrown in C:xampphtdocsdigitallibclassnotesjssindex.php on line 15

The code I used can be found here:
https://docs.google.com/document/d/1KPmxhN8Z7X6Y7xhqZYC7yDAGU_v-r4sUDcPMmnbSMdY/edit?usp=sharing

PHPBB Add User Automatically When They Sign-up on the Main Website

I have a website that requires login and I’ve installed PHPBB to a subdomain. I want users to automatically register to the PHPBB forum when they register to the main page and I need to give them access to only specific forums so I need to give them forum permissions based on their choices on the register page. How can I achieve this?

I’ve tried sending requests to ACP Add User Plugin using cURL but it requires tokens so after some time token expires and I can’t send any more requests.

How do I protect my Vue-routes with Laravel sanctum

I have a Laravel backend and a Vue frontend. I wanted to know how to protect my Vue routes with Lravael sanctum. I want that only logged in users can see the page?

I have tried this but it did not work: https://medium.com/@AshJuventino/building-a-vue-spa-protected-by-laravel-sanctum-33c9c87cc057 and https://techvblogs.com/blog/spa-authentication-laravel-sanctum-vuejs
vue-router

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import("../views/Home")
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import("../views/Register")
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import("../views/Login")
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

api-route-laravel

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

I have tried this but it did not work: https://medium.com/@AshJuventino/building-a-vue-spa-protected-by-laravel-sanctum-33c9c87cc057

https://techvblogs.com/blog/spa-authentication-laravel-sanctum-vuejs