Validations failed to work in PHP and Session

I have created an Online Marathon Form where it requires the user to fill in all the available fields prepare. Once it’s done and submitted, the form will be validated to check any error with the submitted form. However, those validations I set didn’t work except only name validation.
I tried to figure the cause for almost 3 days and kept asking people around but they didn’t reply.
I hope anyone can help me solving this error : Validations set failed to work. I must need this Session for my work.

pbt1.php

<?php
session_start();
?>
<html>
<?php

if(isset($_SESSION['pbt1']))
{
    $nameError      =   $_SESSION['pbt1']['nameError'];  
    $numberError    =   $_SESSION['pbt1']['numberError'];
    $dateError      =   $_SESSION['pbt1']['dateError'];
    $addressError   =   $_SESSION['pbt1']['addressError'];
    $cityError      =   $_SESSION['pbt1']['cityError'];
}
?>

<style>
.registrationform 
{
    padding: 20px;
    margin: auto;
    margin-top: 20px;
    line-height: 30px;
    width: 600px;
    border: solid 3px red;   
}

Label
{
    width:200px;
    display:inline-block;
}

</style>

    <div class= "registrationform">

        <h1>ONLINE MARATHON REGISTRATION</h1>
        <br><br>

        <form name = "pbt1" method = "post" action = "validation.php">
        
        <Label>Name<span style="color: red;">*</span>: </Label>
        <input type = "text" name = "name">
        <span id = "warning" style="color: red;" > <?php echo isset($nameError)?$nameError :'';?></span>
        <br><br>

        <Label>Gender <span style="color: red;">*</span>:</Label> 
        <input type = "radio" name = "gender" value = "Female">Female
        <input type = "radio" name = "gender" value = "Male">Male
        <span id = "warning" style="color: red;"><?php echo isset($genderError)?$genderError :'';?></span>
        <br><br>

        <Label>Date Of Birth <span style="color: red;">*</span>:</Label> 
        <input type = "date" name = "date">
        <span id = "warning" style="color: red;"><?php echo isset($dateError)?$dateError:'';?></span>
        <br><br>

        <Label>Contact Number <span style="color: red;">*</span>:</Label> 
        <input type = "text" name = "phonenumber">
        <span id = "warning" style="color: red;"><?php echo isset($numberError)?$numberError:'';?></span>
        <br><br>

        <Label>Address <span style="color: red;">*</span>:</Label>
        <input type = "text" name = "address" >
        <span id = "warning" style="color: red;"><?php echo isset($addressError)?$addressError :'';?></span>
        <br><br>

        <Label>City <span style="color: red;">*</span>:</Label> 
        <input type = "text" name = "city" >
        <span id = "warning" style="color: red;"><?php echo isset($cityError)?$cityError:'';?></span>
        <br><br>

        <Label>Zip Code <span style="color: red;">*</span>:</Label> 
        <input type = "text" name = "zipcode" >
        <span id = "warning" style="color: red;"><?php echo isset($zipcodeError)?$zipcodeError:'';?></span>
        <br><br>

        <div style="text-align:center;">
        <input type = "submit" value = "Submit" name="Submit">
        </div>
        </form>
        
    </div>

    <br><br>
</html>

validation.php

<?php
session_start();

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

    $name = $_POST['name'];
    if(isset($name) && empty($name))
    {
        $_SESSION['pbt1']['nameError']="Name must be required!";
        header('location: pbt1.php');  
        exit;
    }
    else
    {
        if(!preg_match("/^[a-zA-Z ]*$/",$name))
        {
            $_SESSION['pbt1']['nameError'] = "Only letters and white space allowed";
            header('location: pbt1.php');  
            exit;
        }   
    }

    $phonenumber = $_POST['phonenumber'];
    if(isset($phonenumber) && empty($phonenumber))
        {
            $_SESSION['pbt1']['numberError'] = "Error, insert phone number";
            header('location: pbt1.php');  
            exit;
        }
    else 
        {
            if(!preg_match('/^([0-9]*)$/', $phonenumber))
            {
                $_SESSION['pbt1']['numberError'] = "Numbers only";
                header('location: pbt1.php');  
                exit;
            }
        }
    


    $_SESSION['Userdata'] = ['name'=>$name , 'phonenumber'=>$phonenumber,'address'=>$address,'city'=>$city,
                            'zipcode'=>$zipcode,'gender'=>$gender,'date'=>$date ];

    header("location:pbt2.php");
    exit;
}

function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

pbt2.php

<?php
session_start();
?>
<html>
<style>
    table 
{
    text-align:center;
}
</style>



<div style="background-color:cyan;">

<h1 align = 'center'> YOUR INFORMATION AS THE TABLE BELOW </h1>

<table width = '400' border = '1' align = 'center'>
    <tr>
        <td>Name</td>
        <td><?php echo $_SESSION['Userdata']['name'];?></td>
    </tr>
    <tr>
        <td>Phone Number</td>
        <td><?php echo $_SESSION['Userdata']['phonenumber'];?></td>
    </tr>
    <tr>
        <td>Address</td>
        <td><?php echo $_SESSION['Userdata']['address'];?></td>
    </tr>
    <tr>
        <td>City</td>
        <td><?php echo $_SESSION['Userdata']['city'];?></td>
    </tr>
    <tr>
        <td>Zip Code</td>
        <td><?php echo $_SESSION['Userdata']['zipcode'];?></td>
    </tr>
    <tr>
        <td>Gender</td>
        <td><?php echo $_SESSION['Userdata']['gender'];?></td>
    </tr>
    <tr>
        <td>Date</td>
        <td><?php echo $_SESSION['Userdata']['date'];?></td>
    </tr>
</table>

</div>
</html>

CodeIgniter is putting the base URL in front of external site link

I am using Codeigniter on the backend. I have removed the controller names visibility in the URL by using the below Routes configuration:

$route['default_controller'] = 'home';
$route['(:any)'] = 'CommonPages/postDetails/$1';
$route['(:num)'] = 'CommonPages/postDetails/$1';
$route['([a-zA-Z0-9]+)'] = 'CommonPages/postDetails/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

The above sample code gives the exact result I want eg: base url + post title.
eg: https://example.com/how-to-install-whatsapp

Now I am having issues with the external sites links that is embedded under my blog posts. When I click on the external site link, it is putting my website base url infront of it + the external site url in double courts”” and that makes it not functional. eg:

 <a href=”https://play.google.com/store/apps/details?id=com.dewmobile.kuaiya.play&hl=en&gl=US” target=”_blank”>Play Store  (Zapya)</a> </b>

It is giving me the below result which is not functional:

https://example.com/"https://play.google.com/store/apps/details?id=com.dewmobile.kuaiya.play&hl=en&gl=US"

here is a screenshot below:

enter image description here

Any help will be much appreciated 🙂

Thanks.

WooCommerce recently view product count

If I am using the following code to track recently viewed products…

/**
 * Track user woocommerce viewed products.
 */
function dorzki_wc_track_product_views() {

    if( ! is_singular( 'product' ) || is_active_widget( false, false, 'woocommerce_recently_viewed_products', true ) ) {
        return;
    }

    global $post;

    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) {

        $viewed_products = array();

    } else {

        $viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) );

    }

    $keys = array_flip( $viewed_products );

    if ( isset( $keys[ $post->ID ] ) ) {

        unset( $viewed_products[ $keys[ $post->ID ] ] );

    }

    $viewed_products[] = $post->ID;

    if ( count( $viewed_products ) > 15 ) {

        array_shift( $viewed_products );

    }

    wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );

}

add_action( 'template_redirect', 'dorzki_wc_track_product_views', 20 );

and this code to display recently view products…

/**
 * Display recently viewed products.
 */
function dorzki_wc_display_products_viewed() {

    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) {
        return;
    }

    $total_products = apply_filters( 'loop_shop_columns', get_option( 'woocommerce_catalog_columns', 4 ) );
    $viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) );

    $products = array_slice( $viewed_products, 0, $total_products );
    $ids = implode( ',', $products );

    echo "<h2>" . esc_html__( 'Recently Viewed Products', 'dorzki' ) . "</h2>";
    echo do_shortcode( "[products ids='{$ids}']" );

}

add_action( 'woocommerce_after_cart', 'dorzki_wc_display_products_viewed' );

How can I obtain the ‘count’? Ideally I would like to create a shortcode that will output how many products the user has viewed recently.

How to delete the specific files and folders that begin and cotains with some numbers and titles?

I came up with this questioin. My background is from the Node.js. I am not usually quite used to be in PHP. That’s why I’m aksing this question to solve the current issues.

