How to copy a file inside a newly created folder and rename the file?

Good day experts!

I want to copy a file inside a newly created folder and rename the file but it seems there’s something wrong with codes and I cant figure it out. Here’s my code:

<?php
$name = $_POST["newFileName"];
$folder = mkdir($name);
session_start();
$name = $_POST["newFileName2"];
$file = 'data.php';
$newfile = $folder/$_POST["newFileName2"].'.php';

file_exists($newfile) && die(" <center><br><br><br><br>The Exam name already exists.! Change it! <br><br> <a href='quiz.php'><button>GO BACK</button></a>");

if (!copy($file, $newfile)) {
    echo "Failed to create Quiz";
}else {
   echo "Created Successfully";
}
?>

Is PHP ldap_escape compatible with Microsoft Active Directory?

Here

https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx

you can see how AD requires to escape individual components of a distinguished name (a backslash in front of the character to be escaped).

The ldap_bind function, however, adopts a different escaping technique (I think according to RFC4514) so for example:

SalesEngineering would be:

Sales\Engineering according to 1

and:

Sales5cEngineering if you use ldap_bind

I know that 5c is just the xx hex sequence for , but can this create problems?

I am having troubles using ldap_bind with domainuser DNs in Active Directory that’s why I am wondering if there are compatibility issues.

Thanks

Block users from REST API endpoint while still grabbing data from it

I have created 2 REST API endpoint to store the CPT data and their custom fields:

Archive Data: xyz.com/wp-json/wl/v2/businesses
Single Business data: xyz.com/wp-json/wl/v2/businesses/<ID>

Both these endpoints have been registered with the permission callbacks;

register_rest_route( 'wl/v2', '/businesses', array(
    'methods'   => WP_REST_Server::READABLE,
    'callback'  =>  'wl_businesses_posts',
    'permission_callback'   => '__return_true'
));

It is a business directory website where a common dashboard ( xyz.com/dashboard ) for each ‘business’ client exists and this dashboard page pulls in data for that ‘business’ from the Single Business data REST API endpoint above and fills the input fields on the page.

There is also another page accessible to the non-logged in visitors( xyz.com/business1 ) that is common for all businesses and is a read-only page where visitors can check that business’ details. This page too pulls data from the Single Business data REST API endpoint mentioned above.

What I am trying to accomplish is that no one except the Admin should be able to peep into the Archive Data or the Single Business data endpoints, to avoid stealing info of all the businesses registered with the site. But at the same time, I would want these endpoints to be accessible by the wp_remote_retrieve_body( wp_remote_get( $url ) );code to populate the dashboard and single business info pages.

I tried this code but it obviously also blocks the requests made by the page code to pull and populate data in the pages.

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
      return $result;
    }
    if ( ! is_user_logged_in() ) {
      return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
    }
    return $result;
  });

I am not necessarily looking for a code, just the direction about how to solve this problem.

file_exists(): open_basedir restriction in effect is checking for a file that doesn’t exist

I have a simple Laravel project, it runs just fine on my local machine, but after uploading to the server, when accessing a certain page, the following error is displayed:

file_exists(): open_basedir restriction in effect.
File(C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourceslang/ar/Forgot
Your Password?.php) is not within the allowed path(s):
(C:/Inetpub/vhosts/goldenmedpharma.com;C:WindowsTemp;C:Inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4public;C:WindowsTemp)
(View:
C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourcesviewsauthlogin.blade.php)

I don’t have a file named (Forgot Your Password?.php)! What exactly is this?
I’m using Plesk Obsidian to manage PHP and files on the server.

if condition in Laravelll

I want to check whether the user has cv or not. I used the following expression but doesn’t work any one can help

 public function create()
      
    {   
         if (auth()->user()->cv) {
         
        return $this->edit()-with('You already have a cv!', 'info');
   }
   return view('cv.create');
   }

WordPress search only showing a few posts

I am working on a Website and am linking category links to the search page.
Now the search behaves seemingly random as seen here: https://hasel.dev/?s=dizh

The search for the post returns the post, so far so good. If I click the ‘Developer Productivity’ Tag (= search for it), however, it returns a number of posts, not including the ‘DIZH’ post. If I click the ‘papers’ tag, I don’t get any results at all, although having added the category to over 20 posts.

enter image description here

What is the issue here?

Authentication with symfony 6.1, Token sent with every request, but it returns credentials at each response, problem with session or kernel.response

