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
karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

what the gently caress

v1nce posted:

That's it. The "." on the end. Also: http://to./

what the gently caress!

Adbot
ADBOT LOVES YOU

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

v1nce posted:

Support looks a bit sketchy for Safari and may not do exactly what you want. Wrapping it up in some JavaScript should be a more catch-all fix.

Maybe something like this (html5)?

Ok, yeah I have a tendency to decide I want to do something a certain way without first making sure it will work in all browsers.
I'm not a front-end guy...

What would be the best way to handle IDN domains in those fields? Even if I just skip validation altogether if it's detected to be UTF-8 content in the field.

Edit:
This looks promising.
https://mothereff.in/punycode

Edit 2:
I think I'm going to skip the client-side validation for now. It's proving to be a bit more challenging than expected.
I really only need the validation on two forms, both of those forms have multiple rows of records to validate.
Maybe I'll post in the jquery / javascript thread and see what suggestions they have for implementing your jsfiddle example with the structure of my form and existing javascript.

The back-end validation works perfect so far. Thanks again for all your help v1nce!!!

DarkLotus fucked around with this message at 16:19 on Mar 23, 2016

revmoo
May 25, 2006

#basta
Ok, in the least amount of characters, what's the best way to identify true/false if an IP is local or not.

I know it can be done in one line, just not sure the smartest method. Here's what I've got so far:

filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)

e: filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) ? true : false

revmoo fucked around with this message at 18:41 on Mar 25, 2016

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) ? true : false

That'll only return true if it's an IP and it's also not in the local range. This can fail if you're actually looking for private range IPs, as the filter will return false if it's private or if it isn't an IP. To work around this, you'll need to pair up the filters: one to validate that it's an IP to begin with, then a second one to check for the local range. Something like this:

code:
function ip_is_local($ip) {
    $is_an_ip = (bool)filter_var($ip, FILTER_VALIDATE_IP);
    $is_not_a_local_ip = (bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
    return $is_an_ip && !$is_not_a_local_ip;
}
This way you'll get true if and only if it's both an IP and within the private range. This fails the "least amount of characters" test, though. Hope this isn't for a golf...

revmoo
May 25, 2006

#basta
That's pretty good actually. A bit verbose but definitely more accurate. Not that accuracy is that important here (making one of those stupid war games hack maps so VPs can show off to visitors to our NOC)

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah

revmoo posted:

A bit verbose

code:
function ip_is_local($ip) {
    return (bool)filter_var($ip, FILTER_VALIDATE_IP) ? (!(bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) : false;
}
:v:
(untested)

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
Can someone convince me why I should be fixing notices related to array indexes? Because I don't see what the point is.

There's a bunch of places in our code where we have something like:

php:
<?
if ($row['bacon']) {
    // dosomestuff
}
?>
What is the advantage of adding a
code:
isset($row['bacon']) &&
? If I'm already doing a false-y check then I'm very cool with the null value that php will spit out at me for an unset array index.

spiritual bypass
Feb 19, 2008

Grimey Drawer
None. Just set error level to warnings only.

revmoo
May 25, 2006

#basta
That is one of the things that annoys me about PHP. It's all loosey-goosey with variables and their state, UNTIL you try and hit an array item that doesn't exist.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

IT BEGINS posted:

Can someone convince me why I should be fixing notices related to array indexes? Because I don't see what the point is.
Without the notice that you're trying to check an undefined array index, you leave your code open to simple human error.

php:
<?
$row['bacon'] = true;

if ($row['bacan']) {
    // dosomestuff
}
?>
The if block will fail because the key contains a typo. With the warning silenced, you'll have to dive into troubleshooting when the code doesn't work correctly. People turning those warnings off are leaving themselves open to hidden bugs.

IT BEGINS
Jan 15, 2009

I don't know how to make analogies

McGlockenshire posted:

The if block will fail because the key contains a typo. With the warning silenced, you'll have to dive into troubleshooting when the code doesn't work correctly. People turning those warnings off are leaving themselves open to hidden bugs.

I suppose that makes sense. That said, I'm sure that I waste more time having to do isset() everywhere vs. the few times I mistype an array index and it doesn't work. Still, something to consider. Thanks :)

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

IT BEGINS posted:

I suppose that makes sense. That said, I'm sure that I waste more time having to do isset() everywhere vs. the few times I mistype an array index and it doesn't work. Still, something to consider. Thanks :)

!empty(). You're welcome.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
empty() is not a suitable replacement for many ways isset() is used. isset() is basically !is_null() with a suppression of undefined var & undefined index errors. empty() does the same suppression, but it goes beyond just a null check and considers empty strings and zero to be empty, something isset() does not do.

Use the right tool for the right job. If you need to make sure an array index exists, use array_key_exists(). If you need to make sure a variable exists and contains a not-null value, use isset(). If you need to make sure a variable contains something other than null, the empty string, or zero, use empty().

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
/\/\/\/\/\/\ Dammit.

KARMA! posted:

!empty(). You're welcome.

I'm not sure that's going to save you any isset()'s:
Edit: Huh. You're right and I'm retarded. An empty check on an array key does in fact not throw a notice.

Also beware that empty() is coercive. By this I mean that "0" (zero as a string) results in false, which may nor may not be what you were expecting it to do:
code:
$x = [
    'true       ' => true,
    'false      ' => false,
    'null       ' => null,
    'empty      ' => '',
    'zero       ' => 0,
    'one        ' => 1,
    'string_zero' => '0',
    'string_one ' => '1',
];

foreach($x as $y=>$z) {
    echo $y . ':' . empty($z) . "\n";
}

true       :
false      :1
null       :1
empty      :1
zero       :1
one        :
string_zero:1
string_one :
empty() is basically doing this:
code:
function empty($val) {
    return (false === (bool) $val)
}
Why is this a problem? Say you have an input field where a user can legitimately put in "0", (as in, number of fucks I give), and you do an empty() check as part of your validation; their entry "0" will always come back as invalid. Yes, even if it's a string, not an int, because of the coercion.

I know Symfony is a big fan of accessor classes to avoid this kind of isset bullshit. Here's a custom implementation:
code:

class Accessor
{
    /** @var array */
    private $array;

    /**
     * @param array|\Traversible $array
     */
    public function __construct($array)
    {
        $this->array = $array;
    }

    /**
     * Getter
     * @param string $key
     * @return mixed|null
     */
    public function get($key)
    {
        if (array_key_exists($key, $this->array) {
            return $this->array[$key];
        }
        return null;
    }

    /**
     * Setter
     * @param string $key
     * @param mixed $value
     */
    public function set($key, $value)
    {
        $this->array[$key] = $value;
    }
}
Usage:
code:
// Use accessor to work with the array
$input = new Accessor($_REQUEST);

// Safely expect a value or null. NO MORE ERRORS.
if ($input->get('num_of_fucks') > 0) {
    throw new \UnexpectedValueException('Not implemented: IDGAF');
}
Mmmm, classes. Extend and modify as required. If $x->get('xyz') is too tedious, just pull it into a placeholder variable $numFucks before doing your checks on the value.

Edit: To address the original question

IT BEGINS posted:

Can someone convince me why I should be fixing notices related to array indexes? Because I don't see what the point is.
What is the advantage of adding a
code:
isset($row['bacon']) &&
? If I'm already doing a false-y check then I'm very cool with the null value that php will spit out at me for an unset array index.

You should fix the notices because notices are generally a sign that your code is doing things that are unhealthy. Weirdly in this instance it's "not that bad" and fixing it won't actually give you much more safety. Of course, this depends on the code as a whole, and in most situations I would recommend you do not ignore notices.

You don't want to suppress notices (or anything) in dev because they will flag up all sorts of stuff that's truly important in certain situations. As McGlockenshire said, a notice about array access would generally tell a developer they have a typo in their code, and much like an Undefined Variable warning it's telling you that you're trying to access something that doesn't exist. In the world of code, that's usually a mistake and not an intended outcome.

In review, when I see an isset() check, it indicates to me that the array may-or-may-not contain that key. If there's no isset check, I'll assume it's supposed to always exist (and review up the call stack to ensure that's true). This makes the code more verbose and allows me to infer things about the data.
On the other hand, using tools like accessors to fetch data from the array tells me that it's OK for it to return a null, and I'd expect that case to be explicitly handled in the code.

Without these extras, a coder might just assume the array key will always contain "true" or "false". It's not explicit enough that it could also dump out a "null" intentionally.

