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
DarkLotus
Sep 30, 2001

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

huhu posted:

code:
Route::get('/', function () {
	Schema::create('art',function($newtable){
		$newtable -> increments('id'); 
		$newtable -> string('artist');
		$newtable -> string('title',500);#500 is the num of chars for this string
	});
    return view('welcome');
});
I'm watching a tutorial right now and it told me to type all this in, load the main page, and then comment everything inside the Schema out. Is this how tables are typically created?

You using Laravel?
What you want to do to create your schema is use the migrations.
https://laravel.com/docs/5.3/migrations

What you're doing there will work, but it's really only good for learning / testing but I still think learning the right way is the best way.
Check out laracasts.com for some good tutorials if you're just getting started.

Adbot
ADBOT LOVES YOU

spiritual bypass
Feb 19, 2008

Grimey Drawer

McGlockenshire posted:

whatever you're using is architecturally garbage

Welcome to Laravel, the most popular framework

Forgall
Oct 16, 2012

by Azathoth

McGlockenshire posted:

FWIW whatever you're using is architecturally garbage because it's using static methods to do things that really, really, really badly need to be testable. It screams out that there's global state somewhere.
Not really static methods. https://laravel.com/docs/5.3/facades

McGlockenshire
Dec 16, 2005

GOLLOCKS!

No amount of denial will change the fact that those are static methods operating on an implicit (hidden) global state. If you're using Laravel's facades for non-trivial, non-throwaway applications, you are doing yourself a huge disservice.

I'm also a goddamn code snob, so...

revmoo
May 25, 2006

#basta
lmao Laravel is just fine. If you're building flight control systems for SLS boosters then use C or something but if you're building out forgettable web apps that only need to last a few years this is a silly argument to get into.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

revmoo posted:

forgettable web apps that only need to last a few years

Oh you sweet summer child.

Maintenance never ends. PHP is forever. This is our shared hell.

Depressing Box
Jun 27, 2010

Half-price sideshow.
Debates about the usefulness/harmfulness of facades aside, they're ultimately helper classes on top of the dependency injection system, so you can use them as little as you like:

PHP code:
Log::info('test');
PHP code:
$log = App::make(\Illuminate\Log\Writer::class);
$log->info('test');
PHP code:
public function __construct(\Illuminate\Log\Writer $log) {
    $log->info('test');
}
And so on. Or manually instantiating it and its dependencies, if that's your thing.

Depressing Box fucked around with this message at 19:42 on Sep 12, 2016

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

McGlockenshire posted:

Oh you sweet summer child.

Maintenance never ends. PHP is forever. This is our shared hell.

So true. I'm working on a never ending CI 1 project that will barf if we dare to go beyond 4.3(!).

portd
Nov 2, 2015

McGlockenshire posted:

Oh you sweet summer child.

Maintenance never ends. PHP is forever. This is our shared hell.

I wrote a PHP app in 2006 while working for a marketing agency. I left the company for a while, came back many years later, and the client is _still_ using it. I am currently maintaining this old piece of poo poo. Just deployed new fixes today.

Impotence
Nov 8, 2010
Lipstick Apathy
what is CI? codeigniter? i haven't heard of that existing in years

spiritual bypass
Feb 19, 2008

Grimey Drawer
It does exist and it sucks and for some reason version 4 is about to be released

huhu
Feb 24, 2006
Official Laravel documentation:

quote:

The provider key in your ~/.homestead/Homestead.yaml file indicates which Vagrant provider should be used....
I browse to the folder, Homestead.yaml isn't there. Random forum in my search turns up

quote:

the Homestead.yaml file is locate in ~/.homestead/src/stubs/ folder

WHY? I feel like I didn't have this much trouble learning front end technologies.

Depressing Box
Jun 27, 2010

Half-price sideshow.
Per the previous section in the documentation (under "Installing Homestead"), you need to run bash init.sh in the ~/Homestead/ directory to generate your config files. The stubs/ files you found are the base templates init.sh copies when it creates your ~/.homestead/ directory.

