Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
handle
Jan 20, 2011

Any idea what the ODBC driver version is? yitam's comment on GitHub suggests that the visible error message may be a result of ARM64 not being included as a processor type in the driver code, but as part of a code path that's intending to warn about ODBC not being installed.

Adbot
ADBOT LOVES YOU

Impotence
Nov 8, 2010
Lipstick Apathy
MSSQL support is apparently broken on arm https://github.com/microsoft/msphpsql/issues/1292

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.

Well poo poo. I can confirm this by creating the same configuration on an x86 c5.l box and it works perfectly. I didn't think about driver support from third party vendors when testing graviton. :(

Impotence
Nov 8, 2010
Lipstick Apathy
to be fair, this is kind of ridiculously edge case - who is even using mssql on arm with the per processor licencing costs, not to mention that they have previously just outright said if you want ARM, use azure sql edge instead of mssql. windows people would just be running everything on amd64.

i'm not sure how to describe it, but it feels weird/i've rarely if ever seen a lamp stack or php user using mssql in the first place, and i've rarely if ever seen php running on windows, and same for arm and mssql.

Impotence fucked around with this message at 22:21 on Sep 4, 2021

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
I’m not running SQL server on a graviton processor. The SQL Server box is on an X86 server but I’m connecting to it using PHP on a graviton Ubuntu box.

But apparently I’m not, since the ODBC connector for SQL server isn’t supported.

Edit: With regards to PHP on windows or SQL server versus MySQL, in this application SQL Server blows the doors off of MySQL performance-wise so that’s the direction I went.

Agrikk fucked around with this message at 00:49 on Sep 5, 2021

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
Different project now:

I'm trying to time the download of a given file from various CloudFront pops and I'm having trouble getting the curl command right in PHP.