There are lots of ways to avoid this problem; isset, classes with hydration, accessor class, and defaults. The defaults is the easiest, and looks like this:
code:
// Form defaults
$formDefaults = [
    'numFucks' => 0,
    'herpDerp' => null,
    'thingsWeCantHave' => ['nice'],
];

// Merge our users submission; which might contain no fields at all!
$userSubmission = array_merge($formDefaults, $userSubmission);

// Semi-safe
if ($userSubmission['numFucks'] > 0) {
    // ...
}
array_merge will replace any key in the Defaults with a key from the submission, and leave the rest. This means you know the userSubmission now has every key, with some acceptable defaults.

The problem with this approach, and why I didn't use $_REQUEST as the example, is you don't have any sanitisation of the type of value you're merging. For instance, 'thingsWeCantHave' may no longer be an array, and may be null, or an int. This is why form systems exist, which sanitise the incoming data to expected formats and types.

Of course, if you're not using this as a poor-mans-form-system, it might be totally OK for you do use this approach and pad out your array. As McGlockenshire said, it's a case of using the right tool for a job.

v1nce fucked around with this message at 00:35 on Mar 29, 2016

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Yeah I know all that. When I'm writing php I'm always aware of the type juggling that goes on behind the scenes and know implicitly that pretty much all boolean checks are of the falsy/truthy variety and figured that any php developer would know this as well. I find that isset() is used in a ton of places where you actually wanted to know if a variable holds a workable value and not just any value at all. This results in a lot of if(isset($something) && something == true) (and friends) that is in my opinion too verbose for what you want.

Yes, there are scenarios where the difference between a variable not existing and a variable that exists-but-is-set-to-0 is important, but then you can encode that specificity by not using empy for that check. It creates a good barrier between 'I want to know i I have something workable so I can move on' and 'I need this variable to be of a specific type and please don't jiggle my types'.

If you don't have a running commentary in your head of "ok, I'm checking for truthyness here so would it matter if the input I'm checking actually contains a string with a zero in it" then I feel bad for you. Well I feel bad for everyone having to deal with type juggling at all but more so if you don't keep you eye on the ball so to speak.

v1nce posted:

I'm not sure that's going to save you any isset()'s:
Edit: Huh. You're right and I'm retarded. An empty check on an array key does in fact not throw a notice.

That's why empty is is useful! You can't put in functions or methods though which is a shame. Or maybe they fixed this in a version I'm not privvy to? Seeing as I don't even get shorthand array syntax I'm missing out on a lot you see. Edit: woo, I've only got to wait until we are running 5.5! Chistmas 2020 here I come! :dance:

v1nce posted:

Edit: To address the original question


You should fix the notices because notices are generally a sign that your code is doing things that are unhealthy. Weirdly in this instance it's "not that bad" and fixing it won't actually give you much more safety. Of course, this depends on the code as a whole, and in most situations I would recommend you do not ignore notices.

You don't want to suppress notices (or anything) in dev because they will flag up all sorts of stuff that's truly important in certain situations. As McGlockenshire said, a notice about array access would generally tell a developer they have a typo in their code, and much like an Undefined Variable warning it's telling you that you're trying to access something that doesn't exist. In the world of code, that's usually a mistake and not an intended outcome.

There are quite a few instances where it's not much of a problem, until it does. Fix a notice, plant a tree, save a life. Do good in the world.

karms fucked around with this message at 01:08 on Mar 29, 2016

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

KARMA! posted:

Yeah I know all that.
I figured you would, it was more just to illustrate the issue for anyone else that isn't aware. I've seen a lot of junior devs drop the ball with empty().

KARMA! posted:

I find that isset() is used in a ton of places where you actually wanted to know if a variable holds a workable value and not just any value at all. This results in a lot of if(isset($something) && something == true) (and friends) that is in my opinion too verbose for what you want.
I agree with that observation, but I find it's often used in code which is performing two separate tasks being muddied in one operation; both data sanitisation AND business logic. You can fix a lot of isset() cases by making those steps happen separately in two distinct blocks of code. It's way easier to test, debug, and step through code with that clear demarcation between the two stages, and it's amazingly easy to refactor away lines of code once you don't have that mud in your eyes.

