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
Forgall
Oct 16, 2012

by Azathoth
Is there a way to connect to postgres server from php using ssl client certificate authentication instead of password?

Adbot
ADBOT LOVES YOU

spiritual bypass
Feb 19, 2008

Grimey Drawer
Negative string offsets in 7.1 seem fun and convenient

https://3v4l.org/8sndO

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Forgall posted:

Is there a way to connect to postgres server from php using ssl client certificate authentication instead of password?

Copying and pasting your question into Google indicates yes, there is.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

rt4 posted:

Negative string offsets in 7.1 seem fun and convenient

https://3v4l.org/8sndO

is that only for strings or is it for any array?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

The Wizard of Poz posted:

is that only for strings or is it for any array?

Negative offsets in strings using the array syntax is one of the new 7.1 features.

Negative offsets continue to not work in arrays, as it's actually possible to have negative numbers be actual legal, existing keys in PHP arrays.

stoops
Jun 11, 2001
I'm having some trouble with the logic and coding of this. Any help is appreciated.

I have an array of date intervals. I need to create another array of continous intervals. Sorry, I'll try to explain.

code:
array(
	(int) 0 => array(
			'startDate' => '2015-08-15 12:58:24',
			'stopDate' => '2015-08-15 13:00:04',
	),
	(int) 1 => array(
			'startDate' => '2015-08-15 13:00:04',
			'stopDate' => '2015-08-15 13:01:54',
	),
	(int) 2 => array(
			'startDate' => '2015-08-15 13:01:54',
			'stopDate' => '2015-08-15 13:03:34',
	),
	(int) 3 => array(
			'startDate' => '2015-08-15 15:43:24',
			'stopDate' => '2015-08-15 15:46:14',
	),
Notice how in the first 3 elements the stopDate from the previous matches the startDate from the next. That means it's continous.

I need to put the startDate from element 0 in it's own array with the stopDate that doesn't match with the upcoming startDate.

The output generated would be:

code:
array(
	(int) 0 => array(
			'startDate' => '2015-08-15 12:58:24', //this is from element 0
			'stopDate' => '2015-08-15 13:03:34', //this is from element 2
	),
    ////at this point a new array with the startDate from element 3
	(int) 1 => array(
			'startDate' => '2015-08-15 13:00:04', //this is from element 3
			'stopDate' => ...
	),
I hope this makes sense, and even pseudocode would help.

Depressing Box
Jun 27, 2010

Half-price sideshow.
Try using array_reduce:

PHP code:
$intervals = [
    [
        'startDate' => '2015-08-15 12:58:24',
        'stopDate' => '2015-08-15 13:00:04',
    ],
    [
        'startDate' => '2015-08-15 13:00:04',
        'stopDate' => '2015-08-15 13:01:54',
    ],
    [
        'startDate' => '2015-08-15 13:01:54',
        'stopDate' => '2015-08-15 13:03:34',
    ],
    [
        'startDate' => '2015-08-15 15:43:24',
        'stopDate' => '2015-08-15 15:46:14',
    ],
];

$result = array_reduce($intervals, function($acc, $interval) {
    $i = count($acc) - 1;

    if (isset($acc[$i]) && $acc[$i]['stopDate'] === $interval['startDate']) {
        $acc[$i]['stopDate'] = $interval['stopDate'];
    } else {
        $acc[] = $interval;
    }

    return $acc;
}, []);

var_dump($result);
// array(2) {
//   [0] =>
//   array(2) {
//     'startDate' =>
//     string(19) "2015-08-15 12:58:24"
//     'stopDate' =>
//     string(19) "2015-08-15 13:03:34"
//   }
//   [1] =>
//   array(2) {
//     'startDate' =>
//     string(19) "2015-08-15 15:43:24"
//     'stopDate' =>
//     string(19) "2015-08-15 15:46:14"
//   }
// }

YO MAMA HEAD
Sep 11, 2007

If there's a chance that a subsequent startDate may be slightly before the preceding stopDate, it might be worth looking at a library that can properly handle ranges—I used https://github.com/judev/php-intervaltree on an older project to reduce overlapping segments to a single segment.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
PHP newbie here. I'm trying to make a form that submits data to a database. I have the database set up fine, got it connected and disconnected properly. And I can even get the data submitting. The only problem is I'm trying to create functions to make the process easier and I'm having issues.

My index page:

code:
<?php require_once('connection/databaseconnect.php'); ?>
<?php require_once('functions.php'); ?>

<?php
//if the form is submitted, run the add_word function
if(isset($_POST['submit'])){
	add_word("$_POST");
}
?>

<!DOCTYPE html>
<html>
<head>
	<title>Test App</title>
</head>
<body>
<form method="post" name = "add_word">
	<input for="word" type="text" name="word" maxlength="30">
	<input type="submit" name="submit">
</form>

</body>
</html>

<?php require_once('connection/databasedisconnect.php'); ?>
My functions file:

code:
<?php
require_once('connection/databaseconnect.php');

function clean($a){
	$cleaned = mysqli_real_escape_string($connection, $a);
}

//extract data from the submitted form, clean for injections, then put the cleaned
// word into the database table
function add_word($info){
	extract($info);
	$cleaned_word = clean("$word");
	$query = "INSERT INTO words (word) VALUES ('$cleaned_word')";
	$result = mysqli_query($connection, $query);
}

?>
I know the add_word is running because if I echo $word, the value of the text form comes up just fine. I just can't get it added to the database

Also, I know extract with $_POST is bad practice, but I'm just practicing.

nielsm
Jun 1, 2009



The basic thing is that you are calling add_word() incorrectly, you pass a stringified version of $_POST which is useless, instead of just passing it directly.

This is wrong:
code:
add_word("$_POST");
This is better:
code:
add_word($_POST);
But the function ought to have a different signature altogether:
code:
add_word($_POST['word']); // passing just the data needed, instead of an array full of other junk that may or may not be needed
Also, you should never, ever use the extract() function.

You should also use parameterized queries instead of munging values and pasting them into SQL strings directly.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Okay. I tried fixing that stuff:

code:
function add_word($word){
	echo $word; //WORKING: echos the value from the text field
	$cleaned_word = clean("$word");
	$query = "INSERT INTO words (word) VALUES ('$cleaned_word')";
	$result = mysqli_query($connection, $query);
}
running the function

code:
if(isset($_POST['submit'])){
	add_word($_POST["word"]);
}
Still not workin

nielsm
Jun 1, 2009



Oh right, $connection in that mysqli_query call, that's probably a global. If it is you need to declare it as such at the start of the function body.

http://php.net/manual/en/language.variables.scope.phpv

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Okay. It's working and I got the clean function going as well.

PHP is weird, man. I miss JQuery right now

Also, will that clean function protect me from every SQL injection? Is there better ways of doing it or is real escape string efficient enough?

teen phone cutie fucked around with this message at 23:11 on Dec 29, 2016

Forgall
Oct 16, 2012

by Azathoth

Grump posted:

Okay. It's working and I got the clean function going as well.

PHP is weird, man. I miss JQuery right now

Also, will that clean function protect me from every SQL injection? Is there better ways of doing it or is real escape string efficient enough?
You should use PDO with prepared queries instead of mysqli_ functions. Those are deprecated. (edit: ok, mysqli_ isn't yet deprecated, was thinking about mysql_.)

This seems like a decent enough tutorial: http://www.phptherightway.com/#databases

Forgall fucked around with this message at 23:26 on Dec 29, 2016

McGlockenshire
Dec 16, 2005

GOLLOCKS!
mysqli is not and will not be deprecated. However, you should still consider using PDO while learning PHP, as using prepared statements with mysqli is unnecessarily annoying compared to the way PDO does it.

Unless you have no other plausible choice, never ever ever assemble SQL as a string using user-provided data. Always and only use prepared statements. There are times to break this rule due to restrictions on what you can do with prepared statement placeholders, but treat it as religious dogma until you begin doing advanced / weird stuff.

As a learner, something to keep an eye out for is the date on any tutorials you come across. Trust nothing made more than five years ago, and trust nothing designed for PHP versions prior to 5.3. If there is no date on the tutorial, assume it's trash and move on.

revmoo
May 25, 2006

#basta
IMHO stick composer in your app, add its autoloads, and then use eloquent to do your DB stuff. It uses PDO on the back end, and you can use it to just run plain queries, but it gives you a lot more power. Plus, you'll have composer which you can use to pull in other libs with ease.

revmoo fucked around with this message at 17:53 on Jan 26, 2017

Sab669
Sep 24, 2009

Dumb PHP question: What the hell do people write PHP in?

I'm setting up a phpBB forum my company which I need to make modifications to. I haven't used PHP in over 5 years when I was in college. And even then it was just for some stuff we'd write entirely ourselves so Notepad++ was fine. But jumping into an unfamiliar codebase with 1500 files in a language I haven't used in too long is a bit overwhelming.

After half a decade of using .NET I am a soft and delicate flower who misses things like "Go To Definition" to find where a variable is declared or a class/method implemented. Or "Find All References" to see every where in the codebase something is called.

Edit: I'm on Win7 if that matters.

Forgall
Oct 16, 2012

by Azathoth
PhpStorm isn't free, but they got a trial. Can check it out.

spiritual bypass
Feb 19, 2008

Grimey Drawer
PhpStorm is definitely the best, but NetBeans is the second best PHP IDE if you don't want to spend any money.

Sab669
Sep 24, 2009

Yea I doubt the bossman would buy the license given this is a lower priority project.

I used NetBeans for Java in college and hated it :( seemed so slow. Hopefully newer versions are better.


And goddamn I just realised that in N++ if I double click a variable name it doesn't grab the $ with it, so then the syntax highlighting highlights strings that match my selection and stuff :suicide:

spiritual bypass
Feb 19, 2008

Grimey Drawer
I've never worked for a company will pay for an IDE so I just pay for it myself. Personal license are cheaper than commercial ones.

Jetbrains licenses their IDEs for use on every machine you work with, so I use a single license both at home and at work.

revmoo
May 25, 2006

#basta
Yeah in this case I'd advise paying for PHPStorm yourself. I personally use Vim but if you're just getting re-acquainted PHPStorm will do some nice hand-holding.

joebuddah
Jan 30, 2005
Notepad++ works well for PHP too, and it's free!

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
Is there a function or sample code that can exactly reproduce javascript's deprecated escape() function? I know it's deprecated, but our partner won't update their code so we need to replicate it in PHP. I've tried googling but every response is just people saying "don't use deprecated code" and unfortunately we don't have that luxury.

nielsm
Jun 1, 2009



Sulla-Marius 88 posted:

Is there a function or sample code that can exactly reproduce javascript's deprecated escape() function? I know it's deprecated, but our partner won't update their code so we need to replicate it in PHP. I've tried googling but every response is just people saying "don't use deprecated code" and unfortunately we don't have that luxury.

Untested:

PHP code:
function js_escape($str) {
  $fn = function($matches) {
    $string = $matches[0];
    $offset = 0;
    $code = ord(substr($string, $offset, 1));
    if ($code >= 128) {        //otherwise 0xxxxxxx
      if ($code < 224) $bytesnumber = 2;                //110xxxxx
      else if ($code < 240) $bytesnumber = 3;        //1110xxxx
      else if ($code < 248) $bytesnumber = 4;    //11110xxx
      $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
      for ($i = 2; $i <= $bytesnumber; $i++) {
        $offset ++;
        $code2 = ord(substr($string, $offset, 1)) - 128;        //10xxxxxx
        $codetemp = $codetemp*64 + $code2;
      }
      $code = $codetemp;
    }
    if ($code < 256) {
      return sprintf("%%%02X", $code);
    } else {
      return sprintf("%%u%04X", $code);
    }
  }
  return preg_replace_callback("|[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./]|u", $fn, $str);
}
Based on spec at http://www.ecma-international.org/ecma-262/6.0/#sec-escape-string and sample from http://php.net/manual/en/function.ord.php#109812.
This "should" handle Unicode within the BMP, and fails with characters outside the BMP.

E: The best way to support non-BMP characters may be to first convert the input string to UTF-16 and then process that. It may even be shorter code.

nielsm fucked around with this message at 12:36 on Feb 10, 2017

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
You are amazing!! I tried recreating it myself earlier on using the RFC, but I was absolutely not capable of it.

A minor modification on the sprintf() and a missing semi-colon and it's reproducing exactly what I need:

php:
<?
function js_escape($str) {
    $fn = function($matches) {
        $string = $matches[0];
        $offset = 0;
        $code = ord(substr($string, $offset, 1));
        if ($code >= 128) {    
            if ($code < 224) $bytesnumber = 2;              
            else if ($code < 240) $bytesnumber = 3;        
                else if ($code < 248) $bytesnumber = 4;    
                $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
                for ($i = 2; $i <= $bytesnumber; $i++) {
                $offset++;
                $code2 = ord(substr($string, $offset, 1)) - 128;       
                $codetemp = $codetemp*64 + $code2;
            }
            $code = $codetemp;
        }
        if ($code < 256) {
            return sprintf("%%%'02X", $code);
        } else {
            return sprintf("%%u%'04X", $code);
        }
    };
    return preg_replace_callback("|[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./]|u", $fn, $str);
}
?>
Thank you so much. I've tested it with a bunch of different characters and it seems to be working exactly as I need it to. Even on a non-BMP character I tested, the output between the two is the same, and what's most important is the consistency between the outputs rather than the ultimate decoding, if that makes sense.

Sulla Faex fucked around with this message at 16:45 on Feb 10, 2017

Sab669
Sep 24, 2009

Having issues getting XDebug working.

- Windows 7
- IIS 7.5
- PHP 5.6
- phpBB3 is the application I'm trying to setup

I've downloaded and installed Netbeans. I pasted phpinfo(); output into XDebug's wizard. I downloaded the file the wizard linked, moved that C:\php\ext. I've added zend_extension = .\ext\dllFileName

I restarted IIS.

Load up Netbeans, open my project, adjust the "Project URL" settings and click Debug Project.

This opens my browser to http://localhost/phpBB3/?xdebug_session_start=netbeans-xdebug

But none of my breakpoints fire. Did I do something wrong? :saddowns:

Luxury Communism
Aug 22, 2015

by Lowtax

nielsm posted:

Also, you should never, ever use the extract() function.

old post but,

extract() has its uses. The example that comes to mind is before require()-ing a template.php inside a render() function

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Luxury Communism posted:

old post but,

extract() has its uses. The example that comes to mind is before require()-ing a template.php inside a render() function

yeah I ended up fixing that.

I was just watching Lynda tutorials at work bc I was bored and was trying to make a simple CRUD. The only time I ever worked in PHP was while I was still in school, and never really got the chance to wrap my brain around it.

I'm wondering if it's even worth learning or if it's more valuable to learn Node js as a server-side language, as I'm mainly working with Javascript at work.

spiritual bypass
Feb 19, 2008

Grimey Drawer
PHP has a huge, but mostly lovely base of installed software. PHP tends to pay less than other languages from what I can tell. Node had a sharp rise, but quickly hit a plateau in adoption.
If I was going to start learning a server-side language, I'd learn Python or Java. Python has lower barriers to entry.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Grump posted:

I'm wondering if it's even worth learning or if it's more valuable to learn Node js as a server-side language, as I'm mainly working with Javascript at work.

Doing server-side javascript requires not just learning how to deal with async bullshit in node.js, it also requires that you learn multiple mandatory tools. JS has an incredibly tiny standard library and the culture and tooling that's sprung up to try and deal with this problem are broken and probably unfixable.

PHP might be a poo poo language, but you aren't inexorably, permanently linked to broken tooling just by using it.

If you want to learn a better language than PHP, I'll echo the suggestion to learn python.

spiritual bypass
Feb 19, 2008

Grimey Drawer
gently caress it, learn Clojure

Sab669
Sep 24, 2009

Another dumb question (don't worry; I'm almost done with this project and then I can stop shitposting in here)

So I spent more time than I'd care to admit today tracking down a bug. Turns out I accidentally omitted a $ before a variable name.

My question is, why the gently caress didn't this blow up?

php:
<?
    for ($i = 0; i < count($someArray); $i++)
    {
        foo($someArray[i]);
    }
?>
I left the $ off the i in the middle of the for loop. When I executed this code, I expected it to run extremely quickly, but it ended up timing out after 10 minutes. As soon as I spotted the error I fixed it and it ran instantly.

Does that mean that i must've represented something? If not, why didn't this throw some sort of error?

men with puns
Feb 8, 2010
Young Orc
bare identifiers like 'i' are considered as references to constants, and by dubious tradition, if that constant's name wasn't already defined, it evaluates to itself (in this case, the string "i").

comparing a string with a number in that way generally causes the string to be parsed as a number, which always leads to good times (in this case, "i" is parsed as zero every time the loop iterates and the loop doesn't halt).

this evaluation-of-undefined-constant raises a notice-level error, but with common default php settings this notice doesn't interrupt execution, it just prints a message to stderr or wherever errors have been redirected by your server setup. so it's important to be able to figure out where to see the error output when running a script -- this would have been printing notices somewhere for those 10 minutes. this is also one reason many people like to configure php to use ErrorExceptions, like this example because it will make php be strict about those kinds of errors and cause an immediate termination of the script.

unfortunately php isn't as easy to deal with in windows; a lot of its history is tied closely to unix and related libraries. while it's easier to mix the two now, it's still greatly colored by its history with unix/linux and its relationship with server programs like apache. if it's an unexpected nuisance of a project, you just do the best you can do with php, i guess. but if you are going to spend more than a few weeks with it, it'll quickly start to pay off if you spend time getting familiar with the characteristics it inherited from linux & apache. hope that doesn't apply to you though!

spiritual bypass
Feb 19, 2008

Grimey Drawer
An IDE that puts a red underline under things like that is worth its weight in gold

bigmandan
Sep 11, 2001

lol internet
College Slice
There are some frameworks that registers a handler for notices and convert them to either errors or exceptions. You can do this your self too with:

PHP code:
<?php

$old_handler = set_error_handler("my_handler");

function my_handler($errno, $errstr, $errfile, $errline, array $errcontext = [])
{
	// deal with it here, throw an exception etc...
}
http://php.net/manual/en/function.set-error-handler.php

I find it pretty useful to do so as most php notices should be errors imo.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
EDIT: Post about a delete function. I ended up making unique pages for each row in my table and then adding a delete button on each page.

I originally wanted to list them all and have a delete button next to each item in the list, but I decided that was over my head, so I did it this way instead.

Hey! I'm getting better at PHP CRUD!

PHP code:
//Delete function. Grabs the id from the url then compares it to the id in the row 
//and deletes the appropriate row
function delete_word(){
	global $connection;
	$url_id = $_GET['id'];
	$query = "DELETE FROM words WHERE id = '".$url_id."'";
	if(mysqli_query($connection, $query)){
		echo "Deleted!";
		echo ("<SCRIPT LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated')
    window.location.href='index.php';
    </SCRIPT>");
	}
	else{
		echo "ERROR";
	}
}

teen phone cutie fucked around with this message at 20:42 on Feb 15, 2017

spiritual bypass
Feb 19, 2008

Grimey Drawer
The most important thing about that code sample is that it takes user in put from $_GET['id'] and sticks it directly into a query. You need to use a parameterized query to prevent a malicious user from carrying out an SQL injection attack.

http://php.net/manual/en/pdo.prepare.php

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

This is a dumb question, but I have a wordpress plugin that has since updated and says that it no longer supports PHP 5.2 and under. I checked my phpinfo and it says 5.4.45, which theoretically checks out. However the impression I get is "if not compatible with 5.2 then it's 7.0 only"; am I safe to upgrade this plugin, or do I have to upgrade to PHP 7?

Adbot
ADBOT LOVES YOU

Sab669
Sep 24, 2009

rt4 posted:

An IDE that puts a red underline under things like that is worth its weight in gold

I started using Netbeans instead of N++. I don't think it was underlined in yellow, but maybe it was. loving impossible to notice yellow underlining on a white background through. I suppose there would've been a notification flag in the line-number section... But yea; pretty sure there was no "heads up" :(

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