And you're not alone, web development tooling is almost always a pain to set up the first time. After you've trial-and-errored your way through a few different systems you'll start to get a feel for it, but overall it's a study in ideas outpacing documentation.

Depressing Box fucked around with this message at 03:37 on Sep 15, 2016

spiritual bypass
Feb 19, 2008

Grimey Drawer
more like ChoadIgniter

substitute
Aug 30, 2003

you for my mum
I build webshites

LP0 ON FIRE
Jan 25, 2006

beep boop
I'm trying to attach a pdf from a URL. All it sends is an empty file. I verified that the filename and path are valid. I've tried a few variations, including using curl, and I have the feeling that maybe is something is going wrong in how the headers or body is written?

code:

	    $attachmentPath = "http://www.example.com/myFolder/filename.pdf";
	    $filename = "filename.pdf";

            $file = $attachmentPath; 
            $contents = file_get_contents($file); 
            touch($filename); 
            file_put_contents($filename, $contents);

            $content = chunk_split(base64_encode(file_get_contents($filename)));

            $separator = md5(time());
            $eol = "\r\n";
            $headers = 'From:'.$_SESSION['user'].$eol;
            $headers .= "MIME-Version: 1.0" . $eol;
            $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
            $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
            $headers .= "This is a MIME encoded message." . $eol;


            // message
            $body = "--" . $separator . $eol;
            $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
            $body .= "Content-Transfer-Encoding: 8bit" . $eol;
            $body .= $message . $eol;

            // attachment
            $body .= "--" . $separator . $eol;
            $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
            $body .= "Content-Transfer-Encoding: base64" . $eol;
            $body .= "Content-Disposition: attachment" . $eol;
            $body .= $content . $eol;
            $body .= "--" . $separator . "--";

            mail($usersEmailDec, $subject, $body, $headers);   

revmoo
May 25, 2006

#basta
That's some really complicated PHP. I haven't tried this exact method:

http://stackoverflow.com/questions/2882472/php-send-file-to-user

But it looks right based on my memory. (The method a couple posts down with 5 upvotes)

LP0 ON FIRE
Jan 25, 2006

beep boop

revmoo posted:

That's some really complicated PHP. I haven't tried this exact method:

http://stackoverflow.com/questions/2882472/php-send-file-to-user

But it looks right based on my memory. (The method a couple posts down with 5 upvotes)

Thanks for that method. I replaced the filename variable with $attachmentPath. Then set $content. I'm keeping the body part the same as I did above. No dice. Same thing; blank file.

code:
if(file_exists($attachmentPath)){

                //Get file type and set it as Content Type
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                header('Content-Type: ' . finfo_file($finfo, $attachmentPath));
                finfo_close($finfo);

                //Use Content-Disposition: attachment to specify the filename
                header('Content-Disposition: attachment; filename='.basename($attachmentPath));

                //No cache
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');

                //Define file size
                header('Content-Length: ' . filesize($attachmentPath));

                ob_clean();
                flush();
                readfile($attachmentPath);
                exit;
            }

            $content = chunk_split(base64_encode(file_get_contents($attachmentPath)));

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Check the network sniffer in your browser's debug tool. Make sure that each of the headers, including that Content-Length, are showing up exactly as you set them. Keep in mind that if you're using sessions, those cache control headers are likely going to get overwritten and you'll probably need to use session_cache_limiter() and session_cache_expire() to get that job done.

Also, for debugging, what happens when you manually set the content type to text/plain and the disposition to inline, remove the content length, and just emit a string? That is, have you verified that the code works correctly without trying to send the attachment? Nothing really looks wrong... (I mean, that thing with $content at the end is bogus, but you've exited, so...)

LP0 ON FIRE
Jan 25, 2006

beep boop

McGlockenshire posted:

Check the network sniffer in your browser's debug tool. Make sure that each of the headers, including that Content-Length, are showing up exactly as you set them. Keep in mind that if you're using sessions, those cache control headers are likely going to get overwritten and you'll probably need to use session_cache_limiter() and session_cache_expire() to get that job done.

Also, for debugging, what happens when you manually set the content type to text/plain and the disposition to inline, remove the content length, and just emit a string? That is, have you verified that the code works correctly without trying to send the attachment? Nothing really looks wrong... (I mean, that thing with $content at the end is bogus, but you've exited, so...)

Thanks for the tip on checking the headers. The Content-Length is 0, so it looks like it failed to get the filesize in the first place.

Name Value
Server Apache
Content-Type text/html
Date Wed, 30 Nov 2016 19:53:55 GMT
Connection Keep-Alive
Content-Length 0
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=2, max=99
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma no-cache

You mentioned the session. I'm just using that to get the logged in user's email address for the From field. The message sends fine, minus the attachment. Could this still affect the attachment?

I omitted what you mentioned, and it sends as exactly as before: an attachment with a file name with no size. Looks like something was missed for what I was supposed to remove if it's still sending an attachment.

Also I'm confused what you mentioned about $content at the end. I could have sworn that is actually the file as data, while Content-Type: application/octet-stream; name= is just setting the name.

LP0 ON FIRE fucked around with this message at 21:23 on Nov 30, 2016

nielsm
Jun 1, 2009



LP0 ON FIRE posted:

I'm trying to attach a pdf from a URL. All it sends is an empty file. I verified that the filename and path are valid. I've tried a few variations, including using curl, and I have the feeling that maybe is something is going wrong in how the headers or body is written?

Does the file you're sending really only exist on a remote server? I.e. what you do is download the file for the user and send it by mail? (If the file you want to send exists on your own server, you shouldn't be passing a HTTP URL to file_get_contents(), but just the filename.)

Does the file download if you fetch that URL using your browser? Using a commandline tool (like wget or curl)?

Why does your (original) code write the downloaded data to a new file, only to immediately read it back? Do you know if that writing the file works or fails?

revmoo
May 25, 2006

#basta

McGlockenshire posted:

Check the network sniffer in your browser's debug tool. Make sure that each of the headers, including that Content-Length, are showing up exactly as you set them. Keep in mind that if you're using sessions, those cache control headers are likely going to get overwritten and you'll probably need to use session_cache_limiter() and session_cache_expire() to get that job done.

Also, for debugging, what happens when you manually set the content type to text/plain and the disposition to inline, remove the content length, and just emit a string? That is, have you verified that the code works correctly without trying to send the attachment? Nothing really looks wrong... (I mean, that thing with $content at the end is bogus, but you've exited, so...)

What this guy said.

Also just take the S/O post and make IT work and then work backward into getting your application to do what you want.

LP0 ON FIRE
Jan 25, 2006

beep boop
I just found out the header is giving me a problem with the body of the message where a lot of it is cut off in the email that is sent.. Need to resolve this and investigate the other stuff too.

Update - Thank you everyone for your help. This was so frustrating, and I continued to have issues. I decided to get PHPMailer. Took me 5 minutes to get everything working after that.

LP0 ON FIRE fucked around with this message at 23:21 on Nov 30, 2016

McGlockenshire
Dec 16, 2005

GOLLOCKS!

LP0 ON FIRE posted:

Update - Thank you everyone for your help. This was so frustrating, and I continued to have issues. I decided to get PHPMailer. Took me 5 minutes to get everything working after that.

Hah, I misread your original post and thought you were doing a force download over HTTP.

Yes, always go for SwiftMailer or PHPMailer for anything even remotely complicated with email. The instant you start putting together MIME headers yourself, it's just not worth it any longer.

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:

Welcome to Laravel, the most popular framework

Can you post your stupid home grown framework already or just shut up?

spiritual bypass
Feb 19, 2008

Grimey Drawer
I probably shouldn't respond to someone feigning anger months after a snarky comment, but here goes anyway!

This is the index.php for an alternative approach. I might package it for the public if it proves to be viable, although there's really not much to it. Add more dependencies to Auryn and your action constructors as necessary.

php:
<?php

require_once __DIR__ '/../vendor/autoload.php';

use \ExampleDotCom\Action;

$request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
$emitter = new \Zend\Diactoros\Response\SapiEmitter();
$injector = new Auryn\Injector;
$db = new PDO($dsn);
$authFactory = new \Aura\Auth\AuthFactory($_COOKIE);

$deps = [
    ':db' => $db,
    ':request' => $request
];

$dispatcher FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET''/'Action\Index\Get::class);
});

