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
McGlockenshire
Dec 16, 2005

GOLLOCKS!

Lamb-Blaster 4000 posted:

how do I get mail() to work with my google apps domain mail?

I've tried sending through smtpout.gmail.com with proper credentials and ssl, it doesnt error out, but it also doesnt seem to be sending either

Try with a third-party library like Swiftmailer, which can actually provide intelligent and useful feedback when things go wrong, unlike mail().

Adbot
ADBOT LOVES YOU

FateFree
Nov 14, 2003

I'm trying to decode something in Java that was encrypted with php, but I don't know any php really. Can someone help me translate this php encryption function?

code:
$aes = new Crypt_AES();
$encKey = '1234567812345678';
$aes->setKey($encKey);
$temp_Path = trim(base64_encode($aes->encrypt(str_pad($temp_Path, 16, chr(0xC)))));
return $temp_Path;
As far as I can understand, they are using an AES cipher with a key, then they are padding the string with something, encrypting and base64 encoding and then trimming. What exactly is going on with the padding and the trim?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
They're using some third-party code, so it may be wonky.

The padding ensures that the string is at least sixteen characters in length. The character in question is 0x0c, ASCII 14, form feed. If the string is longer than 16 characters, nothing is changed.

Trim removes whitespace at the beginning and end, which is pretty silly considering that base64_encode doesn't attach newlines.

So, you should be able to decrypt it by reversing the base64, unencrypting, and trimming off any 0x0c characters on the end.

Beware that certain AES implementations may or may not pad the key with null bits to a certain length. If you're having problems with the decrypt, that's probably at fault.

MrMoo
Sep 14, 2000

McGlockenshire posted:

Try with a third-party library like Swiftmailer, which can actually provide intelligent and useful feedback when things go wrong, unlike mail().

mail() is fine but you really need your own mail spool to avoid the time sending anything to Google. Postfix is easy to setup for this.

Lamb-Blaster 4000
Sep 20, 2007

McGlockenshire posted:

Try with a third-party library like Swiftmailer, which can actually provide intelligent and useful feedback when things go wrong, unlike mail().

Thanks! Swiftmail worked beautifully, here's my code if anyone else comes lookin for this answer

code:
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com',465);
$transport->setUsername('existingemail@myappsdomain.tld');
$transport->setPassword('mypassword');

$mailer = Swift_Mailer::newInstance($transport);

$msg = Swift_Message::newInstance('subject');
$msg->setFrom(array('existingemail@myappsdomain.tld' => 'My Name'));
$msg->setTo(array('some@email.com'));
$msg->setBody('body of email');

$result = $mailer->send($msg);

JasonV
Dec 8, 2003
I've got a function I need to write to solve a problem and was wondering if anyone might be able to think of a decent solution.

All it needs to do is calculate the number of minutes between two DateTimes. The catch is: anything between 11pm and 7am doesn't count.

I figure I could just loop over the minutes between $startTime and $endTime and add a minute to a $totalTime if it's not between 11pm-7am, but doesn't seem like the best solution, especially if there's a few weeks between the two dates.

I was curious if anyone can come up with something a bit more elegant?

gwar3k1
Jan 10, 2005

Someday soon

JasonV posted:

I've got a function I need to write to solve a problem and was wondering if anyone might be able to think of a decent solution.

All it needs to do is calculate the number of minutes between two DateTimes. The catch is: anything between 11pm and 7am doesn't count.

I figure I could just loop over the minutes between $startTime and $endTime and add a minute to a $totalTime if it's not between 11pm-7am, but doesn't seem like the best solution, especially if there's a few weeks between the two dates.

I was curious if anyone can come up with something a bit more elegant?

Figure out how many days are between start and end. For the first day it's 16 hours (7-11) minus the start time, for the last day use a similar equation, then for each day inbetween, add 16 hours.

gwar3k1 fucked around with this message at 20:05 on Nov 30, 2010

Baggy_Brad
Jun 9, 2003

THUNDERDOME LOSER
I'm curious, is there an official (or unofficial) standard for comparing strings?

If I'm not worried about ordering or case, am I better checking

php:
<?
if ($x === $y){ echo $x,' equals ', $y; }?>
OR

php:
<?
if (strcmp($x,$y) === 0){ echo $x,' equals ', $y; }?>
Or another way?

While I'm on the topic of strings, is echo and commas good practice? I've read in a few places it's the fastest/easiest to read, but I don't recall seeing it used that often.

epswing
Nov 4, 2003

Soiled Meat
I use
php:
<?
echo "$x equals $y";?>
when I can.
It's cleaner, no commas, less chance of a syntax error.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Baggy_Brad posted:

I'm curious, is there an official (or unofficial) standard for comparing strings?
Good old == works just fine. There's no need to invoke a function.

quote:

While I'm on the topic of strings, is echo and commas good practice? I've read in a few places it's the fastest/easiest to read, but I don't recall seeing it used that often.
I was about to say that echo using commas was ever so very slightly faster than using . to concatenate, but I'm wrong. I put together a small benchmark. This is for PHP 5.3.3 on Fedora 13.

php:
<?php
$then microtime(true);
$cycles 1000000; 
while($cycles--) { echo "1""2""3""4""5""\n"; }
printf("\nTime taken: %0.4f\n"microtime(true) - $then);

Time taken: 13.0978
Time taken: 13.0630
Time taken: 13.2739
Time taken: 13.0910

php:
<?php
$then microtime(true);
$cycles 1000000; 
while($cycles--) { echo "1" "2" "3" "4" "5" "\n"; }
printf("\nTime taken: %0.4f\n"microtime(true) - $then);

Time taken: 12.7028
Time taken: 12.7821
Time taken: 12.9171
Time taken: 12.8754

Conclusion: If you are doing one million echos, using concat instead of commas is about 5% faster.

I personally use commas when splitting an echo over many lines to avoid quote escaping:
php:
<?php
echo '<a href="',
     $foo,
     '">',
     $bar,
     '</a>';

If only PHP had something like Perl's q/qq operators...

McGlockenshire fucked around with this message at 19:25 on Dec 1, 2010

spiritual bypass
Feb 19, 2008

Grimey Drawer
Interpolated double quote variables kick rear end if your editor highlights them.

cka
May 3, 2004
Is "filter_var" good enough for input sanitizing? Some brazilian fucknut was trying to get into works' online store with injection exploits about a hour ago, and for whatever reason the software we use didn't seem to protect against passing quotes in the search field. I've since kind of gone overboard setting up input filtering on the search engine. This is my stop-gap solution right now:

php:
<?
$data['substring'] = str_replace("\0", "", $data['substring']);

if (function_exists('filter_var')) 
{
  $data['substring'] = filter_var($data['substring'], FILTER_SANITIZE_SPECIAL_CHARS);
} 
else 
{
  $data["substring"] = 
    mysql_real_escape_string(trim(htmlentities($data["substring"], ENT_QUOTES)));
}
?>
I can pass in quotes without it triggering SQL errors now, so that's good, but it would be nice to know if there was another simple way to do it. Why this software didn't filter input before I don't know...

edit: lol newline'd the mysql_real_escape_string part cause of table breakin'

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

McGlockenshire posted:


I was about to say that echo using commas was ever so very slightly faster than using . to concatenate, but I'm wrong. I put together a small benchmark. This is for PHP 5.3.3 on Fedora 13.

php:
<?php
$then microtime(true);
$cycles 1000000; 
while($cycles--) { echo "1""2""3""4""5""\n"; }
printf("\nTime taken: %0.4f\n"microtime(true) - $then);

Time taken: 13.0978
Time taken: 13.0630
Time taken: 13.2739
Time taken: 13.0910

php:
<?php
$then microtime(true);
$cycles 1000000; 
while($cycles--) { echo "1" "2" "3" "4" "5" "\n"; }
printf("\nTime taken: %0.4f\n"microtime(true) - $then);

Time taken: 12.7028
Time taken: 12.7821
Time taken: 12.9171
Time taken: 12.8754

Conclusion: If you are doing one million echos, using concat instead of commas is about 5% faster.



Commas are twice as fast for me. Using your code I get this:

Time taken: 0.2130
Time taken: 0.2075
Time taken: 0.2073
Time taken: 0.2079

And with concatenation:

Time taken: 0.4286
Time taken: 0.4167
Time taken: 0.4127
Time taken: 0.4239

I don't think it matters much. I guess if people really care, they can try it themselves.
PHP 5.3.2 on Ubuntu 10.4

bobthecheese
Jun 7, 2006
Although I've never met Martha Stewart, I'll probably never birth her child.
I think if you're writing code where that type of performance change makes a difference, you're using the wrong language.

spiritual bypass
Feb 19, 2008

Grimey Drawer
It's hard to imagine a webapp that spends more time in PHP than it spends in the database, isn't it?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Doctor rear end in a top hat posted:

Commas are twice as fast for me. Using your code I get this:

Time taken: 0.2130
Time taken: 0.2075
Time taken: 0.2073
Time taken: 0.2079