I’ve set an OIDC authentication with a custom authenticator as follow:

class SsoAuthenticator  implements AuthenticatorInterface, AuthenticationEntryPointInterface
{
    private UserProviderInterface $user_provider;
    private ?LoggerInterface $logger;

    public function __construct(LdapUserRepository $ldap_user_repository, UserProviderInterface $user_provider, LoggerInterface $logger = null)
    {
        $this->user_provider = $user_provider;
        $this->logger = $logger;
        $this->ldap_user_repository = $ldap_user_repository;
    }

    public function start(Request $request, AuthenticationException $authException = null): Response
    {
        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'emmaus.example.com'));
        $response->setStatusCode(401);

        return $response;
    }

    public function supports(Request $request): ?bool
    {
        return $request->headers->has('Authorization') || $request->get('token');
    }

    public function authenticate(Request $request): Passport
    {
       $oidc = new Oidc($this->ldap_user_repository);
       $token = $request->get('token');
       $decoded_token = $oidc->decodeToken($token);
       $user_name = $oidc = $oidc->getUserName($decoded_token);
        if(!(is_a($this->user_provider, UserProviderInterface::class)))
        {
            throw new AuthenticationException('error forbidden buddy');
        }
        $user_badge = new UserBadge($user_name);
        $credentials = new BadgeCredentials();
        return new Passport($user_badge, $credentials);
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return new UsernamePasswordToken($passport->getUser(), $firewallName, $passport->getUser()->getRoles());
    }
    public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
    {
        return new OidcToken(['ROLE_USER'], null);
    }
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        $oidc = new Oidc($this->ldap_user_repository);
        $token = $request->get('token') ? $request->get('token') : $request->get('Authorization');
        $decoded_token = $oidc->decodeToken($token);
        $user_identifier = $oidc->getUserName($decoded_token);
        $user = $this->ldap_user_repository->findOneBy(['username' => $user_identifier]);
        $last_name = $user->getLastName();
        $first_name = $user->getFirstName();
        $roles = $user->getRoles();
        $email = $user->getEmail();
        $group_results = array();
        $groups = $user->getGroupBase();
        
        foreach($groups as $group)
        {
            array_push($group_results, $group->getName());
        }

        $token = $request->get('token') ? $request->get('token') : $request->headers->has('Authorization');
        $_SESSION['token_lemon_ldap'] = $token;
        $data = array(
            'roles' => $roles,
            'userName' => $user_identifier,
            'firstName' => $first_name,
            'lastName' => $last_name,
            'email' => $email,
            'token' => $token,
            'groups' => $group_results
        );
        return new Response(
            json_encode($data)
        );


    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        $oidc = new Oidc($this->ldap_user_repository);
        $decoded_token = $oidc->decodeToken($request->get('token'));
        try
        {
            return $this->start($request, $exception);
        }catch(UnexpectedValueException $exception)
        {
            throw new $exception('wrong number of segment');
        }
    }
}
?>

I’ve the authorization to access resources from API after successful authentication, but when I’m fetching response from controller, it return onAutenticationSucess() response’s data at each request, and can’t access data from controllers, do you have an idea what i’m missing? I’m looking at session or kernel.response, but can’t make my head around a proper solution.
Thanks

How to get html data-attribute string from a php variable

I am constructing an html form in php with javascript and css, the following line of code works fine and displays a textarea with the required prefix:

$form .= '<textarea class="text" data-prefix="Message from: " ></textarea>';

However I want to include a php variable i.e

$form .= '<textarea class="text" data-prefix="Message from: $foo" ></textarea>';

This show the textarea with the prefix ‘Message from $foo’.
How do I show it with the value of $foo combined into the data-prefix i.e ‘Message from Foo’?

Any advice would be appreciated, thanks.

How to exclude certain styling in page2 in pagination

I have followed Jeffery Way in Laravel 8 from scratch amazing series but I’m having a trouble in pagination. In the index page we’re making our latest post to have a specific styling and then first 2 posts comes after with a different styling and then rest of posts in different styling. The problem is that these styles are carrying over with us to page2 and 3 and …etc

I want to make this to only posts in page1 or homepage and when I go to page 2 I should have a default styling for all posts.

This is the index

<x-bloglayout>

    @include('posts.__header')

    @if ($posts->count())
        <x-featuredCard :post="$posts[0]" />

        @if ($posts->count() > 1)

            <div class="lg:grid lg:grid-cols-2">

                <x-postCard :post="$posts[1]" />
                <x-postCard :post="$posts[2]" />

            </div>

            <div class="lg:grid lg:grid-cols-3">
                @foreach ($posts->skip(3) as $post)
                    <x-postCard :post="$post" />
                @endforeach
            </div>

        @endif

        {{ $posts->links() }}

    @else
        <p class="text-center">No posts matches your search, please check back later</p>
    @endif



</x-bloglayout>

I tried to use if directive to say if route is home or ?/page1 do this if not do that but it doesn’t seem to work.

This is my pagination:

    public function index()
    {
        return view('posts.index', [
            'posts' => Post::latest()->filter(request(['search', 'category', 'author']))->paginate(6)->withQueryString(),
        ]);
    }

Thanks

What would be the best approach to fetch calculated cells from a JS generated Excel file?

I am building a React web app that asks the user to fill out some inputs that are directly sent into an complex template excel file using ExcelJS. Everything’s working like a charm except that I must open the generated file so MS Excel or LibreOffice recalculates all the formulas, that means I can’t just call a cell getter from JS to fetch a calculated formula.

Unfortunately the file is far too complex to be re written in a simple formula directly in JS, it’s using matrices, graphs, references to other sheets, etc. It’s an old system that has not been reworked since back then and that I’m not permitted to change.

What would be the best approach to treat this case ? I would just like to fetch a single cell from that file, I know PHPSpreadsheet does that because I’ve already done it, would it be OK to create a PHP API that get the generated excel into parameters to fetch the desired cell and store it in a database so that I can get access to it via my react app ? It seems like an overcomplicated, or overcharged solution for what I want to do. I’m not against using something else that ExcelJS if you can provide me another library that can handle with complex excel formulas

Thanks in advance

How to order a Select query in MySQL based on the most occurrence of another table

I have a product table and a memory table. The product table contains product ID and product name:

product_id product
1 RAM
2 HDD
3 SSD

The memory table contains different memory as below:

memory_id memory
1 128 GB
2 256 GB
3 512 GB
4 1 TB
5 8 GB
6 16 GB
7 32 GB

I have created two drop-down select options for products and for memory and save them in a cart table as below:

order_id product_id memory_id
1 1 1
2 1 2
3 1 1
4 2 3
5 2 4
6 2 3

I am wondering is there any way to do DESC order the select options for memory based on the occurrence of that specific product_id in cart table?
My target is to order the select options of the memory with the most used cases.

How to Get Data from YT-DLP to Browser Using PHP

I’m trying to Get YT-DLP data using PHP
Using SSH yt-dlp BaW_jenozKc I’m able to generate download codes, however same thing for PHP is not working on browser.

Have tried this code

<?php
$proc = popen('yt-dlp -o - BaW_jenozKc', 'r');
header("Content-Type: video/mp4");
while (!feof($proc))
{
    echo fread($proc, 4096);
}
pclose($proc);
?>

The above code expect to generate streaming link but its giving me error with no video with supported format and mime type found

On the other side when I use this PHP code

<?php
echo shell_exec("wget -O speedtest.py https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py && chmod +x speedtest.py && ./speedtest.py");
?>

It works great, can anybody tell me what’s wrong with the code or is there any permission issue for displaying data on browser?

unable to get session username to insert to database [closed]

Unable to insert session id to database. I Want to get the session username and insert it to database and display the current session username content.

<?php
require("session.php");
require ("include.php");

if (isset($_POST['save'])) {

    if (
        !empty($_POST['name']) && !empty($_POST['subject']) && !empty($_POST['sender']) &&
        !empty($_POST['to'])) 
    {
        $session_id = $_SESSION["user"];  
        $name = $_POST['name'];
        $subject = $_POST['subject'];
        $sender = $_POST['sender'];
        $to = $_POST['to'];
        $time = date("Y-m-d H:i:sa");

        foreach ($name as $key => $names) {
            $s_name = $names;
            $s_subject =  $subject[$key];
            $s_sender = $sender[$key];
            $s_to = $to[$key];
            $save = mysqli_query($link,"INSERT INTO `incomings`( `name`, `subject`,`sender`, `to_`,
`session_id`,  `time`) VALUES ('$s_name','$s_subject','$s_sender',  
'$s_to','$session_id', '$time' )");
            $save_q = mysqli_query($link,$save);
        } 

        if (!$save) {
            echo " Mails Not Submitted!";
            header("Location:insert_incoming.php");
            exit(0);} 
    }
}
?>