I have it running like so in DOS and gnuwin32:
code:
curl -w "@format.txt" -o chunks\%pop%.chunk -s "https://%distribution%.cloudfront.net/%payload%" --connect-to ::!_ip!
where
%pop% is the name of the endpoint that generates the IP address
%distribution% is the name of the cloudfront distribution
%payload% is the file to be downloaded. (This file is a broken chunk of a .wav file that's been snipped at exactly 1GB)
and !_ip! is the resolved IP address of the pop serving up the specified CF distribution

so I have this:
code:
<?php

$cURLConnection = curl_init();
curl_setopt($cURLConnection, CURLOPT_URL, "https://$distribution.cloudfront.net/$payload");
curl_setopt($cURLConnection, CURLOPT_FORBID_REUSE, true);
$connect_to = array("https://$distribution.cloudfront.net::$ip:");
curl_setopt($cURLConnection, CURLOPT_CONNECT_TO, $connect_to);


$file = curl_exec($cURLConnection);
curl_close($cURLConnection);
which doesn't appear to be working as $start and $end variables suggest an elapsed time in microseconds.

What am I missing?

Agrikk fucked around with this message at 08:34 on Oct 29, 2021

Bitcoin
Sep 12, 2021

Agrikk posted:

Different project now:

I'm trying to time the download of a given file from various CloudFront pops and I'm having trouble getting the curl command right in PHP.

I have it running like so in DOS and gnuwin32:
code:
curl -w "@format.txt" -o chunks\%pop%.chunk -s "https://%distribution%.cloudfront.net/%payload%" --connect-to ::!_ip!
where
%pop% is the name of the endpoint that generates the IP address
%distribution% is the name of the cloudfront distribution
%payload% is the file to be downloaded. (This file is a broken chunk of a .wav file that's been snipped at exactly 1GB)
and !_ip! is the resolved IP address of the pop serving up the specified CF distribution

so I have this:
code:
<?php

$cURLConnection = curl_init();
curl_setopt($cURLConnection, CURLOPT_URL, "https://$distribution.cloudfront.net/$payload");
curl_setopt($cURLConnection, CURLOPT_FORBID_REUSE, true);
$connect_to = array("https://$distribution.cloudfront.net::$ip:");
curl_setopt($cURLConnection, CURLOPT_CONNECT_TO, $connect_to);


$file = curl_exec($cURLConnection);
curl_close($cURLConnection);
which doesn't appear to be working as $start and $end variables suggest an elapsed time in microseconds.

What am I missing?

Try

["{$distribution}.cloudfront.net:443:{$ip}:443"]

aperfectcirclefan
Nov 21, 2021

by Hand Knit
Professional PHP touchers...

Do you find yourselfs using private and public and constants with the language? I'm going through PHP Panda as a refresher for a interview I have next week and they devote alot of time towards that, but I don't think i've ever really used those properties.

Thanks for the help.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I tend to make all of my class properties private (unless it's just a data holder class) and use constants to represent any magic values.

Are you encountering any scenarios that make you wonder about what's best?

aperfectcirclefan
Nov 21, 2021

by Hand Knit
Nah not really, I'd perfer to use them since it makes the language more like Java or C#, but I didn't want to do it and then have people be like "What are you doing? I can't read this!".

spiritual bypass
Feb 19, 2008

Grimey Drawer
The world of PHP definitely has its share of people writing it in the traditional style with no sense of design, but you won't meet those people outside of the world's worst workplaces for programmers. Use type hints, visibility, and interfaces without hesitation

aperfectcirclefan
Nov 21, 2021

by Hand Knit
Excellent alright, thank you very much.


It's hard to find what to expect for a PHP interview so I'm just hoping there isn't a bunch of algorithm questions lol.

itskage
Aug 26, 2003


Yeah if they have that reaction to it you probably don't want it?

Tei
Feb 19, 2011

cum jabbar posted:

The world of PHP definitely has its share of people writing it in the traditional style with no sense of design, but you won't meet those people outside of the world's worst workplaces for programmers. Use type hints, visibility, and interfaces without hesitation

this.

theres no reason to write bad code, even if some mechanism are not well supported yet... writing futureproff code will pay of later

also if you are salary man, having good code that can be the foundation of great programs is interesting

PHP does change behavior based on public, private, protected. I believe. but on top of it everything about giving PHP hints about types is desirable. Always paying attention the PHP version you have has target.

aperfectcirclefan
Nov 21, 2021

by Hand Knit
Thank you all for the posts. I didn't actually know Interfaces were that highly used but thats good because I like using them. It seems like PHP has matured alot lately which is probably great for you hardcore PHP developers!

A Real Happy Camper
Dec 11, 2007

These children have taught me how to believe.
I have a chunk of code that reads from a CSV and puts the data in it into an array:

code:
  function generateCard($row){ //Put the bingo card values into an array
    $playerFile = fopen("players.csv","r");
    $counter = 0;
    while (($data = fgetcsv($playerFile)) !== FALSE){
      $counter++;
      if ($row == $counter){
        return $data; 
        }
      }
    fclose($playerFile); //remember to close it so you don't leak memory!!!!
    }
do I need to put fclose before I return, or if I leave it here will it still do its job?

nielsm
Jun 1, 2009



The file should be closed when the request finishes, regardless of you closing it explicitly, but it's still good practice to explicitly close your handles.

Saoshyant
Oct 26, 2010

:hmmorks: :orks:


A Real Happy Camper posted:

do I need to put fclose before I return, or if I leave it here will it still do its job?

When your code hits a return, any code after is completely ignored -- some IDEs will even warn you of this, marking it as "unreachable code". That means you should do the fclose before the return.

"Oh, but my current structure wouldn't make this easy", you say. Should be easy enough to fix by having a returnable variable that is either empty or filled in case a match is found:

code:
function generateCard($row) { //Put the bingo card values into an array

    $card = [];

    $playerFile = fopen("players.csv","r");
    $counter = 0;
    while (($data = fgetcsv($playerFile)) !== false) {
        $counter++;
        if ($row == $counter){
            $card = $data;
            break;
        }
    }

    fclose($playerFile); //remember to close it so you don't leak memory!!!!

    return $card;
}
A function should always return something and your code as it was wasn't doing that in the first place.

Saoshyant fucked around with this message at 16:10 on Jan 14, 2022

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
FWIW, try-finally is often a better way to handle resource cleanup, e.g.:
code:

function generateCard($row) {
    $playerFile = fopen("players.csv","r");
    try {
      $counter = 0;
      while (($data = fgetcsv($playerFile)) !== false) {
          $counter++;
          if ($row == $counter){
              return $card;
          }
      }
    } finally {
      fclose($playerFile);
    }
}

Good Sphere
Jun 16, 2018

I'm trying to get php installed on macOS, using Intel processor. I've had it before, but I understand there has been some changes, and the brew install is your best bet. Seems to be installed, although php is showing the script instead of the rendered page in my browser. I'm using localhost in the address bar.

I followed these instructions: https://github.com/shivammathur/homebrew-php

spiritual bypass
Feb 19, 2008

Grimey Drawer

Good Sphere posted:

I'm trying to get php installed on macOS, using Intel processor. I've had it before, but I understand there has been some changes, and the brew install is your best bet. Seems to be installed, although php is showing the script instead of the rendered page in my browser. I'm using localhost in the address bar.

I followed these instructions: https://github.com/shivammathur/homebrew-php

Showing the script as text instead of executing means your web server isn't configured to send requests to PHP files to php-fpm. When I do local dev, I prefer to skip the web server config and use the PHP built in webserver to run my project because it's simpler

ModeSix
Mar 14, 2009

Good Sphere posted:

I'm trying to get php installed on macOS, using Intel processor. I've had it before, but I understand there has been some changes, and the brew install is your best bet. Seems to be installed, although php is showing the script instead of the rendered page in my browser. I'm using localhost in the address bar.

I followed these instructions: https://github.com/shivammathur/homebrew-php

Your best and easiest bet might be XAMPP: https://www.apachefriends.org/download.html

Good Sphere
Jun 16, 2018

ModeSix posted:

Your best and easiest bet might be XAMPP: https://www.apachefriends.org/download.html

Thanks! I was just looking into MAMPP, but now I have XAMPP installed and running, with my files.

One thing that got me was the php short tags. I turned it on, but regardless it just won't work. I know it's not safe because of the bad interactions it can have with xml. No big deal, I can write "<?php".

Good Sphere fucked around with this message at 01:34 on Jan 16, 2022

MREBoy
Mar 14, 2005

MREs - They're whats for breakfast, lunch AND dinner !
Ok I could use some advice to see if I made a significant OOPS on something I am working on (probably because I am not very experienced in PHP). For some background I play Foxhole a lot. In Foxhole you have buildings you can privately store things in, but if you don't visit the building at least once every 50 hours the stuff in there gets donated to public. So I started writing an app in PHP to help me catalog the stuff in various storage buildings and to track timers. One thing I need is an animated countdown timer to show how long until the 50 hours runs out. I found plenty of JavaScript examples and managed to get one to integrate enough to run, but I am having a problem.

What I am doing is pulling a list of buildings & info from a SQL source with a fairly simple connect to SQL then while($row = $result->fetch_assoc() to table cells type thing. I got the countdown timer to pick up on a date that is part of the SQL query but what happens is that if there is more than 1 row returned by the query the timer only appears on the 1st row and picks up its countdown time from the last row. So if there are 3 or 7 or 22 rows I only get 1 timer and its counting down the wrong time. Any ideas on how I might get this timer to function with more than 1 row ?

https://pastebin.com/Z8iBubVC for what I have written

nielsm
Jun 1, 2009



Two things:
You only have one instance of the countdown JS, and it only handles a single $countdown value.
And it looks for the cell to fill in the countdown by HTML "id", which is by definition unique inside the document, it's not allowed to have two HTML elements with the same "id".

What I'd personally do is make an empty cell in the output HTML from the PHP, give those cells a specific HTML "class", and then use a "data" attribute on them to store the countdown target. Then in the JS, you can search for all elements with the specific "class" value and create timers for each of them.

PHP code:
while($row = $result->fetch_assoc()) {
  echo "<tr>";
    echo "<td class='tg-dzk6' width='200 px'>", $row["creator"], "</td>";
    echo "<td class='tg-dzk6' width='200 px'>", date("H:i D d M Y e", $d_c), "</td>";
    echo "<td class='tg-dzk6' width='200 px'>", date("H:i D d M Y e", $d_r), "</td>";
    echo "<td class='tg-dzk6 countdowncell' width='200 px' data-expirytime='", $d_e, "'>"; # ----- THIS LINE -----
    echo date("H:i D d M Y e", $d_e); # just for some contents while the JS starts up
    echo "</td>";
    echo "<td class='tg-dzk6' width='200 px'>", $row["comments"], "</td>";
  echo "</tr>";
}
JavaScript code:
let countdown_cells = document.getElementByClassName("countdowncell");

countdown_cells.forEach((td) => {
  setInterval(() => {
    let remaining = td.dataset.expirytime - Date.now();
    td.innerhtml = remaining; // TODO: format this nicely
  }, 1000);
});
The JS code is only needed once, at the very end of the page, since it searches for all the cells and creates all the timers in its own loop.

Banditu
Mar 16, 2009
So the way you script works currently :
- in your while loop you set some variables (countdown) and you build three tables using those variables
- then once the loop is over you insert the countdown into a script that uses the last variable set in the loop. That's why you see the countdown for the last row

A way to solve this would be to set the expiration date as an HTML attribute in the table :

PHP code:
	
echo "<table class='tl' width='1000 px'>";
 echo "<tbody>";
   echo "<tr>";
   echo "<td width='200 px'><input type='submit' name='submit' value='DELETE'></td>";
   echo "<td width='600 px'  >Time Remaining: <BR><timer  data-expiration='".$d_e * 1000 ."' ></timer></td>";
   echo "<td width='200 px'><input type='submit' name='submit' value='REFRESH'></td>";
   echo "</tr>";
 echo "</tbody>";
echo "</table>";
Remove the demo id since timer is a specific tag and we can use it to find all the elements that are supposed to show a countdown.

Then use a script like this one to update each countdown.
JavaScript code:
var x = setInterval(function () {
    var now = <?php echo time() ?> * 1000;


    let timers = document.getElementsByTagName("timer");
    for (const timer of timers) {
        let expirationDate = timer.getAttribute("data-expiration");
        var distance = expirationDate - now;

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        timer.innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

        if (days === 2) {
            timer.style.color = 'blue';
        } else if (days === 1) {
            timer.style.color = 'green';
        } else if (days === 0 && hours <= 23 && hours >= 12) {
            timer.style.color = 'yellow';
        } else if (days === 0 && hours <= 11 && hours >= 6) {
            timer.style.color = 'orange';
        } else if (days === 0 && hours <= 5) {
            timer.style.color = 'red';
        }

    }
},1000);

Banditu fucked around with this message at 21:20 on Feb 13, 2022

MREBoy
Mar 14, 2005

MREs - They're whats for breakfast, lunch AND dinner !
Thanks for the replies to both of you :tipshat: . The last time I did anything with PHP was in a college class in 2012 or so. So while staring at this I slowly remembered that the output of PHP loops sort of don't exist until they get sent to the browser so you can't really change the contents with some other code (this is how my brain wants to think of it) so yeah I understand somewhat why the counter showed up where it did and why it was wrong.

Banditu I tried your solution and it works fine except for one thing - the countdown is no longer animated, it's static now. There was a line of "now = now + 1000;" in there which I'm guessing had something to do with it executing every second but that line is not present in what you wrote.

Banditu
Mar 16, 2009
You're right.

If i'm not mistaken just move :
JavaScript code:
    var now = <?php echo time() ?> * 1000;
before the line

JavaScript code:
var x = setInterval(function () {
....
and add back the
JavaScript code:
 now = now + 1000;
inside the setInterval function argument.

Edit : modified to follow nielsm advice
Replace
JavaScript code:
 	var now = <?php echo time() ?> * 1000;
by
JavaScript code:
var now = new Date().getTime();
No need for now = now + 1000;

Banditu fucked around with this message at 22:55 on Feb 13, 2022

nielsm
Jun 1, 2009



Nah you almost certainly want to check the actual client system time every time the interval timer runs in JS. You don't have any guarantee the timer runs exactly every 1000 ms, it can run a bit later and eventually you get noticeable timer drift. It can be okay to pass the server timestamp in from PHP, but you still want to at least calculate a time delta between page load and now with JS.

MREBoy
Mar 14, 2005

MREs - They're whats for breakfast, lunch AND dinner !

Banditu posted:

You're right.

If i'm not mistaken just move :

JavaScript code:
var now = <?php echo time() ?> * 1000;

var x = setInterval(function () {
 
now = now + 1000;

    let timers = document.getElementsByTagName("timer");
    for (const timer of timers) {
        let expirationDate = timer.getAttribute("data-expiration");
        var distance = expirationDate - now;
Not working :saddowns:

Edit: made changes that Banditu added, no change. I will say though if I try to select the displayed countdown time to copy it it deselects itself in about a second.... so it might be running but not updating the displayed time ? IDK :shrug:

MREBoy fucked around with this message at 23:41 on Feb 13, 2022

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Hey all, I'm having issues accessing a certain JSON variable through PHP and was hoping someone in here might have a idea as to what the hell I need to type to get the exact info I need.

Background:

I am using WooCommerce and accessing data. This is what the data looks like:
code:
"line_items": [
        {
            "id": 5289,
            "name": "Cat Training",
            "product_id": 445,
            "variation_id": 0,
            "quantity": 1,
            "tax_class": "",
            "subtotal": "4500.00",
            "subtotal_tax": "0.00",
            "total": "4500.00",
            "total_tax": "0.00",
            "taxes": [],
            "meta_data": [
                {
                    "id": 45407,
                    "key": "wc_deposit_meta",
                    "value": {
                        "enable": "yes",
                        "deposit": 2250,
                        "remaining": 2250,
                        "total": 4500,
                        "tax_total": 0,
                        "tax": 0,
                        "payment_schedule": {
                            "unlimited": {
                                "amount": 2250,
                                "tax": 0
                            }
                        }
                    },
                    "display_key": "wc_deposit_meta",
                    "display_value": {
                        "enable": "yes",
                        "deposit": 2250,
                        "remaining": 2250,
                        "total": 4500,
                        "tax_total": 0,
                        "tax": 0,
                        "payment_schedule": {
                            "unlimited": {
                                "amount": 2250,
                                "tax": 0
                            }
                        }
                    }
                }
            ],
            "sku": "",
            "price": 4500,
            "parent_name": null
        }
    ],
I'm trying to access line_items>meta_data>value>deposit. So far I have:

code:
  foreach ($order->get_items() as $item_id => $item){

        $item_data = $item->get_data();

        print_r($item_data['meta_data']);
    }
which returns me:

code:
Array ( [0] => WC_Meta_Data Object ( [current_data:protected] => Array ( [id] => 45407 [key] => wc_deposit_meta [value] => Array ( [enable] => yes [b][deposit] => 2250 [remaining][/b] => 2250 [total] => 4500 [tax_total] => 0 [tax] => 0 [payment_schedule] => Array ( [unlimited] => Array ( [amount] => 2250 [tax] => 0 ) ) ) ) [data:protected] => Array ( [id] => 45407 [key] => wc_deposit_meta [value] => Array ( [enable] => yes [deposit] => 2250 [remaining] => 2250 [total] => 4500 [tax_total] => 0 [tax] => 0 [payment_schedule] => Array ( [unlimited] => Array ( [amount] => 2250 [tax] => 0 ) ) ) ) ) ) 
but I can't for the life of me figure out how to properly navigate that array to get what I want.

I tried:

code:
$item_data['meta_data']['value']['deposit']
But I get a "value not a valid property" error.

Hoping someone here who is smart can help assist!

Thanks :v:

nielsm
Jun 1, 2009



"meta_data" is an array of objects, you need something like $item_data['meta_data'][0]['value']['deposit'] or probably rather a loop over it, in case there's multiple metadata.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


That print_r is saying $item_data['meta_data'] is an array so you'd need $item_data['meta_data'][0] to start. After that, current_data and data are the only properties and they are protected so you might need another method call to get the value.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Thank you both that seemed to solve it besides the protected layer :suicide:

ModeSix
Mar 14, 2009

It's funny, I just solved this problem for myself just yesterday on something I was working on.

You could also do something like this:

code:
$deposit = array_column($item_data, 'deposit');
deposit is an object inside the array, so not directly accessible but you can get it by column name, maybe?

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Yeah I ended up just cheating and using WooCommerce's built in functions to not have to deal with it lol. I hope for any of you you never have to interact with HubSpot's API. It is a nightmare.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Speaking of nightmares :suicide:

Hoping someone can help me figure this out.

quote:

Hello, i'm trying to figure out how to send a time stamp correctly to a datepicker property. I've done some research on here but can't really find a answer.

Here's the time stamp:

$time = 1632182399;

I had did some research and found a contributor had suggested this solution: https://community.hubspot.com/t5/APIs-Integrations/Update-Custom-Date-Picker-in-Deals-through-the-AP...
But this doesn't actually work and I don't know why.

code:
function get_time_for_hubspot($time){
    $date = new DateTime();
    $date->setTimestamp($time);
    return gmdate('Y-m-d H:i:s', strtotime($date->format('Y-m-d H:i:s')));
}

 // Time Stamps
    $starttime = strval($booking_object->start);

    $endtime = strval($booking_object->end);

    $starttime = get_time_for_hubspot($starttime);
    $endtime = get_time_for_hubspot($endtime);
Which produces:
$starttime = 2021-09-13 00:00:00
$endtime = 2021-09-13 23:59:59So I think i'm just missing a final step or something. ANy help would be greatly appreciatedThanks for any help.


This is what hubspot says needs to be sent for time:

https://legacydocs.hubspot.com/docs/faq/how-should-timestamps-be-formatted-for-hubspots-apis

Unfortunately all of their documentation is confusing

Banditu
Mar 16, 2009
According to the thread and their documentation you need to send a timestamp in microseconds with the hour part as 00:00:00 UTC.

The timestamp you posted is in seconds you need to multiply it by 1000.

Test with this timestamp for example : 1632096000000

You can use this website to test your timestamps : https://www.epochconverter.com

worms butthole guy
Jan 29, 2021

by Fluffdaddy

Banditu posted:

According to the thread and their documentation you need to send a timestamp in microseconds with the hour part as 00:00:00 UTC.

The timestamp you posted is in seconds you need to multiply it by 1000.

Test with this timestamp for example : 1632096000000

You can use this website to test your timestamps : https://www.epochconverter.com

Thanks for that. For some reason the HubSpot API still doesnt want to take it :negative: . I guess I need to figure out how to properly translate it to UTC in PHP. I tried sending it the following:

code:
17763995520000
and it still won't take it :negative:.

Adbot
ADBOT LOVES YOU

worms butthole guy
Jan 29, 2021

by Fluffdaddy
I figured it out, if anyone ever has to deal with this poo poo:

Hubspot needs the time in Y-m-d format so:

code:
function convert_time_to_milliseconds($time){
    print_r("Time is: " . $time);

    print_r("Time * 1000 is : " . $time * 1000);
    return $time * 1000;
}

function get_time_for_hubspot($time){
    $d = DateTime::createFromFormat('U.v', number_format($time/1000, 3, '.', ''));
    return $d->format("Y-m-d");
}
running the time in seconds through this worked.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply