What happens inside stack when you add an additional element to an array in php?

I learned php before learning C and C++. That’s why when I found out that the developer must defined the length of an array when defining the array itself, I couldn’t understand the underlying purpose behind it. But when I started to study assembly for computer architecture, I understood that because of how stacks are formed, you have to make space for any variable before you assign value. Otherwise you may overwrite existing data or overflow the stack itself.
But my question is: Obviously we do not define the length of any element (inluding primary data types) in languages like php. So lets say we have $array = ['a', 'b', 'c'] in php. What happens when I do $array[3] = 'd'?

Does whole stack get shifted? And if this is the case, does the whole contents of the RAM get shifet?

PHPUnit ‘Error : Class “pathtoclassclassToTest” not found’

I’m trying to write some unit tests. However no matter what I do I keep getting this error:

Error : Class “pathtoclassclassToTest” not found

The test I’m trying to run has a simple structure:

<?php
namespace testsunit;

use pathtoclassclassToTest;
use PHPUnitFrameworkTestCase;

class className extends TestCase
{
  public function testname()
  {
    $classToTest = new classToTest;
    $result = $classToTest->test();
    $this->assertTrue($result);
  }
}

The classToTest looks like this:

<?php
namespace pathtoclass;

class classToTest
{
  public function test()
  {
    return true;
  }
}

Laravel MongoDb Aggregation For unique and null

I want to retrieve documents from mongoDb by using MongoClient for parent_id is only first of same and parent_id is null.Only one aggregation.

$search[] = [
               '$group' => [
                    '_id' => '$parent_id',
                    'doc' => ['$first' => '$$ROOT']
                ]
            ];
            
            $search[] = [
                '$replaceRoot' => ['newRoot' => '$doc']
            ];

 app('mongo')->todo->Product->aggregate(array_filter($search));

Easy way to autonomous periodic data update in Laravel, PHP

How can I autonomous calculate and update value for one column in my Laravel project? I have no much experience in web-dev, so I just dont how to do it effective.

For example, now I’ve column “Condition” that calculates every time user open main page, I know its a dumb solve, so I want to update this “Condition” column every time when column “Count” (just any count) was changed and do it autonomous. I thought about events and listeners, but have too few information about how correctly communicate with this in my case.

In C#, for example, it was too easy, just subscribe to any event and do what u want. Here I need something likes columnWasChanged('Count') -> so call event/listener handler.

Thanks!

I tried:

//...ControllersMyController.php

public function index() {
    ...
    ...
    event(new UpdateConditionEvent($request));
    ...
}

//...ListenersConditionUpdateListener.php

public function handle(UpdateConditionEvent $event) {
    //...updatuing...
}

React app is giving me CORS policy error. How can I fix it?

Problem:

I’m trying to make a login page in React using Vite. To verify login credentials I have created an API in PHP. When I test the API with Postman it returns a data but with my react application it is not working.

Can you kindly help me to fix it? My react app is currently on localhost and my API is on my website. I have added the link to the API below.

Errors in console:

Access to XMLHttpRequest at ‘http://ahmadchattha.com/projects/taleemei/API/index.php’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

http://ahmadchattha.com/projects/taleemei/API/index.php net::ERR_FAILED 301 (Moved Permanently)

PHP Code:

try {
    $con = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['email']) && !empty($_POST['password'])) {
        $userEmail = $_POST['email'];
        $userPassword = $_POST['password'];
        try {

App.jsx:

import $ from 'jquery';
$.ajax({
  type: 'POST',
  url: form.attr('action'),
  dataType: "json",
  data: form.serialize(),
  crossDomain: true,
  format: "json",
  success(data) {
    setResult(data);
    console.log(data)
  },
});

Before using jQuery I also tried to use Axios but had no success with that. Also don’t have very much idea of what I should use because I’m totally new to React.

Thanks for any help 🙂

enter image description here

Using Puphpeteer to scrape web page with no classes or ids [duplicate]

I’m helping a friend to migrate their blog from a “homemade” platform to WordPress and the original developers have not been helpful in extracting the content so I’m trying to figure out how to scrape the site. I’m using PHP & Puppeteer (PuPHPEteer).

https://www.conversationwithachef.com/

The home page has a “load more” button at the bottom to load more blog posts – I know I’ll need to create a loop to keep “clicking” and loading blog posts until there are no more, then loop through each blog post. However, they do not seem to use any Ids or Classes (everything is inline css) so I’m not sure how I can easily identify and “click” the button. The button itself is actually divs so no easy identification there either.

Any thoughts on how I can go about this? Maybe something along the lines of finding the “Load more” then getting the parent div? I’m not super familiar with Puppeteer so not sure if this is even possible?

I want to make make array to submit data in swaggerAPI

Hi I am trying to submit data in swagger API i am trying to submit data like this

        $api_data = array(
            'organizationId' => '6601c70b-b770-4782-801a-3465a4b2f23a',
            'salutation' => isset($posted_data['Title'][0]) ? $posted_data['Title'][0] : '',
            'firstname' => isset($posted_data['Firstname']) ? $posted_data['Firstname'] : '',
            'lastname' => isset($posted_data['Surname']) ? $posted_data['Surname'] : '',
            'email' => isset($posted_data['E-mail']) ? $posted_data['E-mail'] : '',
            'citizenship' => isset($posted_data['nationality'][0]) ? $posted_data['nationality'][0] : '',
            'countryOfOrigin' => isset($posted_data['countryofresidence'][0]) ? $posted_data['countryofresidence'][0] : '',
            'profession' => isset($posted_data['Profession'][0]) ? $posted_data['Profession'][0] : '',
            
        );

This is working but i want to make a different array for address lik this but i am getting error every time.

enter image description here

Upgrading PHP to 8.3.9 from 8.2.12 on Windows 11 – cURL is not working

Steps I am taking:

  1. Fresh install of XAMPP, which uses PHP 8.2.12.
  2. After install, I confirm that cURL shows enabled in my phpinfo and my local coding files work as expected.
  3. I renamed the existing php folder in my xampp directory to php_old.
  4. I downloaded a thread-safe version of php 8.3.9 and unzip to a new ‘php’ folder in xampp directory.
  5. Checking phpinfo again, it does show that my php version was updated to 8.3.9, but cURL is completely missing.

The only thing I know to check:

I went to the php.ini-development file, uncommented ‘extension=curl’, and saved it as a new php.ini. Still nothing in phpinfo.

I feel like I am missing something completely stupid here.

why my form not getting saved to mysql database

this error keep showin up after clickin submit
ERROR: Form data not submitted.

this is the form

<form action="connection.php" method="post">
    
    <p>
        <label for="firstName">First Name:</label>
        <input type="text" name="first_name" id="firstName" required>
    </p>
    
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="last_name" id="lastName" required>
    </p>
    
    <p>
        <label for="Gender">Gender:</label>
        <input type="text" name="gender" id="Gender" required>
    </p>
    
    <p>
        <label for="Address">Address:</label>
        <input type="text" name="address" id="Address" required>
    </p>
    
    <p>
        <label for="emailAddress">Email Address:</label>
        <input type="email" name="email" id="emailAddress" required>
    </p>
    
    <input type="submit" value="Submit">
</form>

and this is my php script

<?php
    // Check if the form data is set
    if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['gender']) && 
        isset($_POST['address']) && isset($_POST['email'])) {

        // Database connection
        $conn = mysqli_connect("localhost", "root", "", "form_data_db");

        // Check connection
        if ($conn === false) {
            die("ERROR: Could not connect. " . mysqli_connect_error());
        }

        // Taking all 5 values from the form data (input)
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $gender = $_POST['gender'];
        $address = $_POST['address'];
        $email = $_POST['email'];

        // Performing insert query execution
        $sql = "INSERT INTO form_data (first_name, last_name, gender, address, email) 
                VALUES ('$first_name', '$last_name', '$gender', '$address', '$email')";

        if (mysqli_query($conn, $sql)) {
            echo "<h3>Data stored in the database successfully.</h3>";
            echo nl2br("n$first_namen $last_namen $gendern $addressn $email");
        } else {
            echo "ERROR: Hush! Sorry $sql. " . mysqli_error($conn);
        }

        // Close connection
        mysqli_close($conn);
    } else {
        echo "ERROR: Form data not submitted.";
    }
    ?>

AlpineJS submit a form without refreshing the page

I am working with Hyva theme with AlpineJs on Magento and using a <form> with the needed inputs to add a product to the shopping cart.

This is part of the form code:

    <form method="post"
          id="product_addtocart_form"
    >
        <input name="product" />
        <input name="selected_configurable_option"  />
        <input name="related_product" />
        <input name="item">
    </form>

And this is the button I am using to submit the form:

    <button type="submit" form="product_addtocart_form">
        Submit
    </button>

Everything works great. However, I want to add a modal that shows after a product is added to the shopping cart but as soon as the product is added the page refreshes.

I found plenty of similar topics but nothing did it for me. I have already tried using event.preventDefault() and onsubmit="return false". Both don’t refresh the page but a product is not added.

I also tried adding products using an HTTP post method which partly solved the issue but when it comes to adding products with configurable options, it becomes too complicated.

Would you have any suggestions or ideas for an approach I can take to stop refreshing the page after a form is submitted?

Problem while trying to run composer update

I’m currently working on the dockerized version of ProcessMaker 4.1.21 and I’m encountering the following error when I try to run the “composer update –ignore-platform-reqs” command :

PHP Fatal error:  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of IlluminateSupportCollection::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupportCollection.php:1277
Stack trace:
#0 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupportCollection.php(11): IlluminateFoundationBootstrapHandleExceptions->handleError()  
#1 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorcomposerClassLoader.php(576): include('...')
#2 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorcomposerClassLoader.php(427): ComposerAutoload{closure}()
#3 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupporthelpers.php(109): ComposerAutoloadClassLoader->loadClass()
#4 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(130): collect()
#5 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(106): IlluminateFoundationPackageManifest->build()
#6 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(89): IlluminateFoundationPackageManifest->getManifest()     
#7 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(78): IlluminateFoundationPackageManifest->config()
#8 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationBootstrapRegisterFacades.php(26): IlluminateFoundationPackageManifest->aliases()
#9 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationApplication.php(219): IlluminateFoundationBootstrapRegisterFacades->bootstrap()
#10 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php(320): IlluminateFoundationApplication->bootstrapWith()      
#11 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php(129): IlluminateFoundationConsoleKernel->bootstrap()       
#12 C:UsersAdministratorDesktopprocessmaker-4.1.21artisan(30): IlluminateFoundationConsoleKernel->handle()
#13 {main} in C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupportCollection.php on line 11

In Collection.php line 11:

  During inheritance of ArrayAccess: Uncaught ErrorException: Return type of IlluminateSupportCollection::offsetExists($key) should either be compatible with ArrayAccess::offsetExist   
  s(mixed $offset): bool, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlarav   
  elframeworksrcIlluminateSupportCollection.php:1277
  Stack trace:
  #0 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupportCollection.php(11): IlluminateFoundationBootstrapHandleExceptions->handleErro   
  r()
  #1 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorcomposerClassLoader.php(576): include('...')
  #2 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorcomposerClassLoader.php(427): ComposerAutoload{closure}()
  #3 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateSupporthelpers.php(109): ComposerAutoloadClassLoader->loadClass()
  #4 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(130): collect()
  #5 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(106): IlluminateFoundationPackageManifest->build()        
  #6 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(89): IlluminateFoundationPackageManifest->getManifest()   
  #7 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationPackageManifest.php(78): IlluminateFoundationPackageManifest->config()        
  #8 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationBootstrapRegisterFacades.php(26): IlluminateFoundationPackageManifest->ali   
  ases()
  #9 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationApplication.php(219): IlluminateFoundationBootstrapRegisterFacades->bootst   
  rap()
  #10 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php(320): IlluminateFoundationApplication->bootstrapWith()    
  #11 C:UsersAdministratorDesktopprocessmaker-4.1.21vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php(129): IlluminateFoundationConsoleKernel->bootstrap()     
  #12 C:UsersAdministratorDesktopprocessmaker-4.1.21artisan(30): IlluminateFoundationConsoleKernel->handle()
  #13 {main}


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

Here is my composer.json :

{
  "name": "processmaker/processmaker",
  "version": "4.1.21",
  "description": "BPM PHP Software",
  "keywords": [
    "php bpm processmaker"
  ],
  "homepage": "http://processmaker.com",
  "license": "GAGPL-3.0-or-later",
  "minimum-stability": "dev",
  "prefer-stable": true,
  "require": {
    "php": ">=7.2.0",
    "babenkoivan/elastic-scout-driver": "^1.2",
    "darkaonline/l5-swagger": "6.0.*",
    "doctrine/dbal": "^2.9",
    "fideloper/proxy": "^4.0",
    "fzaninotto/faker": "^1.4",
    "guzzlehttp/guzzle": "^6.5",
    "igaster/laravel-theme": "2.0.*",
    "laravel/framework": "6.18.35",
    "laravel/horizon": "~3.0",
    "laravel/passport": "9.3.2",
    "laravel/scout": "^7.2",
    "laravel/telescope": "^3.0",
    "laravel/tinker": "^2.0",
    "laravelcollective/html": "^6.1.2",
    "lavary/laravel-menu": "^1.7",
    "lcobucci/jwt": "^3.3",
    "moontoast/math": "^1.1",
    "mustache/mustache": "^2.12",
    "phing/phing": "^2.16",
    "pion/laravel-chunk-upload": "^1.4",
    "predis/predis": "^1.1",
    "processmaker/docker-executor-lua": "^1.0",
    "processmaker/docker-executor-node": "^1.0",
    "processmaker/docker-executor-php": "^1.0",
    "processmaker/laravel-i18next": "dev-master",
    "processmaker/nayra": "1.7.0",
    "processmaker/pmql": "1.2.0",
    "pusher/pusher-php-server": "^4.0",
    "ralouphie/getallheaders": "^2.0",
    "spatie/laravel-fractal": "^5.3",
    "spatie/laravel-medialibrary": "^7.0.0",
    "symfony/expression-language": "^5.1.6",
    "teamtnt/laravel-scout-tntsearch-driver": "^9.0",
    "typo3/class-alias-loader": "^1.0",
    "watson/validating": "^3.1",
    "whichbrowser/parser": "^2.0"
  },
  "require-dev": {
    "filp/whoops": "^2.0",
    "laravel/dusk": "^5.4",
    "laravel/homestead": "10.15.2",
    "mockery/mockery": "^1.0",
    "nunomaduro/collision": "^2.0",
    "phpunit/phpunit": "^7.0",
    "squizlabs/php_codesniffer": "^3.0.2",
    "symfony/dom-crawler": "^4.3"
  },
  "autoload": {
    "files": [
      "ProcessMaker/Helper/helper.php"
    ],
    "classmap": [
      "database/seeds",
      "database/factories"
    ],
    "psr-4": {
      "ProcessMaker\": [
        "ProcessMaker/"
      ]
    }
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\": "tests/"
    }
  },
  "extra": {
    "laravel": {
      "dont-discover": [
        "laravel/dusk",
        "laravel/passport"
      ]
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r "file_exists('.env') || copy('.env.example', '.env');""
    ],
    "post-create-project-cmd": [
      "@php artisan key:generate"
    ],
    "post-autoload-dump": [
      "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
      "@php artisan package:discover"
    ]
  },
  "config": {
    "preferred-install": "dist",
    "sort-packages": true,
    "optimize-autoloader": true,
    "allow-plugins": {
      "typo3/class-alias-loader": false
    }
  }
}

Here is my configuration:

PHP: 8.3.9

Laravel: 11.17.0

Composer : 2.7.7

I tried to downgrade the PHP and Laravel versions but nothing worked really

PHP forach array with objects

How can I echo this PHP array with objects in an foreach loop?
I want to echo each value in different parts of my code.

array(2) {
  ["new_years_day"]=>
  object(DateTime)#1 (3) {
    ["date"]=>
    string(26) "2024-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(16) "America/New_York"
  }
  ["juneteenth"]=>
  object(DateTime)#2 (3) {
    ["date"]=>
    string(26) "2024-06-19 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(16) "America/New_York"
  }
}

I tried this code but it this doesn’t do the job ($holidaysThisYear is the name of the array):

<?php foreach($holidaysThisYear as $holidayThisYear) {
  echo $holidayThisYear->timezone;
} ?>

PHP Sort a multidimensional array by date start, or if uquals, by date end

I need to sort an array containing a date start and a date end.

To sort by date start I use this function:

usort($array, function($a, $b) {
  return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});

but in case an element has the same date start to another one, i need then sort by date end.
And don’t know how to do this. Anyt suggest?

Example array

$array = [
0 => [
        "id" => 1
        "start" => 2024-07-24 05:00,
        "end" => 2024-07-25 14:00
    ],

1 => [
       "id" => 2
        "start" => 2024-07-22 06:00,
        "end" => 2024-07-22 08:00
    ],

2 => [
        "id" => 3
        "start" => 2024-07-27 10:00,
        "end" => 2024-07-28 11:00
    ],

3 => [
        "id" => 4
        "start" => 2024-07-22 06:00,
        "end" => 2024-07-22 07:00
    ]

]

With my example I expected this order id: 4, 2, 1, 3 (because id 4 and 2 has same start, but id 4 ends before)

data cant be save in database

