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
LP0 ON FIRE
Jan 25, 2006

beep boop
If header( 'Location: example.php' ); is placed at the top of a PHP script outside of a function, if statement or any other logic is the rest of the code guaranteed to run properly before it performs the header redirect?

Adbot
ADBOT LOVES YOU

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!

awdio posted:

If header( 'Location: example.php' ); is placed at the top of a PHP script outside of a function, if statement or any other logic is the rest of the code guaranteed to run properly before it performs the header redirect?

I don't know about guarenteed to run properly (that would be nice wouldn't it?) but outputting a header will not disrupt the execution of your script at all.

LP0 ON FIRE
Jan 25, 2006

beep boop

Mashi posted:

I don't know about guarenteed to run properly (that would be nice wouldn't it?) but outputting a header will not disrupt the execution of your script at all.

Okay, good to know. Thanks.

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
Well I suppose there is kind of a border case, where if you have already outputted something that isn't a header, then you'll get an error if you try to use the header() function (but I guess you knew that).

noonches
Dec 5, 2005

It represents my lifestyle and stratus as a street savy irreverent youth, who lives large, and yet hungers for the next level in life.
You can still used ob_start() and ob_end_clean() and output a header at any point.

LP0 ON FIRE
Jan 25, 2006

beep boop

noonches posted:

You can still used ob_start() and ob_end_clean() and output a header at any point.

I'll try this out too. I'm just trying to debug something. For some reason when I when I have the header there SOMETIMES my information that goes to another part of the site doesn't actually go there, and I was just wondering if it was because of something in the header that wasn't giving the site enough time to get the information it needed or something.

Grigori Rasputin
Aug 21, 2000
WE DON'T NEED ROME TELLING US WHAT TO DO
What's the preferred way to reuse header/footer html? I'm talking about opening html/header/doctype/css links/javascript links etc info that would appear in a series of related pages. I came up with three solutions but none seem that great, I was wondering if there was something built in to do this, and if not what the best method is.

1) Have a function that prints string literal information. Kind of tedious to have 'print "<html><header><title></title>..." all over the place, especially in keeping it neat.

2) Have html file stubs stored on the disk to read in and print. Hits the disk, might be a slight security risk.

3) Read from db, print in php file. Seems like a dumb idea.

Enlighten me, please.

EDIT: What's a good O'Reilly book for someone who's been programming awhile but is a little new to webdev? I have access to Safari Online and there's a pile of them... the ones I've looked over so far are pretty newb-friendly, I'm looking for for something that's comprehensive but dumps you into the thick of it.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


If it's static you can just do

php:
<?
readfile('footer.html');
?>
If it's dynamic then just do

php:
<?
include('footer.php');
?>

Grigori Rasputin
Aug 21, 2000
WE DON'T NEED ROME TELLING US WHAT TO DO
Thanks duz, you're like a dream come true through my computer screen!

Atom
Apr 6, 2005

by Y Kant Ozma Post

Grigori Rasputin posted:

2) Have html file stubs stored on the disk to read in and print. Hits the disk, might be a slight security risk.

If this is a serious issue for you, you can use memcache or (harder to write, more optimized) write php that generates php code based on the contents of the db. The risk of somebody rewriting the .html files isn't any more than the risk of someone rewriting the code that includes it in a properly secured system.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Atom posted:

If this is a serious issue for you, you can use memcache or (harder to write, more optimized) write php that generates php code based on the contents of the db. The risk of somebody rewriting the .html files isn't any more than the risk of someone rewriting the code that includes it in a properly secured system.

Or just use readfile which doesn't execute anything.

Atom
Apr 6, 2005

by Y Kant Ozma Post

duz posted:

Or just use readfile which doesn't execute anything.

memcache doesn't execute anything either, and has a lot less overhead than reading from disk.

Zorilla
Mar 23, 2005

GOING APE SPIT
For what you're trying to do, I prefer this. I think I mentioned it before, but I think it's worth mentioning again. It's really useful for templating in conjunction with include() / require(), you can save large chunks of dynamic code into variables like this:

index.php
php:
<?php
define("RUNTEMPLATE"TRUE);

$pagetitle "Boop boop";

ob_start();

?>
<div>
    blablablabla
</div>
<div>
    <?php echo "dynamic blablabla"?>
</div>
<?php

$body ob_get_contents();
ob_end_clean();

include(pagetemplate.php);
?>

And then output them through here:

pagetemplate.php
php:
<?php
defined("RUNTEMPLATE") or die("Direct access to this location is not allowed");
?>
<html>
<head>
<title><?php echo $pagetitle?></title>
</head>
<body>
<?php echo $body?>
</body>
</html>
It is much easier to change elements common to all pages (menus, headers, etc.) once than having an instance of each in every page.

