I have Xampp installed. In a php file, if I run “error_log(“aãa”);” it outputs “axc3xa3a”. Please help me fix it

The error_log problem isn’t my actual problem, though. I’m trying to figure out the following problem:

I have quilljs running on a page.

I type accents, like “aãa” above.

I grab it with getText, send it to php with $.post (ajax, I believe)

Whatever I try to do with it, it comes out garbled like that.

Specifically what I’m trying to do is this: array_count_values(str_word_count($text, 1));

To find repeated words and later highlight them in the text, basic stuff, only the character encoding problem is making it harder than it should be.

Goddamit are character encoding problems annoying.

I’ve made sure php.ini, my.ini and the html file all have utf-8 encoding. I’m at my wit’s end, please send help.

Time difference problems when using FROM_UNIXTIME() – localhost vs. server – php / MySQL

I am trying to create an appointment booking system for a hairdresser.

The conception is that they open at 9:00 and close at 15:30. This is my timeframe.

Steps of booking:

  • choosing the service (it contains the duration of the service is seconds)
  • choosing the desired date (will be passed to a function when checking dates)
  • select date

I loop through the day and use the duration of the service to create timeslots, comparing if it the calendar has enough time to book before next scheduled appointment.

My problem is that now that we want to go live, timestamps for the bookable slots are different.

Let’s say I want to book for 2022-12-15 09:00:00.

On my local machine the timestamp is 1671091200.

And on the server for same card I get a value of 1671094800.

The problem is coming from here I guess:

$Date = "2022-12-15"; //this is a date coming from a dropdown
$DayStart = strtotime($Date." 09:00:00");

After converting to time, I have the time mentioned above: 1671091200

I discovered, that there are due to different time zone settings and most probably my machine is using UTC and the server CET.

I am based in Hungary and the website will go live in Germany and somehow I have to make sure that if I book for 09:00:00, it won’t be registered as 10:00:00.

And of course for future developments I need to know how to avoid this.

One more important thing. I am using the same remote database from the server. I open localhost, connect to db on server and works good – then open domain, connect to exact same db on same server and everything is shifted +1 hour,

Maybe if there is another option to maintain this without unix time, I am open to everything but calculations with duration seconds are done this way.

Currently I am using this query but I may have to prepare time data in php instead of MySQL:

INSERT INTO `timetable.appointments` (Name, Phone, Email, AppDate, AppStart, AppEnd, Duration, ServiceID) VALUES (?,?,?,?,from_unixtime(?),from_unixtime(?),?,?)

Thanks for reading and thinking along!

Have a nice day!

I tried to open the site from different hosts (localhost / domain) but I am not able to find an answer how to fix that in the future.

what is the add to cart hook in woocommerce

I am working on woocommerce right now and I am testing few things ,
I need to retrieve the data of the user and the product that is added to the cart,
for example when the user add the product to the list ,execute a function that

 <script type="text">
"user _id":'.get_current_user_id().',
"product_id":'.$product->get_id().',
"product_price":'.$product->get_price().',
"product_name":'.$product->get_name().',

</script>';

but I don’t know what is the correct hook to write it in the add_action(hook name,function name)

I tried the same thing when the user enter the product page and it is working well by the following code:


add_action( 'woocommerce_single_product_summary','get_product_data');

function get_product_data() {
    global $product;
    global $current_user;
    echo '      
        <script type="text/test" id="product_data">
        {   
            "user":
            {
            "user_id":'.get_current_user_id().',
            "user_name":'.$current_user->user_login.',            
            "user_email":'.$current_user->user_email.'
            },
            "product":
            {
            "product_id":'.$product->get_id().',
            "product_price":'.$product->get_price().',
            "product_name":'.$product->get_name().',
            "product_description":'.$product->get_description().',
            "product_type":'.$product->get_type().',
            "product_average_rating":'.$product->get_average_rating().',
            "product_parent_id":'.$product->get_parent_id().',
            "product_rating_count":'.$product->get_rating_count().',
            "product_review_count":'.$product->get_review_count().',
            "product_children":'.$product->get_children().',
            "product_image_source":'.$src.'
            }
        }
        </script>
        ';
}

then I tried this to the add to cart:

add_action( 'woocommerce_add_to_cart',array($this, 'get_add_to_cart_product_data'));
function get_add_to_cart_product_data(){
        global $product;
        global $current_user;
        echo ' <script>  alert("the user '.$current_user->user_login.' added succesfully the '.$product->get_name().' product to the cart"); </script>';
}

it displays the correct user but it don’t access the product,it gives me an error : Uncaught Error: Call to a member function get_name() on null
that means it does not have access on the product like the ‘woocommerce_single_product_summary’ hook.

any idea it would help me to solve my problem thanks you

Laravel – POST form refreshing page for no reason

I have a <form> which calls an AJAX function with method POST and after doing some stuff it refreshes the page and I don’t really know why. If anyone can point out the problem, I’d greatly appreciate it!

web.php

Route::post('reportEvent', 'ReportController@create')->name('reportEvent');

ReportController.php

public static function create(Request $request)
{
    $user_id = $request->input('user_id');
    $event_id = $request->input('event_id');
      
    $exists = DB::table('report')->where('users_id', $user_id)->where('event_id', $event_id)->get();
    if (count($exists) > 0) {
        return 2; # 'You have already reported this event!'
    }

    $report = new Report();

    $highest = DB::table('report')->max('id');

    $id = $highest + 1;

    $report->id = $id;
    $report->users_id = $user_id;
    $report->event_id = $event_id;
    $report->description = $request->input('description');
      
    $report->save();

    return 1; # 'Event reported!'
}

HTML

<form onsubmit="reportEvent({{ $event->id }}, {{ Auth::user()->id }}, description.value)" class="white-font" id="report-form">
    {{ csrf_field() }}

    <label for="description" class="white-font">Description</label>
    <input id="description" type="text" name="description" value="" class="report-textarea" placeholder="Write a report..."   required autofocus>

    <button type="submit" class="report-btn mgl10">
        Confirm
    </button>
</form>

JS/AJAX

function reportEvent(event_id, user_id, description) {
    $.ajax({
        method: "POST",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        url: "{{ route('reportEvent') }}",
        data: { event_id: event_id, user_id: user_id, description: description },
        success: function (response) {
            showReportStatus(response); //just changes some HTML elements
        }
    });
}

EDIT 1 – After submitting the form, I get a url of something like:
http://localhost:8000/event/2?_token=o3YCw1OnddF5YjPjdeYXbrfA0EUuY2Qba8Fkaw7v&description=gdfsf. Initially, the url is http://localhost:8000/event/2

exif_read_data immediately after a move_uploaded_file

I have made a script like this :

if(move_uploaded_file($src, $output_dir )){
$retour["statut"] = 0;
$retour["adresse"] = $output_dir;
//$exif = exif_read_data("http://wfr.zone/localisation_plantes/".$output_dir, 0, true);
$exif = exif_read_data($output_dir, 0, true);
if($exif===false) {
    $retour["exif_present"] = 0;
    
    $tout = "";
    foreach ($exif as $key => $section) {
        foreach ($section as $name => $val) {
            $tout .= "$key.$name: $valn";
        }
    }
    
    
    $retour["exif"] = $tout;

} else {
    $retour["exif_present"] = "Exif absent";
}

}else{
    $retour["statut"] = "move_uploaded_file n'a pas marché.";
};

The move_uploaded_file work, and if i download the photo, she still have the EXIF header.
But in the this script, the exif_read_data call return false.

Near that, i make the test file who use the precedent uploaded photo :

$exif = exif_read_data("http://wfr.zone/localisation_plantes/photos/20221207_122726.jpg", 0, true);
echo $exif === false ? "No header data found.<br />n" : "Image contains headers<br />n";

foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />n";
    }
    echo "<hr/>";
}

And the EXIF from the exif_read_data call is correct.

I do not understand why. Should I close something after the move_uploaded_file work ? I have read a lot, and it do not seem that there is something special.

Somebody have an idea ? Thanks !

Send two variables in headers php [closed]

  $path = 'http'."://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] ."/dashboard/theme/verifying.php?url=$url_validation" . ";"." email=$email,";


      $verification_link = "<a href='$path'>Your account verification link</a>";

How to refresh page and send request with some data via jquery

I am doing dynamic dropdown menu but I have problem to keep it after page refreshing.

I use maybe old way and if user choose some option in first select, I am sending ajax request to php page and show options on current page in second select.

I store all values of fields via localstorage, but problem is that selects (inputs) added dynamically by ajax are not visible on load of page.

So I decide to send my data to php page directly in request sent after refreshing.

My code is something like this:

    $(window).on('load', function() {
        // Send cat id to add.php to change select options in html according to cat id
        $.ajax({
            url: 'add.php',
            headers: {"X-Test-Header": "test-value"}
        });
    })

Is there some good way how to do that? Or should I for ex totaly change logic and use dynamically dropdown menu just with JS? Need to load tbale data form db to object.

Thanks

C# Get Data From MySQLDatabase With PHP

I just started C#. I want to exchange data from my remote server. I couldn’t find any code that would work for me. It would be great if you could help with code snippets. Some of my sample code is below.

My PHP Code;

<?php
include 'Connect.php';
$response = array();

if(isset($_POST['tag']) && $_POST['tag'] != '') {
    $tag = $_POST['tag'];
    
    if($tag == 'CheckUser') {
        
        $UserName = $_POST["UserName"];
        $Password = $_POST["Password"];
        
        try {
            $Check = "SELECT * FROM Users WHERE UserName=? AND Password=?";
            $query = $con->prepare($Check);
            $query->execute(array($UserName, $Password));
            $Dataa= $query->rowCount();
            if($Dataa> 0) {
                $response["success"] = 1;
                $response["message"] = "User Found";
            }
            else {
                $response["success"] = 0;
                $response["message"] = "User Not Found";
            }
        }
        catch(Exception $e) {
            $response["success"] = 0;
            $response["message"] = $e->getMessage();
        }
    }
}
else {
    $response["success"] = 0;
    $response["message"] = "You do not have transaction authorization";
}
echo json_encode($response);
?>

How can I get the results of “success” and “message” in C#? Could you please suggest a sample code snippet?

Docker phpdockerio/php:8.1-fpm builds with PHP version 8.2: How can I revert to 8.1?

I’m running my project on a PHP-FPM docker container (details of config files below). When I build my containers and attempt to run composer I’m getting errors reporting missing PHP extensions. However, I thought my build files where covering these extensions (see docker/php-fpm/Dockerfile below).

It turns out that the container is being built with php8.2 as the default version. I have been able to change the symlinks to set the default version back to php8.1 but this doesn’t seem like the right solution. Can anyone suggest a better fix?

How I know the container is running 8.2:
Inside the container I ran php --version and got:

root@fee8cc9ff790:/application# php --version
PHP 8.2.0 (cli) (built: Dec  8 2022 13:56:08) (NTS)

Then which php gave me:

root@fee8cc9ff790:/application# which php
/usr/bin/php

I followed the symlinks to find that linked PHP binaries in /etc/alternatives are:

phar -> /usr/bin/phar8.2
phar.phar -> /usr/bin/phar.phar8.2
php -> /usr/bin/php8.2
phpdbg -> /usr/bin/phpdbg8.2

This is the bit that doesn’t seem right to me. I was able to relink these to their 8.1 versions and things seem to be running fine now but what happens when I rebuild the container?

Details of my files:

docker-compose.yml

###############################################################################
#                          Generated on docker.io                          #
###############################################################################
version: '3.9'
services:
    mailhog:
        image: 'mailhog/mailhog:latest'

    redis:
        image: 'redis:alpine'

    mysql:
        image: 'mysql:8.0.27'
        working_dir: /application
        platform: linux/amd64
        environment:
            - MYSQL_ROOT_PASSWORD=
            - MYSQL_DATABASE=
            - MYSQL_USER=
            - MYSQL_PASSWORD=

    webserver:
        image: 'nginx:alpine'
        working_dir: /application
        volumes:
            - '.:/application'
            - './docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf'

    php-fpm:
        build: docker/php-fpm
        working_dir: /application/
        volumes:
            - '.:/application'
            - './docker/php-fpm/php-ini-overrides.ini:/etc/php/8.1/fpm/conf.d/99-overrides.ini'
            - './docker/php-fpm/php-ini-overrides.ini:/etc/php/8.1/cli/conf.d/99-overrides.ini'

docker-compose.override.yml

###############################################################################
#                          Generated on phpdocker.io                          #
###############################################################################
version: '3.9'
services:

    mailhog:
        ports:
            - '8026:8025'

    mysql:
        ports:
            - '33061:3306'

    webserver:
        ports:
            - '801:80'

docker/php-fpm/Dockerfile

FROM phpdockerio/php:8.1-fpm
WORKDIR "/application"

RUN apt-get update; 
    apt-get -y --no-install-recommends install 
        git 
        php-xdebug 
        php8.1-mysql 
        php8.1-sqlite 
        mysql-client 
        php8.1-redis; 
    apt-get clean; 
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

Product thumbnail does not show in cart drop down menu Laravel(bumbummen99/shoppingcart)

i am facing this issue where everything is displaying but product thumbnail does not show in cart drop down menu and when i visit the http://127.0.0.1:8000/product/mini/cart page i get “image”: null as shown below

{"carts":{"814a8a82665ce9e1fdf8db97d1546227":{"rowId":"814a8a82665ce9e1fdf8db97d1546227","id":"15","name":"Angised 0.5mg Tablet 10 'S","qty":4,"price":12,"weight":1,"options":{"image":null,"size":"0.5mg"},"discount":0,"tax":1.2,"subtotal":48},"c2452c3ec12fa191ac42161be14935a0":{"rowId":"c2452c3ec12fa191ac42161be14935a0","id":"17","name":"Cardace 5mg Tablet 10 'S","qty":3,"price":25,"weight":1,"options":{"image":null,"size":"Small"},"discount":0,"tax":2.5,"subtotal":75},"8ca52c69734d690cc1261de455a4ee3e":{"rowId":"8ca52c69734d690cc1261de455a4ee3e","id":"10","name":"Pinix 0.25mg Tablet 10 'S","qty":"1","price":30,"weight":1,"options":{"image":null,"size":"Pack"},"discount":0,"tax":3,"subtotal":30},"e8441eb85c22e56677ba4f2d9c5ecdf1":{"rowId":"e8441eb85c22e56677ba4f2d9c5ecdf1","id":"9","name":"Transamin (5ml) 500mg Injection 1 'S","qty":"1","price":110,"weight":1,"options":{"image":null,"size":"Medium"},"discount":0,"tax":11,"subtotal":110}},"cartQty":9,"cartTotal":289}

here is CartController

public function AddToCart(Request $request, $id){

    $product = Product::findOrFail($id);

    if ($product->discount_price == NULL) {
        Cart::add([
            'id' => $id, 
            'name' => $request->product_name, 
            'qty' => $request->quantity, 
            'price' => $product->selling_price,
            'weight' => 1, 
            'options' => [
                'image' => $product->product_thumbnail,
                'size' => $request->size,
            ],
        ]);

        return response()->json(['success' => 'Successfully Added on Your Cart']);

    }else{

        Cart::add([
            'id' => $id, 
            'name' => $request->product_name, 
            'qty' => $request->quantity, 
            'price' => $product->discount_price,
            'weight' => 1, 
            'options' => [
                'image' => $product->product_thumbnail,
                'size' => $request->size,
            ],
        ]);
        return response()->json(['success' => 'Successfully Added on Your Cart']);
    }

} 
// Mini Cart Section
public function AddMiniCart(){

    $carts = Cart::content();
    $cartQty = Cart::count();
    $cartTotal = Cart::total();

    return response()->json(array(
        'carts' => $carts,
        'cartQty' => $cartQty,
        'cartTotal' => round($cartTotal),

    ));
} 

and here is my main_master.blade.php file

function productView(id) {

//alert(id)
$.ajax({
type: ‘GET’,
url: ‘/product/view/modal/’+id,
dataType: ‘json’,
success: function(data){
//console.log(data)
$(‘#pname’).text(data.product.product_name_en);
$(‘#price’).text(data.product.selling_price);
$(‘#pcode’).text(data.product.product_code);
$(‘#pcategory’).text(data.product.category.category_name_en);
$(‘#pbrand’).text(data.product.brand.brand_name_en);
$(‘#pimage’).attr(‘src’,’/’+data.product.product_thumbnail);
$(‘#product_id’).val(id);
$(‘#qty’).val(1);

  //product price
  if (data.product.discount_price == null) {
    $('#pprice').text('');
    $('#oldprice').text('');
    $('#pprice').text(data.product.selling_price);
  } else {
    $('#pprice').text(data.product.discount_price);
    $('#oldprice').text(data.product.selling_price);
    
  }

  // Start Stock opiton
  if (data.product.product_qty > 0) {
          $('#available').text('');
          $('#stockout').text('');
          $('#available').text('Available');
      }else{
          $('#available').text('');
          $('#stockout').text('');
          $('#stockout').text('Out of stock');
      } // end Stock Option 

  //size
  $('select[name="size"]').empty();        
  $.each(data.size,function(key,value){
      $('select[name="size"]').append('<option value=" '+value+' ">'+value+' </option>')
      if (data.size == "") {
          $('#sizeArea').hide();
      }else{
          $('#sizeArea').show();
      }
  })
}

})
}

here is the preview

Preview of thumnail not showing

Does mysqldump cronJob work on 000webhost?

I am currently using a free plan on 000webhost. I want to backup my database daily so I made a php script executing mysqldump. Bellow is the code I used:

<?php
// Set database connection details
$host = 'localhost';
$user = 'id19943800_ppcvodatabase';
$password = 'hkYy^0[TVX17?>D0';
$database = 'id19943800_ppcvo';

// Set the filename for the backup
$filename = 'dataBackups/PPCVO' . date("Y-m-d-H-i-s") . '.sql';

// Dump the database using mysqldump
$command = "mysqldump --user={$user} --password={$password} --host={$host} {$database} > {$filename}";
system($command);
?>

I tried the script locally through XAMPP and it seems to work just fine. So, does 000webhost just does not support mysqldump cronjobs? or do I have an error in my script?

I tried to execute the script locally through xampp and it seems to work just fine.

phpMyAdmin config access denied for root with no password

My php code is below:

<?php
$host = 'localhost';
$dbname = 'db_skrining';
$user   = 'root';
$pass   = '';

$con = mysqli_connect($host,$user,$pass,$dbname);

if(!$con){
  die("Connection Failed".mysqli_connect_error());
}
echo "Success";
?>

And what I get is the error:

Fatal error: Uncaught mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: NO) in C:xampphtdocsskriningauthkonfigurasi.php:7 Stack trace: #0 C:xampphtdocsskriningauthkonfigurasi.php(7): mysqli_connect('localhost', 'root', '', 'db_skrining') #1 {main} thrown in C:xampphtdocsskriningauthkonfigurasi.php on line 7.

Here’s what the solutions I’ve tried so far:

  1. Changing the IP settings in the “phpMyAdmin/config.inc.php” into the port I’ve assigned on the Apache XAMPP MySQL main port in the “Service and Port Settings”. Not solved.

  2. Recheck numerous times about the port, the dbname, the user ‘root’ and the password it’s still the same as default settings (both in the config.icg and the sql.ini [haven’t changed anything so far]. But I noticed that the password section on “sql.ini” file is “your_password” (without “…”); if that’s the case. but not solved

  3. Use try{...} and catch(){}, mysqli_connect_strict also mysqli_connect_errno. still, not solved yet

Attachments:
conf.php file; editor used: VSCode

Thank you

Strtotime ACF datefield parses 1 jan ’70

I’m using this code but the output results in 01.01.70. Clearly my code is wrong. But for the life of me I don’t know where. The date comes from datefield ACF called ‘datum_event’.

     if ( function_exists( 'get_field' ) ) {
    $date = get_field( 'datum_event' );
    if ( $date && is_string( $date ) ) {
        $html .= '
' . date( 'd.m.y', strtotime( $date ) ) . '
    ';
    }
}

I was expecting to have the result of the input in the ACf datepicker.

Difference between PHP and JS [duplicate]

I cannot at this point understand what is the difference between PHP and JS (the only thing that I got is that PHP runs from the server instead of the client side), why should we use JS when PHP will always hide the source code! I’m searching everywhere for this answer!, is PHP with HTML like JS with node.JS? Can you hide css elements in PHP so people will not copy it?Can you do everything in PHP what you can do in JS, if yes then why would a person use JS to expose the code through source code?

Tried to find the answer online, various answers but still no good analogy for me to understand

Create a table of all invoices from Stripe API in PHP

I am trying to create a table in PHP of all invoices in the table with the Stripe API.

This is my code so far:

$result = $stripe->invoices->all(['limit' => 100]);

echo $result;

I don’t know how I can just display the invoice id, customer name and amount in a table. This is my first time working with Stripe and API’s.