In code review I consider an array with ephemeral keys to be pretty unsafe and hairy, and personally I hate working with them in bulk. In most cases I'll demand they get form sanitized (which provides the defaults and structure checks) before they hit any business logic. We use Doctrine a lot, so most times we actually hydrate data into classes rather than leave arrays floating around the system. We only have a few rare cases in our system where fully dynamic arrays are required and can't easily be mapped to something less dodgy.

KARMA! posted:

you can encode that specificity by not using empty for that check. It creates a good barrier between 'I want to know i I have something workable so I can move on' and 'I need this variable to be of a specific type and please don't jiggle my types'.
Trouble is, I feel that blurs things for my developers. I'd like them to know what they can use for sanitisation and what they can use for logic, and not have to know "oh XYZ is ok for Objects and Arrays, but you've got to ABC for strings, ints and booleans". It's much easier to think of it in terms of "was something supplied for this value? yes/no" followed with "was that something of type x/y? yes/no" for sanitisation. As you go down that road, you end up separating those responsibilities in code, then refactoring it into shared tools and methods, and finally you have a sanitisation system where you just give it rules from a high level and watch it un-gently caress your data.

This is mostly in regards to working with forms (yay CRUD), but it can be done with hydrators and serialisers, too. We get this for free internally with Doctrine, entities, and cast getter/setters.
All this works ends up with a lot of domain knowledge rather than PHP knowledge, but it's a necessity when the alternative is writing the same crap code every day for a year.

KARMA! posted:

Fix a notice, plant a tree, save a life. Do good in the world.
"What can I do that will make the other developers hate me less?"

v1nce fucked around with this message at 02:09 on Mar 29, 2016

stoops
Jun 11, 2001
I have a list of dates, 30 of them