list($disposition$handlerType$vars) = $dispatcher->dispatch($request->getMethod(), $request->getRequestTarget());

foreach ($vars as $name => $value) {
    $deps[":{$name}"] = $value;
}

switch ($disposition) {
    case FastRoute\Dispatcher::NOT_FOUND:
        echo '404';
        break;
    case FastRoute\Dispatcher::FOUND:
        $handler $injector->make($handlerType$deps);
        $emitter->emit($handler->execute());
        break;
}

Actions just return a response:
php:
<?php

namespace ExampleDotCom\Action\Index;

use Psr\Http\Message\ResponseInterface;
use ExampleDotCom\Action\ActionInterface;
use ExampleDotCom\Layout\PublicHomepage;
use Zend\Diactoros\Response;

final class Get implements ActionInterface
{
    public function __construct()
    {
    }

    public function execute(): ResponseInterface
    {
        return new Response\HtmlResponse((new PublicHomepage())->render());
    }
}

McGlockenshire
Dec 16, 2005

GOLLOCKS!

rt4 posted:

This is the index.php for an alternative approach. I might package it for the public if it proves to be viable, although there's really not much to it. Add more dependencies to Auryn and your action constructors as necessary.

This is a good approach and closely mirrors what I do in my personal projects. Anyone wanting to do the same should review the No Framework Tutorial first.

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:

I probably shouldn't respond to someone feigning anger months after a snarky comment, but here goes anyway!

This is the index.php for an alternative approach. I might package it for the public if it proves to be viable, although there's really not much to it. Add more dependencies to Auryn and your action constructors as necessary.

php:
<?php

require_once __DIR__ '/../vendor/autoload.php';

use \ExampleDotCom\Action;

$request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
$emitter = new \Zend\Diactoros\Response\SapiEmitter();
$injector = new Auryn\Injector;
$db = new PDO($dsn);
$authFactory = new \Aura\Auth\AuthFactory($_COOKIE);

$deps = [
    ':db' => $db,
    ':request' => $request
];

$dispatcher FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET''/'Action\Index\Get::class);
});

list($disposition$handlerType$vars) = $dispatcher->dispatch($request->getMethod(), $request->getRequestTarget());

foreach ($vars as $name => $value) {
    $deps[":{$name}"] = $value;
}

switch ($disposition) {
    case FastRoute\Dispatcher::NOT_FOUND:
        echo '404';
        break;
    case FastRoute\Dispatcher::FOUND:
        $handler $injector->make($handlerType$deps);
        $emitter->emit($handler->execute());
        break;
}

Actions just return a response:
php:
<?php

namespace ExampleDotCom\Action\Index;

use Psr\Http\Message\ResponseInterface;
use ExampleDotCom\Action\ActionInterface;
use ExampleDotCom\Layout\PublicHomepage;
use Zend\Diactoros\Response;

final class Get implements ActionInterface
{
    public function __construct()
    {
    }

    public function execute(): ResponseInterface
    {
        return new Response\HtmlResponse((new PublicHomepage())->render());
    }
}


I wasn't feigning "anger" I just got sick of you banging on about how frameworks suck etc etc, figured it was time you showed what you're doing that is so much better.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
A hopefully simple PHP question I can't figure out. I have a site for the cat adoption center I volunteer at, and I have a field in the database where I put the cat's approximate age. But I want the cat's age to update automatically, because sometimes a cat will be there for a few months (or in rare cases, years) and I don't want a cat to be listed as being four months old forever.

So I made a field where I can enter the cat's approximate date of birth in dd/mm/yyyy format. I want to use PHP to calculate the age and display it as "Age: (YEARS) years, (MONTHS) months". I found a few things on Stack Overflow, but they don't seem to work and with my limited PHP knowledge I'd have to spend hours figuring it out. Any help would be appreciated.

Depressing Box
Jun 27, 2010

Half-price sideshow.
Try the DateTime class:

PHP code:
$now = new DateTime();
$birth = new DateTime('08/05/2014');
$age = $now->diff($birth);

echo "Age: $age->y years, $age->m months";
// Age: 2 years, 4 months

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

Depressing Box posted:

Try the DateTime class:

PHP code:
$now = new DateTime();
$birth = new DateTime('08/05/2014');
$age = $now->diff($birth);

echo "Age: $age->y years, $age->m months";
// Age: 2 years, 4 months

I feel like I'm so close here:

PHP code:
$customfielddob = get_field('approximate_date_of_birth'); //This outputs as, for example, 06/01/2016
$now = new DateTime();
$birth = strtotime($customfielddob); //Not sure about this line
$age = $now->diff($birth);
echo "Age: $age->y years, $age->m months";
That line that starts with $birth is the one that's probably the reason it's not working. I think it's just not converting it properly to a date that the "diff" function can compare it to.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Watch out when using DateIntervals, outside of DateTime::diff(). Unless they're created with a complete DateTime on both ends, they don't properly populate the y/m/d/h/i/s properties.

quote:

That line that starts with $birth is the one that's probably the reason it's not working. I think it's just not converting it properly to a date that the "diff" function can compare it to.
Pass the date string directly to the DateTime constructor, as in the example above. It uses strtotime() under the hood. You need to pass DateTime::diff() another DateTime to compare against, not just a unix timestamp string.

Also, if you have the option or ability, try to pass it only entirely unambiguous date formats, like YYYY-MM-DD. strtotime() is usually pretty good at figuring out our weird MM/DD/YYYY stuff, but...

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
Ohhh. Got it! Thanks. I love figuring out PHP, it's often a puzzle where I know where to start and what the end result should be, but there's often just one line of code in the middle like figuring out how to define a variable that gets me stuck.

awesomeolion
Nov 5, 2007

"Hi, I'm awesomeolion."

Any idea why my time is off here by 46 minutes?

code:
date_default_timezone_set('America/Los_Angeles');
$date= date('Y-m-d H:m:s');
echo "<h1>Current time: " . $date . "</h1>";

McGlockenshire
Dec 16, 2005

GOLLOCKS!

awesomeolion posted:

Any idea why my time is off here by 46 minutes?

code:
date_default_timezone_set('America/Los_Angeles');
$date= date('Y-m-d H:m:s');
echo "<h1>Current time: " . $date . "</h1>";


Because the time on the server is off by 46 minutes. Bug your host. If you are the host, check to see what went wrong with NTP.

Pile Of Garbage
May 28, 2007



Return value is entirely dependent on the host, make sure your server is configured to sync time via NTP against a good server (See: http://www.pool.ntp.org/).

E:f;b!

nielsm
Jun 1, 2009



awesomeolion posted:

Any idea why my time is off here by 46 minutes?

code:
date_default_timezone_set('America/Los_Angeles');
$date= date('Y-m-d H:m:s');
echo "<h1>Current time: " . $date . "</h1>";


You want "i" for minutes, "m" means month.

awesomeolion
Nov 5, 2007

"Hi, I'm awesomeolion."

Thanks y'all! Going to get the primary user of the *brace yourself* GoDaddy account to configure NTP Synchronization and I should be set. Much appreciated :)

YO MAMA HEAD
Sep 11, 2007

nielsm posted:

You want "i" for minutes, "m" means month.

it's this one!!

Adbot
ADBOT LOVES YOU

Ghostlight
Sep 25, 2009

maybe for one second you can pause; try to step into another person's perspective, and understand that a watermelon is cursing me



It's a December past 8.

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