The issues is that’s to says I have certain Files and Folders that contains with a specific letters and number at the beginning. As you can see given by down below with a scrrenshot.

enter image description here

I just learn and writing some php code that I grabbed it from the internet resources. Take a look at what’s my code:

  1. I want this to detele this all folders which contains letters “exp_” and all the files names start with this numbers “xx-xx-xx” etc.

  2. I created delete.php. When I’d called this file via the browser, I want to achieve to delete all the files and folder which for the No. 1 case.

  3. All these folders and files are generated in everdays. That’s why I do want to clean all those data.

<?php
$path = "test";

if(!unlink($path)){
 echo "File has not deleted yet.";
} else {
 echo "Successfully deleted!";
}

?>

Is there any how any solution to solve this issues? I will appreciate all in advanced who are giving me idea and suggestions from you guys.

How can i update a Website wich is using json data [closed]

Does anybody know how you can completely refresh a website on load with code, so that every user wont get the “browser not refreshing” bug?

Im currently working on a page where the content builds up by a json data file so it would really help that every user sees the newest version of the website and not the old saved one.

Thanks in advance!

How do I get Laravel session authentication working on my server?

I’m having this weird issue with my laravel app where my passport authentication only works on my server but not on my local environment using php artisan serve.

so the below works on my web server but not on local as authentication fails

 /**
 * Admin API Routes
 */
Route::group(['middleware'=>'auth:api'], static function () {
    Route::post('/page', 'ApiPageController@create');
});

on my local the response I get a the below response

{"message":"Unauthenticated."}

and this works on my local environment but not on my server:

 /**
 * Admin API Routes
 */
Route::group(['middleware'=>'auth:admin'], static function () {
    Route::post('/page', 'ApiPageController@create');
});

here’s my guard config

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

Also on my server when ever I try to authenticate a customer it always seems to fail even when I’m clearly loggged in.

example of authentication in controller:

if(!auth('customers')->id()) {
    return $this->error('You are not authorized to access this', 403);
}

and my session are file based

I’m completly lost here as the behavior is inconsistent between environment and I’m not sure what I’m doing wrong.

Any help will be greatly appriciated

Thanks

my old code keep getting mysqli_fetch_array error in newer device [duplicate]

i was building a web based application using my old code from my previous work in my older laptop on a newer laptop, but somehow it didn’t work in my newer laptop, i tested the code on my older laptop and it still works fine.

error message:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in D:XAMPPhtdocsrpl2sppstafdatastafread.php on line 32

the line in question:

$staf=$mysqli->query("SELECT * FROM staf ORDER BY id_staf");
$no=0;
while($stf=mysqli_fetch_array($staf)){

i apologize for my bad english,

Permission denied for image dompdf even with chroot set

I am getting errors when I tried to include image in dompdf. I am using version 1.2.1
I tried with base4 encoded image as well from one of the solutions mentioned in forums, that also not working.

<?php

namespace Dompdf;
require_once 'dompdf/autoload.inc.php';

$_dompdf_show_warnings = true;
$_dompdf_warnings = [];

$path="http://localhost/dompdf/assets/images/logo.png";
$data = file_get_contents($path);
$image = 'data:image/' . $type . ';base64,' . base64_encode($data);

$htmldata = '<!DOCTYPE html>
<html>

<head>
  <title>Results</title>
  <style>
  body {
        background-color: lightblue;
    }
    .container {
      width: 90%;
      max-width: 600px;
      margin: 0 auto;
    }
  </style>
</head>

<body>

  <div class="container">
      
      <h1>test pdf</h1>
      <img src="/assets/images/logo.png" alt="image">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer egestas elementum justo, eget maximus odio ultricies eu. Aenean faucibus varius massa, sit amet sagittis neque vulputate luctus.</p>

      <img src="'.$image.'" alt="base64">
  </div>

</body>

</html>';


$options = new Options();
$options->getChroot($_SERVER['DOCUMENT_ROOT']."/dompdf/");;
$options->setisRemoteEnabled(true);
$options->setIsHtml5ParserEnabled(true);

$dompdf = new Dompdf($options);

$dompdf->loadHtml($htmldata);
$dompdf->render();
$dompdf->stream("",array("Attachment" => false));
exit(0);

?>

Getting these errors, first is when I include the image path and second for base64 encoded one. I tried to enable remote, added chroot path and tried several solutions found on internet. Nothing helped.

Permission denied on /assets/images/logo.png. The file could not be found under the paths specified by Options::chroot. /assets/images/logo.png

Unable to create temporary image in /var/folders/bc/tnbzrzvd1k370wftgbm5lnqh0000gn/T data:image/;base64,iVBORw0KGgoAAAANSUhEUgA

Can anyone suggest a solution for this?

Laravel Backup to Dropbox Backup failed because Unable to write file at location

Hello
I am trying to backup laravel to dropbox. I keep getting this error:

Exception message: rmdir(C:xampphtdocscareermovestorageapp/backup-temptemp): Directory not empty

Exception trace: #0 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateFoundationBootstrapHandleExceptions.php(231): IlluminateFoundationBootstrapHandleExceptions->handleError(2, ‘rmdir(C:xampp…’, ‘C:xampphtdocs…’, 173) #1 [internal function]: IlluminateFoundationBootstrapHandleExceptions->IlluminateFoundationBootstrap{closure}(2, ‘rmdir(C:xampp…’, ‘C:xampphtdocs…’, 173) #2 C:xampphtdocscareermovevendorspatietemporary-directorysrcTemporaryDirectory.php(173): rmdir(‘C:xampphtdocs…’) #3 C:xampphtdocscareermovevendorspatietemporary-directorysrcTemporaryDirectory.php(99): SpatieTemporaryDirectoryTemporaryDirectory->deleteDirectory(‘C:xampphtdocs…’) #4 C:xampphtdocscareermovevendorspatielaravel-backupsrcTasksBackupBackupJob.php(174): SpatieTemporaryDirectoryTemporaryDirectory->delete() #5 C:xampphtdocscareermovevendorspatielaravel-backupsrcCommandsBackupCommand.php(58): SpatieBackupTasksBackupBackupJob->run() #6 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateContainerBoundMethod.php(36): SpatieBackupCommandsBackupCommand->handle() #7 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateContainerUtil.php(41): IlluminateContainerBoundMethod::IlluminateContainer{closure}() #8 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateContainerBoundMethod.php(93): IlluminateContainerUtil::unwrapIfClosure(Object(Closure)) #9 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateContainerBoundMethod.php(37): IlluminateContainerBoundMethod::callBoundMethod(Object(IlluminateFoundationApplication), Array, Object(Closure)) #10 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateContainerContainer.php(653): IlluminateContainerBoundMethod::call(Object(IlluminateFoundationApplication), Array, Array, NULL) #11 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateConsoleCommand.php(171): IlluminateContainerContainer->call(Array) #12 C:xampphtdocscareermovevendorsymfonyconsoleCommandCommand.php(291): IlluminateConsoleCommand->execute(Object(SymfonyComponentConsoleInputArgvInput), Object(IlluminateConsoleOutputStyle)) #13 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateConsoleCommand.php(156): SymfonyComponentConsoleCommandCommand->run(Object(SymfonyComponentConsoleInputArgvInput), Object(IlluminateConsoleOutputStyle)) #14 C:xampphtdocscareermovevendorspatielaravel-backupsrcCommandsBaseCommand.php(28): IlluminateConsoleCommand->run(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #15 C:xampphtdocscareermovevendorsymfonyconsoleApplication.php(989): SpatieBackupCommandsBaseCommand->run(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #16 C:xampphtdocscareermovevendorsymfonyconsoleApplication.php(299): SymfonyComponentConsoleApplication->doRunCommand(Object(SpatieBackupCommandsBackupCommand), Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #17 C:xampphtdocscareermovevendorsymfonyconsoleApplication.php(171): SymfonyComponentConsoleApplication->doRun(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #18 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateConsoleApplication.php(102): SymfonyComponentConsoleApplication->run(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #19 C:xampphtdocscareermovevendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php(129): IlluminateConsoleApplication->run(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #20 C:xampphtdocscareermoveartisan(37): IlluminateFoundationConsoleKernel->handle(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput)) #21

How can I solve this? Please help

How to match these 2 strings

I have 2 strings :

World - Friday 22 April.pdf

World of 22 April 2022 Pdf

How can I say they are the same ? (by the words : World and by the date)

I tried using

if(strpos("World - Friday 22 April.pdf", "World of 22 April 2022 Pdf") !== false){
    echo "Found !";
}

I tried to make a regex which will get everything after the numeric. So I could compare 22 April and extract the first word to compare.
I’m very beginner in regex.

I can use something like d.(get everything after the match)

https://regex101.com/r/253KhJ/1

how to add code to service provider by artisan command

i created an Artisan Command that created Repository. A Repository File and an Interface.
when user run below command, this files will be generated.

php artisan make:repository RepositoryName

now, next step is to add bind code to RepositoryServiceProvider in register method.
How do I add the following code to that file?

$this->app->bind(
    RepositoryNameInterface::class,
    RepositoryName::class,
);

and generally, how to add custom code to the method of class in PHP?

Is there a way to pass a variable into an if statement of an Ajax request?

I am using Yajra Datatables to display audit data into a table. I have a function which gets audit data from a table using a received ID of a user and Request and gets the data using that ID. When i check if the request is Ajax using an if statement; I cannot get any variable outside of this if statement and even if i hard code a variable into this if statement so it should get the data based on this variable nothing is happening. I even tried die and dump the hard coded variable but its not dumping it on the screen. Below is the function;

    public function getByUser(User $user, Request $request)
{
    
    $email = $user->email;

       if ($request->ajax()) {
        //$email = "[email protected]";
        $audits = Audit::where('action_taken_by', $email)
        ->orderBy('id', 'DESC')
        ->get();

            return Datatables::of($audits)
                    ->addIndexColumn()
                    ->rawColumns(['action'])
                    ->make(true);
        }

    return view('audit/index');
}

If i remove the if statement the code is working but just dumping the array on the screen and not returning them on the view as intended and if the if statement is there all the results are displayed without checking the email variable. Is there a way i can pass this variable into the if statement?

Symfony 5 – A problem with the form to registrate a credit card with MangoPay

I’m trying to register a credit card with MangoPay.

I’ve installed the mangopay/php-sdk-v2 package.

To register a credit card, it needs three steps.

  1. Create a token of the card
  2. Post card info (using a url created by the token) that will render a string that start with data=
  3. Add the registered card to the MangoPay user
// ProfilController.php 

   /**
     * @Route("/payment/{id}", name="payment")
     * * @param int $id
     */
    public function payment(Request $request, ApiUser $ApiUser, $id): Response
    {           
            $returnUrl = "";

            $user = $this->userRepository->findOneBy(['id' => $id]);
            $userId = $user->getIdMangopay();
            $registration = $ApiUser->Registration($userId);
            
            if($request->request->count() > 0){
                $payment = new PaymentMethod(); 
                $payment->setName($request->request->get('name'));
                $payment->setCardNumber($request->request->get('cardNumber'));
        
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($payment);
                $entityManager->flush();

                $registrationCard = $ApiUser->RegistrationCard($registration, $request);

                $returnUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
                $returnUrl .= '/profil';
            }
            
            return $this->render('home/payment.html.twig', [
                    'CardRegistrationUrl' => $registration->CardRegistrationURL,
                    'Data' => $registration->PreregistrationData,
                    'AccessKeyRef' => $registration->AccessKey,
                    'returnUrl' => $returnUrl,
            ]);
    }

The Registration and ResitrationCard functions come from the ApiUser file:

// ApiUser.php

    public function Registration($UserId)
    {
        $CardRegistration = new MangoPayCardRegistration();
        $CardRegistration->UserId = $UserId;
        $CardRegistration->Currency = "EUR";
        $CardRegistration->CardType = "CB_VISA_MASTERCARD";
        $Result = $this->mangoPayApi->CardRegistrations->Create($CardRegistration);
      $this->registrationInfo = $Result;
      $this->CardRegistrationUrl = $Result->CardRegistrationURL;

      return $Result;
    }

    public function RegistrationCard($CardInfo)
    {
      $cardRegister = $this->mangoPayApi->CardRegistrations->Get($CardInfo->Id);

      $cardRegister->RegistrationData = $_SERVER['QUERY'];
      
      $updatedCardRegister  = $this->mangoPayApi->CardRegistrations->Update($cardRegister);
    
      return $Result;
    }

I’m able to create the token of the card and get the data= string, but the problem is that I cannot do the last step.

It seems that I cannot enter into the if statement, so it doesn’t register the card on the database and I cannot update the card information (3rd step).

The returnUrl, I can simply put it outside of the if statement to make it works, but I want to change it only if the form is valid.

How can I fix the statement? Why doesn’t it enter into the if?