And with concatenation:

Time taken: 0.4286
Time taken: 0.4167
Time taken: 0.4127
Time taken: 0.4239

I don't think it matters much. I guess if people really care, they can try it themselves.
PHP 5.3.2 on Ubuntu 10.4

Something ain't right here.

I adjusted the printf with a fopen/fwrite to php://stderr and piped output to /dev/null at the command line. For concat, I got ~0.88 seconds, then I got a whopping ~2.2 seconds for commas.

Then I wrapped the while in an ob_start and ob_end_clean, which resulted in a consistent ~0.48 for concat and a consistent ~0.40 for commas.

Output is way more expensive than how you get there.

rt4 posted:

It's hard to imagine a webapp that spends more time in PHP than it spends in the database, isn't it?

Not necessarily. Some of the worst pages on our internal app approach and regularly exceed 50% PHP time. Lots of business logic that can't be done at the database level (because the original developers were clueless and we're stuck with their architectural mistake). For example, a report that Purchasing uses many times a day takes about 5 seconds on average to generate, spending "only" 2.4 of that in the database. They've burned 24 minutes in the past two weeks waiting for that page to load. We call it the "soul sucking" factor, it's a great thing to measure and mitigate. (The Purchasing lead has burnt a full hour waiting for our app over the past two weeks. He's our best, worst user.)

McGlockenshire fucked around with this message at 08:30 on Dec 2, 2010

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

McGlockenshire posted:

Then I wrapped the while in an ob_start and ob_end_clean, which resulted in a consistent ~0.48 for concat and a consistent ~0.40 for commas.

I should have mentioned that this is what I did.

Hadlock
Nov 9, 2004

is this even possible?

On my php enabled webserver (godaddy + wordpress) have a folder root/files/imagecycle/ with 5 images in /imagecycle
In root/files/ there is one image called banner.png

Every 20 minutes I want to copy one file (sequentially, randomly, whatever) from /imagecycle to /files and rename it banner.png

The end result being that banner.png changes to a different image in a set folder every 20 minutes, but retains the same filename. I bet there's a simpler way to do this. Google hasn't been much help.

Any ideas?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
You need five files swapped out every 20 minutes. Or, in other words:
php:
<?php
// Five files.
    $files = array(
        'file1.jpg',  'file2.jpg',  'file3.jpg',  'file4.jpg',  'file5.jpg'
    );
// Five files over sixty minutes.
    $minutes_per_file 60 count($files); // = 12
    $current_minutes_in_hour date('i');
// Make zero minutes equal to sixty minutes.  Yeah, really.  Why?
    if($current_minutes_in_hour) == 0
        $current_minutes_in_hour 60;
    $array_index floor($current_minutes_in_hour $minutes_per_file);
// Because: 0 for minutes 0-11, 1 for 12-24, 2 for 25-36, 3 for 37-48, 4 for 49-60
    $filename $files$array_index ];

You can then do whatever you need to do with $filename. You probably don't want to actually overwrite the file. You can just use this code to serve up the correct filename to begin with.

If you need this run on a timer, you'll need it to be a cron script. I'm not sure if GoDaddy does those, they're a pretty universally awful host.

As an alternative to hard-coding the filenames, you can also do this:
php:
<?php
    $files glob('directory/*.jpg');

Hadlock
Nov 9, 2004

McGlockenshire posted:

As an alternative to hard-coding the filenames, you can also do this:
php:
<?php
    $files glob('directory/*.jpg');

Even better. That's what I was hoping for, but I didn't want to ask too much.

Baggy_Brad
Jun 9, 2003

THUNDERDOME LOSER
If you are serving different images up by changing them to the same file name you can also run into problems with caching, where the user's browser won't change the image because it doesn't know it has changed on the server.

Also, if you don't have cron and these banners aren't time relevant you could cycle the images by pageviews and store a counter in your $_SESSION array, so that after every x page views it shows the next banner.

Super Delegate
Jan 20, 2005

ƃɐlɟ ǝɥʇ
I'm trying to sort my array by different categories. The code that works looks like this.
code:
$author[$key]  = $row['author'];
array_multisort($author, SORT_DESC, $books);
I'm trying to get this code to work.
Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag

When $getview echos as author the code still doesn't work.
code:
echo $_GET["view"];
$getview = $_GET["view"];
echo $getview;
$getview[$key]  = $row[$getview];
array_multisort($getview, SORT_DESC, $books);

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Super Delegate posted:

I'm trying to sort my array by different categories. The code that works looks like this.
code:
$author[$key]  = $row['author'];
array_multisort($author, SORT_DESC, $books);
I'm trying to get this code to work.
Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag

When $getview echos as author the code still doesn't work.
code:
echo $_GET["view"];
$getview = $_GET["view"];
echo $getview;
$getview[$key]  = $row[$getview];
array_multisort($getview, SORT_DESC, $books);

Without more information on the types of these variables it's a bit hard to say, but perhaps $getview is a string and the [] is being treated as string offset notation? You would then be passing a string rather than an array.

Super Delegate
Jan 20, 2005

ƃɐlɟ ǝɥʇ

Hammerite posted:

Without more information on the types of these variables it's a bit hard to say, but perhaps $getview is a string and the [] is being treated as string offset notation? You would then be passing a string rather than an array.
code:
$author[$key]  = $row['author'];
array_multisort($author, SORT_DESC, $books);
In the above code I can replace $row['author']; with title, price, etc and the code works fine.
$getview is set to the same words (title,author,price,etc) and it does not work.

Baggy_Brad
Jun 9, 2003

THUNDERDOME LOSER
The first argument to array_multisort needs to be an array, you're passing it a value off the query string.

In your working example you're passing an array called $author to the method.

In the second you're passing a string called $getview.

If, for example, you have an array called $author and an array called $title declared in your code, you need some logic.

I.E.
php:
<?
$author = array(....);
$title = array(....);

if ($getview == "author"){
array_multisort($author, SORT_DESC, $books);
} else if ($getview == "title"){
array_multisort($title, SORT_DESC, $books);
}
?>
Alternatively, I think you can use $$ to access the arrays.

php:
<?
$author = array(....);
echo $_GET['view']; // author
$getview = $_GET['view'];
if (is_array($$getview)){
array_multisort($$getview, SORT_DESC, $books);
}
?>
But this puts you at risk of throwing an exception if someone dicks with your query string and passes an array that you don't want to be sorting, so you'd want to use a whitelist if you take this approach, unless you know you can always trust your user.

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

Baggy_Brad posted:

Alternatively, I think you can use $$ to access the arrays.

php:
<?
$author = array(....);
echo $_GET['view']; // author
$getview = $_GET['view'];
if (is_array($$getview)){
array_multisort($$getview, SORT_DESC, $books);
}
?>
But this puts you at risk of throwing an exception if someone dicks with your query string and passes an array that you don't want to be sorting, so you'd want to use a whitelist if you take this approach, unless you know you can always trust your user.

The $$ operator makes a variable with the name of what was in the original.

php:
<?
$butt = "abutt";
$$butt = "twobutts";
echo $abutt;
?>
will echo "twobutts"

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Oh, I didn't twig to what he was trying to do.

Yeah, as it stands if $_GET['view'] contains 'author' you're trying to array_multisort the string 'author', whereas what you wanted to do was array_multisort the array $author. Yes, using variable variables (with appropriate sanitisation) would be one way of doing what you want to do, although I don't approve of it.

butt dickus
Jul 7, 2007

top ten juiced up coaches
and the top ten juiced up players

Hammerite posted:

Oh, I didn't twig to what he was trying to do.

Yeah, as it stands if $_GET['view'] contains 'author' you're trying to array_multisort the string 'author', whereas what you wanted to do was array_multisort the array $author. Yes, using variable variables (with appropriate sanitisation) would be one way of doing what you want to do, although I don't approve of it.

Ah it all makes sense now. The whitelist would be an easy approach.

php:
<?
$fields = array("author", "name", "blah", "bluh");
if(!in_array($_GET['view'], $fields))
  die("Don't dick with my querystring, rear end");
?>

Baggy_Brad
Jun 9, 2003

THUNDERDOME LOSER

Doctor rear end in a top hat posted:

The $$ operator makes a variable with the name of what was in the original.

php:
<?
$butt = "abutt";
$$butt = "twobutts";
echo $abutt;
?>
will echo "twobutts"

Not only make, but also access. E.g.

php:
<?
$_GET['view'] = "author";
$getview = $_GET['view'];
$author = array("one","two","do the kungfu");
print_r($$getview); // Array ( [0] => one [1] => two [2] => do the kungfu )
?>
Not that I'm saying this is the approach to be used, just more "this is right syntax for what you're trying to do now". :)

Long John Power
Sep 11, 2001

Does anyone know what the largest file size that PHP can handle is?

I am trying to do this...

code:
<?php 

echo "<h1>Data Split-o-matic</h1>";
//$loadeddatafile = file('data.dat');

$loadeddatafile=file_get_contents('/data.dat', true);