Zorilla fucked around with this message at 01:08 on May 8, 2008

Anveo
Mar 23, 2002

Atom posted:

memcache doesn't execute anything either, and has a lot less overhead than reading from disk.

Unless you're really disk bound, memcached is going to be about 5x slower than reading off local memory, and about 2x slower than reading off the disk.

The big benefit is that it is easily distributed, not that it is faster.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Didn't know where to put this question but since I'm writing in PHP...

Should I stick to using a timestamp like this YYYY-MM-DD or use the Unix timestamp?

Is it okay to use both (eg. one for one system and one for another)?

nbv4
Aug 21, 2002

by Duchess Gummybuns

drcru posted:

Didn't know where to put this question but since I'm writing in PHP...

Should I stick to using a timestamp like this YYYY-MM-DD or use the Unix timestamp?

Is it okay to use both (eg. one for one system and one for another)?

What I do is use YYYY-MM-DD when putting dates into the database, and when i get dates from the database, I immediately convert to unix timestamp for php manipulation.

I've found that entering a unix timestamp into the database directly, via the UNIX_TIMESTAMP() mysql function (or whatever it's called) would sometimes add or a few hours because of timezones, so it would end up incrementing the day. Theres probably a good solution to that problem, but gently caress it, I just use YYYY-MM-DD so I know it's the right date.

BadGopher
Dec 13, 2002

drcru posted:

Didn't know where to put this question but since I'm writing in PHP...

Should I stick to using a timestamp like this YYYY-MM-DD or use the Unix timestamp?

Is it okay to use both (eg. one for one system and one for another)?

If I'm dealing with a date, datetime, or timestamp in a mysql database, I stick with YYYY-MM-DD (or YYYY-MM-DD HH:MM:SS) because it's easy to read and strtotime() can deal with the ugly bits of converting it into seconds-since-epoch as needed. That is, unless I want to log when something happened, in which case I just use now() in the query and be done with it.

BadGopher fucked around with this message at 07:19 on May 8, 2008

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!

Anveo posted:

Unless you're really disk bound, memcached is going to be about 5x slower than reading off local memory, and about 2x slower than reading off the disk.

The big benefit is that it is easily distributed, not that it is faster.

Eh? How is it going to be slower than reading from the disk? Memcached stores information in memory.

Standish
May 21, 2001

Mashi posted:

Eh? How is it going to be slower than reading from the disk? Memcached stores information in memory.
Because in all but pathological situations, small frequently-accessed files like the HTML headers/footers being described will be in the disk cache.

duck monster
Dec 15, 2004

Standish posted:

Because in all but pathological situations, small frequently-accessed files like the HTML headers/footers being described will be in the disk cache.

Trick we worked out in an old job was to store all our HTML in ramdisks (which you script to load in on server boot).

Even better with something like Smarty (or whatever), and keep the cache in ramdisk.

If Xdebug is to be believed, the performance increase was astronomical.

hey mom its 420
May 12, 2007

What's a good PHP library for sending out emails? Just one at a time from a form, so no need for mass mailing.

nbv4
Aug 21, 2002

by Duchess Gummybuns

Bonus posted:

What's a good PHP library for sending out emails? Just one at a time from a form, so no need for mass mailing.

mail()? doesnt get much simpler than that

Zorilla
Mar 23, 2005

GOING APE SPIT

Bonus posted:

What's a good PHP library for sending out emails? Just one at a time from a form, so no need for mass mailing.

PHPMailer is used is just about every content management system out there. Despite a lot of information you'll find on message boards, up-to-date versions support SSL and TLS, so even GMail works with it. There's also Swift Mailer, but its object structure is not nearly as nice and simple as PHPMailer's

Zorilla fucked around with this message at 11:26 on May 8, 2008

hey mom its 420
May 12, 2007

nbv4 posted:

mail()? doesnt get much simpler than that
Yeah, simpler, but I don't really feel like being the victim of a header injection attack or spending several hours getting myself acquainted with and implementing protection against such attacks.

Zorilla: Thanks, I'll try that out!

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


I use PEAR:Mail

Anveo
Mar 23, 2002

Mashi posted:

Eh? How is it going to be slower than reading from the disk? Memcached stores information in memory.

It is stored in memory, but you have the overhead of TCP to access it, plus network latency if the server you are accessing isn't the local one.

Assuming you are reading off a local disk, access is pretty much just doing a file read, plus as a bonus is might also be cached by the OS buffers if it is frequently accessed. (Another option is a ramdisk, which is really fast, but I mention an easier option down a few sentences).

IMHO, the only time you should be using memcached is when you have multiple webservers and want a 'single' distributed cache accessed by all of them.

If you only have one webserver and need more performance and caching, the first thing you should do is install a compiler cache like APC or XCache. Other than the obvious (big)speedup of op-code caching(I've seen req/s increase by over 50%), both of those provide in memory caching systems which will be quite a bit faster than disk reads or memcached.

Anveo fucked around with this message at 15:49 on May 8, 2008

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

So last night I wrote a fairly simple calendar function. It seems to work fine but it looks inefficient. Keeping within the same principles... how would you make it better?

php:
<?
    function getMonth($month, $year)
    {
        $first        = mktime(0, 0, 0, $month, 1, $year);
        $start_day    = date('D', $first);
        $day_offset    = $this->getDayOffset($start_day);
        $days        = cal_days_in_month(0, $month, $year);

        $block = 0;
        $block_limit = 35;

        if($day_offset == 6)
            $block_limit = 42;

        while($day_offset > 0)
        {
            $this->days[$block] = null;
            $day_offset--;
            $block++;
        }

        $day = 1;

        while($day <= $days)
        {
            $timestamp = mktime(0,0,0, $month, $day, $year);
            $this->days[$block]['day'] = $day;
            if(isset($this->events[$timestamp]))
            {
                $this->days[$block]['venue']    = $this->events[$timestamp]['venue'];
                $this->days[$block]['location']    = $this->events[$timestamp]['location'];
            }
            $day++;
            $block++;
        }

        while($block < $block_limit)
        {
            $this->days[$block] = null;
            $block++;
        }
    }?>


The output is being stored in a multidimensional array.

Acer Pilot fucked around with this message at 22:28 on May 8, 2008

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

drcru posted:

So last night I wrote a fairly simple calendar function. It seems to work fine but it looks inefficient. Keeping within the same principles... how would you make it better?

The first thing to do to make this better is to maybe comment it then tell us what it is supposed to do and why.

noonches
Dec 5, 2005

It represents my lifestyle and stratus as a street savy irreverent youth, who lives large, and yet hungers for the next level in life.
So I've got this question, mainly because the people I work with called it sloppy code, and yet my CS teachers from HS and two colleges taught me this.

in this example, it's checking for any blank post values. when one is found, it's supposed to break out of the loop and stop checking values, as it's already found a blank one.
php:
<?
foreach($_POST as $k=>$v)
  {
     if($v=='')
        break;
  }

?>
#1) would the break statement break out of the foreach, or just the IF statement?

#2) is this "sloppy" code? It was taught to me in a basics of comp sci class, and echoed again in a few other classes, so I just assumed it was standard protocol.

other people
Jun 27, 2004
Associate Christ

noonches posted:

So I've got this question, mainly because the people I work with called it sloppy code, and yet my CS teachers from HS and two colleges taught me this.

in this example, it's checking for any blank post values. when one is found, it's supposed to break out of the loop and stop checking values, as it's already found a blank one.
php:
<?
foreach($_POST as $k=>$v)
  {
     if($v=='')
        break;
  }

?>
#1) would the break statement break out of the foreach, or just the IF statement?

#2) is this "sloppy" code? It was taught to me in a basics of comp sci class, and echoed again in a few other classes, so I just assumed it was standard protocol.

You would have to do break 2; to get out of the if statement and then the foreach.

I would use empty() and a do-while loop, but I don't have any formal training at all.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
You cannot "break" out of an if statement. break is for loops and switch statements.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Kaluza-Klein posted:

I would use empty() and a do-while loop, but I don't have any formal training at all.

Don't even have to do that much, array_search() should take care of it with one line.

Edit: They probably call it sloppy because you shouldn't be breaking out of a for loop. If you arn't sure you'll go until the end, you are supposed to use a while or something like that. Is that specific case it doesn't matter that much but other times it shows poor planning.

duz fucked around with this message at 03:38 on May 9, 2008

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Begby posted:

The first thing to do to make this better is to maybe comment it then tell us what it is supposed to do and why.

Sorry about that.

php:
<?
    function getMonth($month, $year)
    {
        $first        = mktime(0, 0, 0, $month, 1, $year); // first date of the month in unix time
        $start_day    = date('D', $first); // starting 'day' eg. mon, tues, wed, etc
        $day_offset    = $this->getDayOffset($start_day); // how many days from sunday does the calendar start
        $days        = cal_days_in_month(0, $month, $year); // how many days in this month?

        $block = 0; // init the block count
        $block_limit = 35; // how many days to include on the calendar with offsets

        if($day_offset == 6)
            $block_limit = 42; // exception the month starts on a saturday

        // add all the empty blocks before the first day
        while($day_offset > 0)
        {
            $this->days[$block] = null;
            $day_offset--;
            $block++;
        }

        $day = 1;

        // add all the days to the calendar
        while($day <= $days)
        {
            $timestamp = mktime(0,0,0, $month, $day, $year);
            $this->days[$block]['day'] = $day; // current day number
            if(isset($this->events[$timestamp])) // there's an event on this day
            {
                $this->days[$block]['venue']    = $this->events[$timestamp]['venue'];
                $this->days[$block]['location']    = $this->events[$timestamp]['location'];
            }
            $day++;
            $block++;
        }

        // add more blocks to make calendar symmetrical.
        while($block < $block_limit)
        {
            $this->days[$block] = null;
            $block++;
        }
    }?>

noonches
Dec 5, 2005

It represents my lifestyle and stratus as a street savy irreverent youth, who lives large, and yet hungers for the next level in life.

duz posted:

Don't even have to do that much, array_search() should take care of it with one line.

Edit: They probably call it sloppy because you shouldn't be breaking out of a for loop. If you arn't sure you'll go until the end, you are supposed to use a while or something like that. Is that specific case it doesn't matter that much but other times it shows poor planning.

Hrmm, I should have thought of array_search. But it's no matter. I ended up going about that a different way. I was just mainly asking out of curiosity, because I have never seen a reason to use it till then, and got more curious when my co-workers called it sloppy code. I know it shows poor planning, but I was just trying to crack out a quick solution for a project that was due before it was even given to me, so I couldn't have been able to plan it any less.

Evil Angry Cat
Nov 20, 2004

The problem I've always found with =="" and empty() checks is that accidentally a user could hit the space bar when filling in a certain field which tricks both checks and means they haven't filled a required field in. So I always use

if (str_replace(" ", "", $_POST['my_test'])=="") { error(); }

when it's something really important.

Zorilla
Mar 23, 2005

GOING APE SPIT

Evil Angry Cat posted:

The problem I've always found with =="" and empty() checks is that accidentally a user could hit the space bar when filling in a certain field which tricks both checks and means they haven't filled a required field in. So I always use

if (str_replace(" ", "", $_POST['my_test'])=="") { error(); }

when it's something really important.

Why not use trim() to remove trailing spaces before checking instead?

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Zorilla posted:

Why not use trim() to remove trailing spaces before checking instead?

Yes, this is a better approach. Trim() also removes whitespace characters like enters and tabs as well.

Dominoes
Sep 20, 2007

I just learned PHP, and set up a simple script to email me submitted form data. I have a small problem that I"m hoping someone can help me with.

Here's the website with form.

Here's the PHP file:
code:
<html>
<body>
<?php

$to = "contact@equilibriumpomade.com";
$subject = "Question/Comment";
$name = $_REQUEST["name"];
$message = $_REQUEST["question"];
$from = $_REQUEST["email"];
$headers = "From: $from";

mail($to,$subject,"Name: $name
Message: $message",$headers);
echo "Message Sent!";
?>
</body>
</html>
The emails are received, but the person using the form is redirected to the php page with the printed text. How do I direct the user to an HTML page instead? I don't want them to go to the php page, I just want to use the script to process the form data.

Zorilla
Mar 23, 2005

GOING APE SPIT

Dominoes posted:

The emails are received, but the person using the form is redirected to the php page with the printed text. How do I direct the user to an HTML page instead? I don't want them to go to the php page, I just want to use the script to process the form data.

Probably something like this:

php:
<?php
isset($_POST["submit"])
    or header("Location:index.html");

$to "contact@equilibriumpomade.com";
$subject "Question/Comment";
$name $_REQUEST["name"];
$message $_REQUEST["question"];
$from $_REQUEST["email"];
$headers "From: " $from;

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">

<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
    <title>Equilibrium Natural Pomade</title>
    <meta http-equiv="refresh" content="3;url=index.html">
</head>

<body>
<?php
if (mail($to,$subject,"Name: " $name "\r\nMessage: " $message,$headers)) {
?>
Email sent successfully
<?php
} else {
?>
Error: the message could not be sent
<?php
}
?>
</body>
</html>

You'll still have to load this page and then it will display a message, then it will go back to wherever you want it to go 3 seconds later. If you want to send the email without ever leaving the page you're coming from, you'll probably need to use AJAX.

Zorilla fucked around with this message at 02:37 on May 11, 2008

Adbot
ADBOT LOVES YOU

noonches
Dec 5, 2005

It represents my lifestyle and stratus as a street savy irreverent youth, who lives large, and yet hungers for the next level in life.

Dominoes posted:

The emails are received, but the person using the form is redirected to the php page with the printed text. How do I direct the user to an HTML page instead? I don't want them to go to the php page, I just want to use the script to process the form data.

At the very top of the page put ob_start() and after the echo put:
php:
<?
ob_end_clean()
header("Location: thank-page.php");
die();
?>

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