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
spacebard
Jan 1, 2007

Football~

Yay posted:

php:
<?
if (property_exists('body', $node) && is_array($node->body)) {
    $body = $node->body['und'][0];
}?>
should do it. Node is a simple object (StdClass), but body, field_url and their children are standard arrays.

You're going to run into a cross-site scripting vulnerability if you do this exactly like that. At least run the value of body through check_markup().

However that would ignore any other module's hard work in case you have tacked on functionality that extends core Drupal 7 fields. In Drupal 6, we had to do it like that.

The $content variable built as a part of template_preprocess_node is now an Array in Drupal 7 ready to be plugged into render(). You can extract the fields from $content instead of the $node object. It will look kind of like the example in field_attach_view.

php:
<?
  print render($content['body']);
  print render($content['field_url']);
?>
And then $content['body'] ALSO has a copy of the node object in it :psyduck:

They did all this just for theme developers :v:

Adbot
ADBOT LOVES YOU

spacebard
Jan 1, 2007

Football~

Golbez posted:

Looks like it. Thanks. Just shows how hosed up that particular part of mysqli is. I think I'm going to run with PDO for now, I'm seeing no drawbacks compared to mysqli (the performance difference appears at most trivial)...

One thing that the MySQL PDO driver does not currently support is SSL. It has been added to the PHP 5.3 branch so it's only a matter of time until the next official release. This only matters if you don't run on dedicated hardware or are connecting over an open network.

spacebard
Jan 1, 2007

Football~

duck monster posted:

Well I'm liking Symfony2 so far, but gently caress me does doctrine have the whiff of over-engineering to it.

I'm tempted to put it in the "optional" category and drag in an ORM that isn't written by insane java victims.

I thought that's what Symfony2 was all about. :v:


Seriously though isn't it influenced by Spring?

spacebard
Jan 1, 2007

Football~

stoops posted:

I'm working on wordpress, but I think this may be php related.

On the code below, I'm getting a Call to undefined function on line 3, "getItems($items)".
I googled and I found that I should be calling it like this "$this->getItems($items);", but that still gives me the same error. Any help is appreciated.

No, you do not use $this.

http://www.php.net/manual/en/language.oop5.basic.php posted:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

The code works fine when run via PHP so perhaps Wordpress is doing something weird with including that code?

spacebard
Jan 1, 2007

Football~

silentpenguins posted:

Hey, didn't see a drupal thread so posting this here. Does it make a big difference to call variable_get multiple times on the same variable that's not going to change in the same code, or is it better to define a global? Not sure if drupal has some sort of caching so it wouldn't matter. Version is drupal 7 by the way.

Variables are cached so there's no database performance hit.

spacebard
Jan 1, 2007

Football~

Sulla-Marius 88 posted:

It's in an AD environment using IE to grab the user's domain login details. Running PHP on Apache on Windows Server 2008. I've been told http headers but getallheaders() doesn't output what I'm looking for. Should I be looking somewhere else or does the fault lie with group policy settings that aren't broadcasting the login name through http headers to trusted sites (i.e. mine)?

Is the header in the http request at all? You may be able to view the raw request in IE developer tool these days. It's possible with Firefox, Chrome, etc...

If there is supposed to be a http header set, then I'd verify it's absinthe sent. Maybe apache access log can reveal it if configured? Man, I hate debugging in IE...

spacebard
Jan 1, 2007

Football~

musclecoder posted:

This is called a database migration and there are libraries available for every major framework and stand-alone application. Find one you like and start using it. If you had a proper deployment process in place (like using Capistrano and Phing) adding the database migrations would be simple and automated.

I agree.

However I'm always nervous about automating major updates. I like to babysit: run the migration/update script, inspect the data at the end, and then be ready to rollback or not. I do this on staging, but I still get nervous about everything regarding production deployments so I feel as if I have to do that there too. Better unit and functional tests in development have reduced this fear over time, but it's still there.

There are also times when data is too large or sensitive to create functional/integration tests (on a limited infrastructure). And for that it's great to make staging specifically as a deployment test.

If a company has the resources, then it's best to throw away the concept of three environments. If I need to test or develop or stage, spin up a box via Vagrant and Puppet, back port the database, install, go, and do my worrying there. Then spin down the site later. Not everyone has those resources though.

spacebard
Jan 1, 2007

Football~

Gnack posted:

This is fine logically, it's easy enough to write this stuff but how would you guys go about testing it? For example, maybe I want to make sure notification emails are sent out at the correct time, or that games are locked down from tipping once they've begun - how would I test this? I could manually change the date/time of my dev environment but that's a lot of stuffing around.

Hopefully your classes are loosely-coupled enough so that you could create a unit test based off of PHPUnit_Frameworke_TestCase. Then you should have high confidence that if you assert that your isLocked method or whatever returns true or false.

spacebard
Jan 1, 2007

Football~

Gnack posted:

Ah okay, thank you. I did wonder if that's what he was getting at. I was hoping to avoid that but it makes sense so I think I'll go for that approach. Thanks both of you.