$loadeddatafile= explode("+++", $loadeddatafile);

$number_of_lines = count($loadeddatafile );

echo "Number of lines: $number_of_lines<br><br>";
echo "<hr>";

for ( $counter = 0; $counter < $number_of_lines; $counter += 1) {

$string = $loadeddatafile[$counter];
echo "testing: $counter <br>";
if (preg_match("/991/i", $string)) {
    	echo "$loadeddatafile[$counter]";
    	echo "<br><br>";
    	} 
      else {
    echo "Record not found.<br><br><br>";
}

}
	
The problem is that data.dat is 80mb, I could split it up and use smaller parts but I am wondering if there is any sort of limit to the size of data I can pass around in PHP that I need to stick to?

Or is it just one part in particular that is going wrong?

gibbed
Apr 10, 2006

PHP can open any size file the file system can handle, loading the file data into memory is what you're concerned about, and depends on the memory limit settings in php.ini.

Long John Power
Sep 11, 2001

gibbed posted:

PHP can open any size file the file system can handle, loading the file data into memory is what you're concerned about, and depends on the memory limit settings in php.ini.

Cheers I came back to post that it ended up being the server that was the problem. I had fixed the memory limit but not restarted it. Schoolboy error on my part.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Long John Power posted:

Cheers I came back to post that it ended up being the server that was the problem. I had fixed the memory limit but not restarted it. Schoolboy error on my part.

There's also the maximum execution time which is set to 30 seconds by default. Sounds like that wasn't the issue but it's always a good setting to be aware of.

Ziir
Nov 20, 2004

by Ozmaugh
I have a form where people can type in data and then I want php to do some math with it. Is there a way to set the entered value directly as a variable? Right now I'm doing something like $data = $_POST["valueofinput"] after the form submit because that's what the first google result told me to do but I'd like to just skip this step if possible.

Baggy_Brad
Jun 9, 2003

THUNDERDOME LOSER

Ziir posted:

I have a form where people can type in data and then I want php to do some math with it. Is there a way to set the entered value directly as a variable? Right now I'm doing something like $data = $_POST["valueofinput"] after the form submit because that's what the first google result told me to do but I'd like to just skip this step if possible.

There is, but you don't want to do it. It would mean a user could hoax your form and submit a value for whatever variable in your script they wanted.

In fact, you really should be doing some checking on the value from POST before attempting anything with it.

E.G. at the very least:
$data = floatval($_POST["valueofinput");

epswing
Nov 4, 2003

Soiled Meat

Ziir posted:

I'd like to just skip this step if possible.

ahhh nm.

epswing fucked around with this message at 15:27 on Dec 16, 2010

KuruMonkey
Jul 23, 2004

Ziir posted:

I have a form where people can type in data and then I want php to do some math with it. Is there a way to set the entered value directly as a variable? Right now I'm doing something like $data = $_POST["valueofinput"] after the form submit because that's what the first google result told me to do but I'd like to just skip this step if possible.

I think this requires a more colourful response.

Accepting form content should be seen as analogous to agreeing to accept the sexual advances of anyone who happens to wander past.

Your request is therefore akin to "google says I should use a condom, but I'd like to skip that step".

DO NOT SKIP STEP!!

DarkLotus
Sep 30, 2001

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

KuruMonkey posted:

I think this requires a more colourful response.

Accepting form content should be seen as analogous to agreeing to accept the sexual advances of anyone who happens to wander past.

Your request is therefore akin to "google says I should use a condom, but I'd like to skip that step".

DO NOT SKIP STEP!!
I love it! Thank you for making me smile :)

Ziir
Nov 20, 2004

by Ozmaugh

Baggy_Brad posted:

There is, but you don't want to do it. It would mean a user could hoax your form and submit a value for whatever variable in your script they wanted.

In fact, you really should be doing some checking on the value from POST before attempting anything with it.

E.G. at the very least:
$data = floatval($_POST["valueofinput");

Thanks, that was my next question, how do I forbid a user from entering in something that isn't a number?

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Ziir posted:

Thanks, that was my next question, how do I forbid a user from entering in something that isn't a number?

You could use Javascript to validate user input, but you can't count on that. You have to either check the input yourself (look at http://php.net/manual/en/function.preg-match.php to make some sanity-checking regexes) or clean it and use it as best you can.

floatval() will return 0 if whatever gets passed in can't be interpreted as a float* (same with intval), so you can just use whatever comes out of it.

*This is an oversimplification of what the manual says: http://php.net/manual/en/function.floatval.php

Munkeymon fucked around with this message at 18:55 on Dec 16, 2010

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