i have a registration form and i want to store the information (gender and phone included) but it didnt store in the database even the register is successful but the column for gender and phone_number are blank
– I had tried to change my structure of gender from ENUM “MALE”, “FEMALE” to varchr(50) also not work

  • when ENUM, it shows empty

  • when varchar, it shows 0

    also my phone number also stated blank

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `nickname` varchar(50) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `gender` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `address` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone_number` varchar(20) NOT NULL,
  `country` varchar(50) NOT NULL,
  `user_type` varchar(50) NOT NULL,
  `program` varchar(100) NOT NULL,
  `department` varchar(50) DEFAULT NULL,
  `password` varchar(255) NOT NULL,
  `avatar_url` varchar(255) DEFAULT NULL,
  `registration_date` timestamp NOT NULL DEFAULT current_timestamp()
) 
20, 'AFLRED', 'CEO of MDIS', 'DCT-1151', '', 69, '54,Jalan Impian 20', '[email protected]', '', 'MY', 'STAFF', '', 'OFFICE OF THE REGISTER', '$2y$10$JJZVYp5DQ7QC6SMT0zYQC.Eq84gJtW8ATwhBxTWExE1xW5EQ.nVTG', './uploads/MDIS-badge.png', '2024-07-23 17:04:20'),

my phone number and gender are not being record

<?php
session_start();
$conn = new mysqli("localhost", "root", "", "forum");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$avatar_url = null; // Initialize $avatar_url

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $full_name = $conn->real_escape_string($_POST['full_name']);
    $nickname = $conn->real_escape_string($_POST['nickname']);
    $user_id = $conn->real_escape_string($_POST['user_id']);
    $gender = $conn->real_escape_string($_POST['gender']);
    $age = (int)$_POST['age'];
    $address = $conn->real_escape_string($_POST['address']);
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : "";
    $phone_number = preg_match("/^[0-9]{10,15}$/", $_POST['phone_number']) ? $_POST['phone_number'] : "";
    $country = $conn->real_escape_string($_POST['country']);
    $user_type = $conn->real_escape_string($_POST['user_type']);
    $program = $conn->real_escape_string($_POST['program']);
    $department = $conn->real_escape_string($_POST['department'] ?? '');
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Handle file upload
    if (isset($_FILES['avatar_url']) && $_FILES['avatar_url']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['avatar_url']['tmp_name'];
        $fileName = $_FILES['avatar_url']['name'];
        $fileSize = $_FILES['avatar_url']['size'];
        $fileType = $_FILES['avatar_url']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));

        // Set allowed file extensions
        $allowedExts = array('jpg', 'jpeg', 'png', 'gif');
        if (in_array($fileExtension, $allowedExts)) {
            // Move file to destination directory
            $uploadFileDir = './uploads/';
            $dest_path = $uploadFileDir . $fileName;

            if (move_uploaded_file($fileTmpPath, $dest_path)) {
                // Store file path in $avatar_url
                $avatar_url = $dest_path;
            } else {
                $_SESSION['error'] = 'Error moving the file.';
                header("Location: register page.php");
                exit();
            }
        } else {
            $_SESSION['error'] = 'Invalid file type.';
            header("Location: register page.php");
            exit();
        }
    }
    
    // Check password match
    if ($password !== $confirm_password) {
        $_SESSION['error'] = 'Passwords do not match.';
        header("Location: register page.php");
        exit();
    }

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Prepare and execute statement to check if user_id already exists
    $stmt = $conn->prepare("SELECT COUNT(*) FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    if ($count > 0) {
        $_SESSION['error'] = 'ID already exists. Please use a different ID.';
        header("Location: register page.php");
    } else {
        // Prepare and execute statement to insert user data
        $stmt = $conn->prepare("INSERT INTO users (full_name, nickname, user_id, gender, age, address, email, phone_number, country, user_type, program, department, password, avatar_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssissssssssss", $full_name, $nickname, $user_id, $gender, $age, $address, $email, $phone_number, $country, $user_type, $program, $department, $hashed_password, $avatar_url);

        // Execute the statement
        if ($stmt->execute()) {
            header("Location: index.html");
            exit();
        } else {
            $_SESSION['error'] = "Error: " . $stmt->error;
            header("Location: register page.php");
        }

        $stmt->close();
    }

    $conn->close();
}
?>

i want my gender can be display either male or female in database and the phone_number also can be display in varchar

MySQL data to OneDrive [closed]

We are using windows server and scheduled phpscript to extract MYSQL data and load into csv file, then upload it to Onedrive. However this process in the recent days seems to be troublesome.

We are trying to find an alternative without using windows server.

Is there anyway please?

Thanks