code:
array(
	(int) 0 => '20140801',
	(int) 1 => '20140802',
		.....
    (int) 30 => '20140831'
I also have a list of files with long pathnames. these can be over 4000 sometimes

code:
array(
	(int) 0 => '/web/space/webroot/data/nav/NAVCAM/Cruise_phase_Examples/Mars_flyby/xxx1_20070224T183232.FITS',
	(int) 1 => '/web/space/webroot/data/nav/NAVCAM/test/Mars_flyby/xxxx1_20070224T191032.FITS',
	(int) 2 => '/web/space/webroot/data/nav/NAVCAM/Earth_flyby/planet/xxx_20071113T210056.FITS',
    	......
    (int) 4000 => '/web/space/webroot/data/nav/NAVCAM/STP013/xxxx_M1_20140819T040718.FITS'    
I need to check if each of the dates is listed on the files array. if they are, add it to a new array.


Now, i thought i could do a loop in the dates and do a preg_grep

code:
foreach ($dates as $date){
	$newArray[] = preg_grep("/".$date."/", $filesArray);
}
This works for 200 files or so, but once it starts getting higher, it boinks. (I run out of memory)

Is there any other way to optimize this?

Any help is appreciated, thanks.

revmoo
May 25, 2006

#basta
Have you tried doing

$newArray = [];
foreach ($dates as $date) {
foreach ($files as $file) {
if (strpos($file, $date !== false)) $newArray[] = $file;
}
}

?

Seems like it would probably have adequate performance.

stoops
Jun 11, 2001

revmoo posted:

Have you tried doing

$newArray = [];
foreach ($dates as $date) {
foreach ($files as $file) {
if (strpos($file, $date !== false)) $newArray[] = $file;
}
}

?

Seems like it would probably have adequate performance.

Significantly faster. Thanks alot!

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
Laravel Question...

Trying to access AWS SQS to pull bounce and complaint reports that were pushed to SQS from SES.
Do I have to use the AWS SDK directly or can I use the built in Laravel Queue facade to access the SQS queue?
I've been looking and can't find any way to access the Queue with Laravel without writing a custom class or just using the AWS SDK to do it manually.

Synter
Sep 22, 2004

College Slice

DarkLotus posted:

Laravel Question...

Trying to access AWS SQS to pull bounce and complaint reports that were pushed to SQS from SES.
Do I have to use the AWS SDK directly or can I use the built in Laravel Queue facade to access the SQS queue?
I've been looking and can't find any way to access the Queue with Laravel without writing a custom class or just using the AWS SDK to do it manually.

Can't say for sure with SQS, but most AWS stuff needs to use signed requests. The AWS SDK will handle all of that for you.

I'm no expert with Laravel either, but I've had some success extending the Elastica client (before the latest relase, I should probably update my deps) to sign requests using the AWS SDK because AWS doesn't provide a CloudSearch client - so it might be possible to do something similar?

The AWS SDK will allow you to sign any PSR7 request, so if Laravels Queue stuff uses PSR7 you could do that maybe?

Synter fucked around with this message at 10:43 on Apr 8, 2016

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!
Forgot to reply... I decided to just create a custom SQS Queue and Message handler for my specific needs.
I'm using SES and need to process the Bounces and Complaints so those go to two SQS queues which I then need to handle.

Got it all working, can't use the default Laravel Queue stuff since it's really not designed to work that way.

jiggerypokery
Feb 1, 2012

...But I could hardly wait six months with a red hot jape like that under me belt.

Has anyone tried to retrofit migrations into a Symfony/Doctrine project that doesn't have them? I've got a bunch of clients with various versions of the project and am struggling to come up with a strategy to achieve this in any sensible way. Advice please!

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

jiggerypokery posted:

Has anyone tried to retrofit migrations into a Symfony/Doctrine project that doesn't have them? I've got a bunch of clients with various versions of the project and am struggling to come up with a strategy to achieve this in any sensible way. Advice please!

Yes, use Phinx, it doesn't care about your framework, has it's own API for building tables/adding columns (I still prefer to use straight SQL), and you can drop it into a project at any time. I used dropped it into a massive database at my place of work. Giant Postgres database with over 650 tables, works great for everything going forward.

jiggerypokery
Feb 1, 2012

...But I could hardly wait six months with a red hot jape like that under me belt.

I've used Phinx before, I even contributed. I can't recall if it got merged though. Is there any reason you recommend using it along side doctrine? The migration bundle probably has everything I need, it is more a case of how to get a consistent migration history between databases in different states. Perhaps this is more a question for the SQL or general programming thread. How would you approach the problem, using Phinx or otherwise?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

jiggerypokery posted:

How would you approach the problem, using Phinx or otherwise?

At my previous job, we had a pretty straightforward system. We did not use an ORM with tooling, so we managed the schema ourselves. This system predates pretty much all modern tooling, now that I've thought about it a bit, otherwise we'd have used something else.

There's a directory containing the version updates. Each version update itself is another directory, named after the version number parsable by version_compare() for sorting. The software knows the current version and scans the directory for the current version and the immediately previous version for files. The files are named in numerical order, like 08-account-fields-index.sql. Each file gets a row in a version table. If a file is found that doesn't exist in the version table, it's put in a queue to execute. Once the list of files is collected, they're run in version order and numerical order, with SQL files being exploded on semilcolons and PHP files just being included. After each file is successfully executed, it's logged in the version table. All of this is stored in source control with the rest of the code, so deploys can simply always try to perform a migration on rollout and get a guarantee that the code and the database changes are in lockstep.

We found three problems with this solution.

First, the dev team needs to collaborate on file numbering and version directory placement. This can get messy under both distributed development (we were an svn shop) and if you suddenly need to bring a dev-only feature into stable unexpectedly (instead of waiting for a trunk release to become the new stable).

Second, the updates themselves need to be aware that they might get run multiple times needlessly, during development. Using ... IF NOT EXISTS everywhere became needed, but there are some DDL statements that can't have exists checks, and that got irritating.

Third, we didn't build a rollback mechanism. Upgrades are one way. Usually this wasn't a problem, but maybe we got lucky. With schema detection like Doctrine provides, it can do migration of the database format easily. The Doctine CLI tool will produce SQL statements when prompted, and it should be "easy" enough to make it produce both forward migration scripts and reverse migration scripts.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

jiggerypokery posted:

I've used Phinx before, I even contributed. I can't recall if it got merged though. Is there any reason you recommend using it along side doctrine? The migration bundle probably has everything I need, it is more a case of how to get a consistent migration history between databases in different states. Perhaps this is more a question for the SQL or general programming thread. How would you approach the problem, using Phinx or otherwise?

I specifically wanted to de-couple my ORM from my migrations (I do this even for brand new Symfony/Doctrine projects). I ditched Doctrine Migrations because it seemed like it was being abandoned (they may have picked up development on it recently), and my migrations are straight SQL.

If you want to get consistent databases, I think you're best bet would be to create the migrations for the existing schema, manually record those entry in whatever table you use to store the migrations that have been executed in, and then you can rebuild any database based off those migrations.

For example, if you had an existing table named users that looked like this:

code:
users
----------
user_id integer not null default nextval('users_user_id_seq')
created_at timestamp without time zone
updated_at timestamp without time zone
username text NOT NULL,
password_hash text NOT NULL,
full_name text NOT NULL

indexes
------------
users_pkey (user_id)
UNIQUE users_username_idx (username)
You could create a new migration that looked like this (in Phinx) named 20160405191228_create_users_table.php:

php:
<?php

use Phinx\Migration\AbstractMigration;

class CreateUsersTable extends AbstractMigration
{
    /**
     * Migrate Up.
     */
    public function up()
    {
        $this->execute("
            CREATE TABLE users (
                user_id serial NOT NULL,
                created_at timestamp without time zone NOT NULL,
                updated_at timestamp without time zone NOT NULL,
                username text NOT NULL,
                password_hash text NOT NULL,
                full_name text NOT NULL,
                CONSTRAINT users_pkey PRIMARY KEY (user_id)
            ) WITH (OIDS=FALSE)
        ");

        $this->execute("CREATE UNIQUE INDEX users_username_idx ON users (username)");
    }

    /**
     * Migrate Down.
     */
    public function down()
    {
        $this->execute("DROP TABLE IF EXISTS users CASCADE");
    }
}

Then, before your next deployment, manually insert that record into the table you store migrations in (say, _migrations):

code:
INSERT INTO _migrations VALUES(20160405191228, LOCALTIMESTAMP(0), LOCALTIMESTAMP(0), 'CreateUsersTable');
And now, you can do a deployment without worrying about a migration failing, and you can bring up a new database using your migration history. If you prefer not to do the last part of manually inserting the migration record, you could probably do a CREATE TABLE IF NOT EXISTS in the initial migration.

Gozinbulx
Feb 19, 2004
I have zero experience with PHP and m here just to shamelessly ask for a ready-made solution.

I want to setup a small local web server (running Nginx) that I can put some PHP script on so that I can do just the following:

I send a HTTP GET or POST request that includes some kind of identifying name and some kind of message. The server accepts and stores the message and the indentifying name and returns an "OK 200" or something similar.

I send another HTTP GET or POST request asking to retrieve the message, asking for it by name. The server returns the message.


This seems super simple but I'll be damned if I know what to search for that is specific enough to actually get results relevant to that I'm asking.

Anyone know of some super simple solution to implement something like this? Or even just what I should be searching for?

Any help would be appreciated, thanks.

Impotence
Nov 8, 2010
Lipstick Apathy
key value store

revmoo
May 25, 2006

#basta
Memcached with a really light (probably <20 lines of code) PHP wrapper would work. Or you could use a RDBMS if you need persistence.

edit: Looks like there's some stuff on Packagist that can probably do most of this. Setup composer, add index.php, fill in the blanks. Probably could knock it out in an hour or two.

revmoo fucked around with this message at 13:23 on Apr 14, 2016

Gozinbulx
Feb 19, 2004

revmoo posted:

Memcached with a really light (probably <20 lines of code) PHP wrapper would work. Or you could use a RDBMS if you need persistence.

edit: Looks like there's some stuff on Packagist that can probably do most of this. Setup composer, add index.php, fill in the blanks. Probably could knock it out in an hour or two.

Is this something someone with no PHP experience (and very little coding experience in general) can pull off?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Gozinbulx posted:

Is this something someone with no PHP experience (and very little coding experience in general) can pull off?

Not really, and memcached is not a database.

Hash the name and use that as a filename on disk. Store the message in each file. Simple, stupid, easy, no third party dependencies, and file_get_contents()/file_put_contents() have no learning curve.

revmoo
May 25, 2006

#basta

McGlockenshire posted:

Not really, and memcached is not a database.

A database is an organized collection of data.

It's probably not suitable for his needs, though.

quote:

Is this something someone with no PHP experience (and very little coding experience in general) can pull off?

For work? Doubtful. For learning I think it would be a great experience though.

To setup a MySQL db, make a table called 'data' and put two columns in it, and then create a REST endpoint and manage queries to/from it is really not that hard, and it doesn't go very deep on any point of the stack. Hell, you could use HTTP basic auth even.

bigmandan
Sep 11, 2001

lol internet
College Slice

Gozinbulx posted:

I have zero experience with PHP and m here just to shamelessly ask for a ready-made solution.

I want to setup a small local web server (running Nginx) that I can put some PHP script on so that I can do just the following:

I send a HTTP GET or POST request that includes some kind of identifying name and some kind of message. The server accepts and stores the message and the indentifying name and returns an "OK 200" or something similar.

I send another HTTP GET or POST request asking to retrieve the message, asking for it by name. The server returns the message.


This seems super simple but I'll be damned if I know what to search for that is specific enough to actually get results relevant to that I'm asking.

Anyone know of some super simple solution to implement something like this? Or even just what I should be searching for?

Any help would be appreciated, thanks.

Here's a super low :effort: script that does this:

https://gist.github.com/dcabanaw/929c0bbf8c5dea56c41f29cba55bccd3

Runs fine with "php -S 127.0.0.1:8080" ( I don't have access to an nginx server atm)

- make POSTs to the root to add/update
- (key=someKey value=someValue)
- make GET requests with http://127.0.0.1:8080?key=someKey

Like I said this is super low effort. No error checking, etc... Feel free to do whatever you want with it.

poxin
Nov 16, 2003

Why yes... I am full of stars!
So looks like the Laravel creator made a sort of billing scaffolding for projects, looks pretty neat. https://spark.laravel.com/

Would take a lot of writing out of the mix for similar projects.

Gozinbulx
Feb 19, 2004

bigmandan posted:

Here's a super low :effort: script that does this:

https://gist.github.com/dcabanaw/929c0bbf8c5dea56c41f29cba55bccd3

Runs fine with "php -S 127.0.0.1:8080" ( I don't have access to an nginx server atm)

- make POSTs to the root to add/update
- (key=someKey value=someValue)
- make GET requests with http://127.0.0.1:8080?key=someKey

Like I said this is super low effort. No error checking, etc... Feel free to do whatever you want with it.

Thanks I will take a look at this, really appreciate it.

Also really appreciate the other responses, you have set me on a good course. Thank you

Lord Windy
Mar 26, 2010
How should I connect to a database with PHP? I'm learning how to use PHP while building a web game. I'm connecting each time via new mysqli(); The PHP is meant to be a series of APIs that my website uses.

Is this ok way of doing it, or should I be using some kind of global, or singleton?

revmoo
May 25, 2006

#basta

Lord Windy posted:

How should I connect to a database with PHP? I'm learning how to use PHP while building a web game. I'm connecting each time via new mysqli(); The PHP is meant to be a series of APIs that my website uses.

Is this ok way of doing it, or should I be using some kind of global, or singleton?

Global is fine. Use PDO though.

Academician Nomad
Jan 29, 2016
I have a PHP scripted tool running on a test server, and when you run it, it renders everything as it processes it:

[Edited out] (press "Generate" with default values to see what I mean)

But when I put the exact same code on a different server, it waits to go to the new page until it can show everything at once:

[Edited out]

Does anyone know what this (presumably php.ini) setting is called so I can get the second server to act like the first one? I'd prefer users to be able to see what it's doing, so they don't just give up and quit if it takes a while. Unfortunately, I don't have access to php.ini on the test server to compare to the production one, where I do have root access. Normally I would just google it, but I'm having a hard time describing the difference in specific enough language to find anything.

Edit: removing identifable URLs since I got an answer. Thanks

Academician Nomad fucked around with this message at 02:58 on Apr 20, 2016

Adbot
ADBOT LOVES YOU

Impotence
Nov 8, 2010
Lipstick Apathy
^5 cal nerd

try
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);
ini_set('implicit_flush', 1);


at the top of your php file if you don't have ini access

performance slowdowns apply when you do this afaik, and compression breaks because you're sending it chunk by chunk

make sure you also send a header('Content-Type: text/html; charset=utf-8');, and you may need to disable gzip/deflate for that user/page/virtualhost

Impotence fucked around with this message at 02:59 on Apr 20, 2016

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