Sorry, I was suggesting that functional programming makes things easier to test. :goonsay:

isLocked() probably does't make sense to take any parameters, but return a boolean based off some property on the object. Having a getter/setter for date would help.

Basically,

php:
<?
// Create a date that's in the future.
$date = new Date(time() + 3660);

$mock = new MyMatchClass();
$mock->setMatchTime($date);

$this->assertTrue($mock->isLocked());

// Subtract enough time to be in the past, and set matchtime
$date->sub(DateInterval::createFromDateString('4000 seconds'));
$mock->setMatchTime($date);

$this->assertFalse($mock->isLocked());
?>

spacebard
Jan 1, 2007

Football~

Wheany posted:


Well, now I'm going to have to interface with a web service that both inputs and outputs XML. So I need something to generate valid XML for making requests and I need to parse the response to get the data I requested.

Looking at SimpleXML, that looks painless enough for generating simple requests. I might be able to live with that.
But processing incoming XML with, say DOM, sounds potentially lovely. I can probably live with that as well if need be, but if there are better options, I'd like to hear about them at least.

late edit: Looks like I misunderstood SimpleXML's purpose. I thought it was meant for encoding data into XML, but looks like it also parses XML. Well, I'm going to try that for now and see if I run into some massive problems.

Guzzle can output SimpleXML and probably you could extend guzzle to use DOM. If you need to validate with a schema than I think DOMDocument works better.

spacebard
Jan 1, 2007

Football~
Edit: awful app pasting

silentpenguins posted:

If I have class files used by several scripts, is it more efficient to have one set of the class files, or have a directory with copies of the class files for every script? Disk space is of no issue, and there's no difference across the class files whatsover. Just wondering, obviously if there are edits to be made to the class files it would be smarter, however in my year plus tenure at this position we've never had to change them.

Any insight is appreciated, thanks.

If these scripts are all a part of the same application with a shared runtime/bootstrap, then your class files should be a part of an auto loader like Composer. In other words, yes, the class files should be shared for easier testing and deployment.

spacebard
Jan 1, 2007

Football~

Experto Crede posted:

When trying to use curl_setopt to get verbose info from a curl_exec, PHP will send the output to stderr, which is fine when you're using cli, but a problem when running it in a web environment.

I know you can just set the error_log using php.ini/ini_set which will save that output to a file, but ideally I'd like the stderr output to be usable someway (ie to save it to a variable, for example) when using code that runs in a browser.

Can this be done easily, or at all?

Can you not get what you need with curl_error() and curl_errno()?

If you use Guzzle, you can catch exceptions fairly easily.

spacebard
Jan 1, 2007

Football~

Raskolnikov2089 posted:

I decided this is the weekend to start learning PHP and am having some trouble with XAMPP installation for windows.

Do I need to install Tomcat if I just want this for PHP/MySQL development? I tried installing it once and ran into problems where it was conflicting with already installed Java, and I'd really just as soon not bother.

No, you don't need Tomcat.


Though if you're going to be eventually working with a Linux environment, you might as well use PuPHPet to generate a vagrant and puppet manifest. It's really easy. If you're a bit more involved, using vagrant with rsync is preferable to NFS on Windows in VirtualBox.

spacebard
Jan 1, 2007

Football~

Experto Crede posted:

At work, I run a unix command using watch to view the queue on our PBX, ideally I'd like to find a way to show this in a browser also in real time.

Is there a way in PHP to basically to view the live output of a command through shell_exec?

Allowing shell execution is not really best practice, but it's possible. Writing the output to a file accessible to the web server would be better. Then have a HTML page that picks up the file with some javascript and updates it. Could be a quick little React/Ember/Angular thing (the latter two if you wanted to over engineer it).

spacebard
Jan 1, 2007

Football~

Depressing Box posted:

To avoid loading everything into memory you'll want to use streams instead of read/put. Check the docs for your filesystem library of choice and look for code using fopen/fclose.

I don't know about streaming directly from a browser to S3, though. At that point maybe you want to look into multipart file upload.

It looks like the Laravel library uses aws/aws-sdk-php. The steam wrapper used file_get_contents but the docs at https://github.com/aws/aws-sdk-php/blob/master/docs/service-s3.rst recommend to use multipart file upload for large files. Not sure if the Laravel library supports that though.

spacebard
Jan 1, 2007

Football~

musclecoder posted:

Not if the payload is part of the URL, which in a GET request, it is. I know the headers and POST parameters are encrypted, but obviously the GET parameters aren't (GET requests can't have a payload body either).

e;fb on this during preview, but ...
No, the entire HTTP request is encrypted per the spec. The client initiates SSL connection first, and then sends the HTTP request. The server, of course, will have the decrypted request and will probably log the URI any query parameters.

And the HTTP specification does not explicitly prohibit GET request from sending a body, but it is not specifically supported either. It's just understand that applications should behave as good citizens and respect GET semantics.

spacebard
Jan 1, 2007

Football~

COOL CORN posted:

Good point. It'll be a small project, with just a handful of pages, basic authentication, and probably a MySQL backend for some basic data. Laravel has good documentation on getting a Vagrant box up and running, but so far Vagrant seems very "black box"ish to me. I don't know how it does stuff, it just does. If it's easy enough to build a Vagrant box for Silex or something like that, I might go that route.

Thanks for the pointers!

You can also try out PuPHPet which is a web site to configure a Vagrant VM specifically for PHP applications.

spacebard
Jan 1, 2007

Football~

revmoo posted:

In general.

I'm waiting for someone to come along and tell me why I'm wrong. Are there any good use cases for switch()?

I don't think its necessarily good or bad, but I liked a recursive function I wrote that traversed a DomDocument object. The switch statement was easier than a large number of if/elseif. The switch had case statements equal to an element name.

I think the better approach might have been implementing a sub class of DomDocument and other classes with custom methods for iterations. That could have broken the complexity down.

Either way complexity was going to be high because it was a complex XML file from an external system that needed to be transformed into HTML.

spacebard
Jan 1, 2007

Football~
Sort of related, but what are opinions about using PHP's assert function and having it run on development environments?

It seems like a lot of effort, but I can see the benefit of relying on that instead of doing the strict type comparison, which decreases readability. On the other hand, all the assert function examples I've seen look pretty crazy in terms of readability too.

spacebard
Jan 1, 2007

Football~
Laravel what the hell :stare:

Php is fast when you write it in C :v:

spacebard
Jan 1, 2007

Football~

hayden. posted:

Don't you have to worry about being PCI compliant the second you touch card info?

Yep. Pretty clearly D since January of this year. Even without passing cardholder data through a form submit a site's still A:EP.

spacebard
Jan 1, 2007

Football~

v1nce posted:

Hello, thread. I'm looking for a couple of opinions.

In the Symfony2 project I'm looking after, we have the following repository access pattern:
php:
<?
class MyController
{
    public function myAction(Request $request)
    {
        $id = (int) $request->get('id', null);
        $someStuff = $this->getDoctrine()->getRepository('MyBundle:SomeEntity')->findSomeStuff($id, true);
    }
}
?>
There's been a suggestion to change it to something like this:
php:
<?
class MyController
{
    public function myAction(Request $request)
    {
        $id = (int) $request->get('id', null);

        $someService = $this->get('service.some_service');
        $someStuff = $someService->findSomeStuff($id, true);
    }
}

class SomeService
{
    protected $someEntityRepository;

    // Omitted: constructor

    public function findSomeStuff($id, $includeDeleted)
    {
        $query = $this->someEntityRepository->findSomeStuff($id, $includeDeleted);
        return $query->getResult();
    }
}
?>
These two approaches obviously lead to exactly the same result.

Is there any major benefit to moving the Repository access behind a service rather than accessing the repo directly in the controller?
Is it a good idea to put the repository in the service?

I guess whichever is easier to mock the Repository service for testing MyController, which is probably the second option even though that depends on mocking the service container too, right?

It would probably be "better" to inject the Repository service into myAction by making MyController a service too. I asked several people about whether there would be a big performance impact, and even with a ton of routes, there wouldn't be any.

spacebard
Jan 1, 2007

Football~

revmoo posted:

I'm parsing the output of an API that, depending on the object you're querying, either may or may not have extremely recursive output, IE nested arrays and objects that can be up to 10 levels deep.

Is there a smarter way of transforming this data than doing a poo poo ton of ugly isset() crap everywhere? I'm looking to have probably 300 lines of isset() and nested loops just to check if data exists or not and it's getting extremely unwieldy. I feel like I'm going about this the wrong way.

Seems like one of those times a recursive function may come in handy. Like I needed to parse an arbitrary nested list elements in a HTML partial file the other day. So I wrote a recursive function to look thru the DOMDocument via xpath queries.

spacebard
Jan 1, 2007

Football~

Sab669 posted:

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" :(

I thought that Netbeans would do this, but I guess it doesn't out of the box. phpcs (with PSR2 standards set) doesn't catch it either... PHPStorm does have a setting for it though.

spacebard
Jan 1, 2007

Football~

Acidian posted:

This does not work:

code:

$files = scandir($dir);
$image_archive = 'images.zip';

$zip = new ZipArchive();
$zip->open($image_archive, ZipArchive::CREATE);

            foreach ($files as $file){
                if($file == '..' || $file == '.'){
                    continue;
                }

                $file_loc = $dir . $file;
                $zip->addFile($file_loc, $file);
                }
$zip->close();

What am I doing wrong?

This worked for me pretty much as-is (PHP 7.1). I plopped it into some php file, made sure $dir and $image_archive had __DIR__ concatenated, ran it, and I got a zip file with my files.

Do you have any memory or file system restrictions? Or maybe the calling code is timing out or closing the file handle? Honestly no clue other than that why it wouldn't work since you've pretty much guaranteed the files exist.

Adbot
ADBOT LOVES YOU

spacebard
Jan 1, 2007

Football~

Agrikk posted:

How do I delete multiple spaces in a row but leave a single whitespace in a string?

The function trim will remove leading and trailing white space characters from a string. Similar to other programming languages.

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