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
Standish
May 21, 2001

Bonus posted:

You also can't do
php:
<?
$bla = new Something()->method();
?>
and I don't know why the hell PHP doesn't allow that.

You also can't do
php:
<?
empty(someFunctionThatReturnsAString())?>
which bit me earlier today.

Adbot
ADBOT LOVES YOU

Standish
May 21, 2001

"Unexpected T_PAAMAYIM_NEKUDOTAYIM" is my favourite PHP wtf, what do you mean not everybody speaks Hebrew?

Standish
May 21, 2001

Tap posted:

When a variable or function is declared with a single underscore as the first character (i.e. $_foo or $_fake_function()), what exactly does this tell me as a programmer?
It has no set meaning, but it's often used to denote an class member or an internal function i.e. anything that shouldn't be directly used except by the original author of the code.

Standish
May 21, 2001

fletcher posted:

When I am validating fields submitted from a form I end up with a big if/else like:

php:
<?
if (!aValid) {
    //error information
} else {
    if (!bValid) {
        //error information
    } else {
        if (!cValid) {
            //error information
        } else {
            //db interaction
        }
    }
}?>
There's gotta be a better way than that. What's the right way to do this? Should the fields be validated by the setters of my class?
Use "else if" rather than nested "if"s:
php:
<?
if (!aValid) {
    //error information
} 
else if (!bValid) {
    //error information
} 
else if (!cValid) {
    //error information
} 
else {
    //db interaction    
}?>

Standish
May 21, 2001

Jahuran posted:

I figured I could do it in a few ways:
  • 1.Store a file on the filesystem per user with their colorpicks in it and load these into a session whenever they return to the website.
  • 2.Store a file on the filesystem per user and load it everytime a user loads up a page.
  • 3.Store the colorsettings in a database table and load them into a session when the user returns to the website.
  • 4.Store the colorsettings in a database table and load them everytime a user loads up a page.

Options 1 and 2 create a heavier load in terms of disk i/o.
Options 3 and 4 create more constant database queries (disk i/o and processing)

Options 3 and 4 seem the most viable to me. I'm expecting around 250 concurrent users daily during normal business hours. When people navigate to eachothers pages the colorpicks of the page they are visiting need to be loaded not their own!

So what method would you guys pick? Is there another way of going about this?
Recommendations are very welcome!
PHP by default stores session data in a file on disk so 1, 2 and 3 are actually the same thing from a performance point of view, just with different interfaces. Use a database like the guy said, it's going to be orders of magnitude faster to query an indexed database table containing a million user records than to open a file in a directory containing a million user settings files.

Standish fucked around with this message at 11:56 on Apr 13, 2008

Standish
May 21, 2001

Safety Shaun posted:

How do I get the data of say, http://55.55.55.55/image.jpg or http://myimageserver.com/image.jpg into $imagedata?
Use the cURL http library:
php:
<?php

$ch curl_init("http://myimageserver.com/image.jpg");

curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
$imagedata curl_exec($ch);
curl_close($ch);
?>

Standish
May 21, 2001

fletcher posted:

I thought HTTP_REFERER couldn't be trusted?
Cross-site request forgery isn't an attack on the server, it's an attack on the client. It doesn't enable the client to do anything it doesn't already have permission to do, it just tricks the client into doing it with the wrong parameters.

Standish fucked around with this message at 00:16 on May 3, 2008

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.

Standish
May 21, 2001

blunt posted:

I've been having a problem where the following is throwing out a syntax error and i for the life of me can't find the problem

php:
<?
$check = mysql_query("SELECT 'id', 'fname', 'lname', 'active', 'type' FROM 'users' WHERE 'email' = $email AND 'pass' = $pass") 
    or die(mysql_error());
?>
I've tried just about every variation of ' placement, spaces and anything else i can think of but im sure its stupidly simple :(

Single quotes go around string literals, not around column names:
php:
<?
$check = mysql_query("SELECT id, fname, lname, active, type FROM users WHERE email = '$email' AND pass = '$pass'") 
    or die(mysql_error());
?>

Standish
May 21, 2001

Emo Businessman posted:

I know that I can 'fix' the error by simply passing a $this reference to SubCoolio, but I am curious as to why $this disappears as soon as the function in the include is called. What's happening here?
"require", "include" and their variants do simple text inclusion, so what you've really got from PHP's point of view is:
php:
<?php
 // index.php 
class Coolio 
{   
    function Coolio()   
    {
        // inc.php
        echo $this->WhatIsIt("Coolio"); 
        SubCoolio(); 
        function SubCoolio() 
        {   
             echo $this->WhatIsIt("SubCoolio"); 
        } 
    }   
    function WhatIsIt($string)   
    {     
        return "<p>WhatIsIt is being called from ".$string."</p>";   
    } 
} 
$nothing = new Coolio(); 
?> 
Nested functions in PHP can't see their parent function's scope.

Standish
May 21, 2001

Safety Shaun posted:

I could transmit the answer back
php:
<?
<input type="button" value="Answer Here">?>
and compare that field to the correcta on submission, but I'm assuming it will start spitting out "wrong answer" messages when the correct answer is clicked if the answer contains certain characters.
htmlspecialchars() and mysql_real_escape_string().

Standish
May 21, 2001

Safety Shaun posted:

$q_image = str_replace('\', '/', $q_image);
and
$q_image = str_replace("\", "/", $q_image);
are messing up for me, is there any way I can replace slashes?
Backslashes inside double quotes need to be escaped with a double \ i.e.
php:
<?
$q_image = str_replace('\\', '/', $q_image);
and
$q_image = str_replace("\\", "/", $q_image);?>

Standish
May 21, 2001

You're assigning empty variables to the session,
php:
<?
$name=$_POST['name']; 
$address=$_POST['address'];?>
needs to go before
php:
<?
$_SESSION['name'] = $name; 
$_SESSION['address'] = $address; ?>

Standish
May 21, 2001

Lank posted:

Right now, when I use fopen, fgets and then a little csv parser I wrote, and then add the rows to my sql tables I'm having an issue. On both the echo statements I use for debugging in firefox and in the actual table itself there is a little black diamond with a question mark in it in between every single character.


If I open said csv in notepad, resave it as ANSI encoding and run the exact same process, it works fine.
If every single character (even regular alphanumeric characters) has a black diamond before it then it sounds more like UCS-2 encoding than UTF-8. Try
php:
<?
iconv("UCS-2","UTF-8", $string);?>

quote:

I have a csv that's generated from a website that I need to read in to a sql table.
Check out the response headers on the website you're downloading the CSV from, is it sending a particular character set in the Content-Type?

Standish fucked around with this message at 20:48 on Sep 10, 2008

Standish
May 21, 2001

Stephen posted:

I guess if I stored the session ID and the IP address in the database and matched them each time the user browses to a page, it wouldn't be so bad.
You can't assume in general that a user will retain the same IP address for the length of their session, it breaks for a lot of ISPs that put their users behind transparent load-balancing proxies. (You can't even assume the top /16 or /24 bits of the IP will be the same, I've run into situations where consecutive requests from the same user came from totally unrelated IPs.)


If you want to protect your users against cookie sniffing/session hijacking, use SSL (and set the "secure only" attribute on your cookies).

Standish
May 21, 2001

Munkeymon posted:

And I guess you could make PHP tell you how may days there are in a year, but I'm going to cross my fingers that nothing changes that for a long time.
Actually it changed this year.

Standish
May 21, 2001

KuruMonkey posted:

I don't do a lot with timezones, honestly (its a perk of living in GMT - just make everything Zulu and forget about it)
...until March when all your times will be 1 hour off for six months.

quote:

But; when I do, I simply...

1-store all times as Zulu
2-manually offset by any required timezone offset using the magic of addition and subtraction, at the point the offset is required (i.e. I brute force it)
Again, this won't work because of daylight saving time. (Even if you're not currently under daylight saving time, the time you're converting could need to be adjusted for DST, for example my offset from GMT is currently zero, but if I want to format the UTC time "2009-06-01 12:00Z" then that needs to be offset by 1 hour even though DST is not currently in effect in my timezone.).


The right way to do it is to store the symbolic zoneinfo timezone name e.g. "Europe/Berlin" and call
php:
<?
$timezone = $user->getPreferredTimezone(); // or whatever
date_default_timezone_set($timezone); 
?>
somewhere near the start of your script.

Standish
May 21, 2001

Stephen posted:

I've been trying to create a multipart text/html email and for some reason I can't get it to read properly. Here's what I've been doing, following examples of mime types on Google:
code:
$headers = 'From: E-mail <email@myaddress.com>';
$headers .= "MIME-Version: 1.0\r\n";
$headers .= 'Content-type: multipart/mixed; boundary="boundary123"'."\r\n";

$body = "--boundary123\r\n";
$body.= "Content-type: text/plain\r\n";
$body.= "Here's some content";
$body.= "--boundary123";
$body.= "Content-type: text/html\r\n";
$body.= "<html><Here's some HTML content</html>";
$body.="--boundary123--";

mail($to, $subject, $body, $headers )
The email will show up in my inbox, however it doesn't properly split the boundaries, it just prints them on the page with all the HTML as text.

Can anyone point out what the issue with my code is? Thanks
You need two "\r\n"s between the last header and the body, not one. Also it's "Content-Type", not "Content-type". Also you have no \r\n after the From: header, or before the "--boundary123"s.

Standish
May 21, 2001

awdio posted:

I finally figured out what was causing the problem, but I don't know WHY it happens. I had a variable defined with a get:

$catNum=$_GET['catNum'];

If I simply make that variable a number and not the get my other variable from the database gets sent to Flash. Why??

$catNum=3;

Edit: Basically, if I have that variable $catNum defined with the get $_GET['catNum'], $imageSourcesString does not pass to Flash! If I make $catNum equal say, "3", everything works. But I NEED the get for $catNum.
Looks like Flash is not supplying the "catNum" parameter in its GET query string for some reason, try running wireshark to see exactly what's going over the wire.

Standish
May 21, 2001

Lankiveil posted:

I've got some strings that need to be inserted into the database via an UPDATE command. However, the strings may or may not already be escaped (don't ask). For instance, I might have "don't go not don't" or "don/'t go not don/'t" passed to my module.

Is there any reliable way to make sure that apostrophes have only one slash, and are not double-slashed like in this thread title?
No, you cannot tell the difference between "\\\' because it's been double-escaped" and "\\\' because that's what the user actually entered".

Standish
May 21, 2001

Sylink posted:

How would I test to see if a database query returned no results?
php:
<?
if (mysql_num_rows($result) == 0)
?>

Standish
May 21, 2001

nbv4 posted:

it looks like this: "México", with a "A" with a squiggly line above it and a copyright logo
That is the correct UTF-8 encoding of the "e grave" character "0xC3 0xA9", except your browser is interpreting it as ISO-8859-1 where 0xC3="A tilde" and 0xA9="copyright symbol".

Looks like utf8_encode is working fine, check your page charset.

Standish
May 21, 2001

cLin posted:

gently caress yes it helps. Thanks. With letting any user access their data, aren't they prone to attacks/malicious doings?
No, typically you only get access to the same operations that are accessible via a HTTP/web browser interface and using the same authentication/access control, just with a more programmer-friendly interface on it.

Standish
May 21, 2001

SmirkingJack posted:

I was digging through some Kohana code and came across this syntax, which I have never seen before:

php:
<?
($field === TRUE) and $field = $this->any_field;?>
What does this do?
this is called "short-circuiting".
http://en.wikipedia.org/wiki/Short-circuit_evaluation

doing it in the context of
php:
<?
some_func() or die("some_func() returned an error!");
?>
is a very common idiom but using it for assignment like in the example you gave is a bit obfuscated.

Standish
May 21, 2001

Safety Shaun posted:

php:
<?
$myArray = $_REQUEST["myArray"];
print_r($myArray); //prints the contents fine
//^^^ Array ( ['someVar1'] => text woo ['someVar2'] => text wee ['someVar3'] => text omg ['someVar4'] => ['someVar5'] => ) 
echo "test: alias = " . $myArray['someVar1']. "<br>"; //blank?
?>
What am I doing wrong please? the array is bring passed across from the form on the previous page and print_rd properly but I am having trouble using those array entities.
can't tell without full code but I'm guessing $_REQUEST["myArray"] is the literal text:

"Array ( ['someVar1'] => text woo ['someVar2'] => text wee ['someVar3'] => text omg ['someVar4'] => ['someVar5'] => ) "

and not an array at all.

Standish
May 21, 2001

Filthy Lucre posted:

After spending a few hours trying to get Jack's formmail.php script working and not having any luck, I gave up and wrote my own.

Since I'm pretty new at PHP, I was hoping someone with a little more experience could give my code a quick look over to make sure I'm not doing anything obviously stupid before I put the code on a public web page.

code:
<?php
$to = "me@mydomain.com";
$bcc = "";

function sanitizePOST() {
  $keyWords = array ( "to", "bcc");
  $body = "";
  
  foreach($_POST as $key => $value) {
    $goodText = true;
    for($i=0; $i<count($keyWords); $i++)
	  if ($key == $keyWords[$i]) $goodText = false;
	
    if ($goodText == true) {
	  if (strlen($value) > 0) $body .= $key .": " .$value ."\r\n\r\n";
	  else $body .= $key .": empty\r\n\r\n";
	}else exit;
  }
  return $body;
}

$msgBody = sanitizePOST();
$additionalHeaders 	= "From: Web Form Submittal\r\n";
if (strlen($bcc) > 0) $additionalHeaders .= "BCC: " .$bcc ."\r\n";
mail($to, "Web Form Submittal", $msgBody, $additionalHeaders);

echo "<b>Your submission has been sent. Thank you for your participation.</b><br><br>";
?>
$to and $bcc should be sanitized by the sanitizePOST function, so it shouldn't be able to send email to unauthorized addresses. I hope, anyway.
You're never assigning anything from $_POST to $to and $bcc (they're hardcoded to "me@mydomain.com" and "" respectively), so there should be no need to sanitize them, unless they're being automatically assigned because you have register_globals turned on, which is really really bad and should be turned off immediately.

Standish
May 21, 2001

Agrikk posted:

if ($IsThere=="no")
Also using strings "yes" and "no" instead of booleans is just shameful.

Standish
May 21, 2001

Agrikk posted:

Getting off topic for a second, what does it matter if I use strings or booleans? Is it a performance issue or something?
It's slower to use strings, yes, but the main thing is style and avoiding horrible bugs like
code:
$a = "no";
...
if ($a) // the string "no" converts to the boolean value true!

quote:

Oh motherfucker. Using booleans instead of strings actually made it all work.
No, it didn't, the problem was that you had a single '=' instead of a '==' in that line I quoted, so you were assigning $IsThere to "no" instead of checking its value. The reason it started working when you changed to booleans is because the assignment "$IsThere=false" itself evaluates to boolean false, so the if condition failed.

Standish fucked around with this message at 20:04 on Oct 1, 2009

Standish
May 21, 2001

insidius posted:

I already figured out how to use count to get the number of records to match them by type and spit out the results but I cant figure out exactly how to get records ONLY from the last 7 days that are marked completed. I can get completed and narrow it down to type but not to time.
code:
select * from records where taskstatus='completed' and date_submitted > (unix_timestamp() - (60 * 60 * 24  * 7))
But really, just use the MySQL DATETIME data type...

Standish
May 21, 2001

eHacked posted:

Hello friends :)

I am trying to pass some variables via exec.

Here is my code:

code:
exec("/usr/local/bin/php -q galleryHandling.php --task=50 > log.log &");
from my understanding,
code:
$argv[1];
should contain the passed information, right? It should have "task=50"... right?

Well obviously I'm missing something because no variables seem to be passed!

Are you using the CGI php binary instead of the CLI PHP binary?

http://www.php.net/manual/en/features.commandline.php

Standish
May 21, 2001

crabrock posted:

http://uk3.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime?

Standish
May 21, 2001

quote:

Anyone have an idea why ? All the other words go through fine.
"AD" is a valid hexadecimal number while "CI" and "NA" aren't, so I'm guessing something somewhere is calling urldecode() on your text (or you're failing to call urlencode() on it in the first place and it's getting automatically decoded into $_REQUEST).

Standish
May 21, 2001

You need to have an explicit constructor for class playerrankclass as follows:
php:
<?
class playerrankclass {
    public $rankname;
    public $rankmin;
    public $rankmax;
    function playerrankclass($newRankname, $newRankmin, $newRankmax) { 
        $rankname = $newRankname;
        $rankmin = $newRankmin;
        $rankmax = $newRankmax;
    }
}
?>
It's not smart enough to figure out "oh, the class has 3 members and you're passing 3 args to the constructor, I'll automatically assign them".

Standish
May 21, 2001

Hammerite posted:

When I saw that post my immediate reaction was "What? Can you do that?" (You can't, unless my hosting has set some ini setting to disable it)
Yes, you can do this:http://de2.php.net/manual/en/functions.variable-functions.php

but if you do and I end up having to maintain your code I will track you down and kill you.

Standish
May 21, 2001

Yossarko posted:

But I'm trying to chmod some files to 0755 and I get "Operation not permitted".

The owner of the file (well, all files) is my FTP username. PHP script is running as "apache" I think.

I don't want to have to manually chmod files or folders in FTP, rather I want my script, when run, to chmod various directories and files (upload folders, temp folders, log files). Once I put my website online I run this script and it correctly sets the permissions.

How can I get around this ?
You need to be the owner of the file (or root) to call chmod on it. Have your PHP script make a temp copy of the file, delete the original, then copy your temp copy back over it.

Standish
May 21, 2001

Yossarko posted:

Yeah, I know. I understand, but isn't there any way to just give "apache" (www-data in my case) full rights ?
Not really, and running your webserver as root is a really bad idea anyway.

Your best bet would probaby write a tiny C program that is owned by the FTP upload user, and has the setuid bit set, and that calls the chmod(2) library function on its (carefully validated) argument. You can then invoke that program from PHP using system() or exec() whatever.

Edit: or depending on which FTP server software you're using, you might be able to set the default umask so the permissions on uploaded files are the ones you want to begin with.

Standish fucked around with this message at 15:58 on Oct 21, 2009

Standish
May 21, 2001

Begby posted:

$secondsInADay = 60 * 60 * 24;
Not all days have 24 hours.

Standish
May 21, 2001

v1nce posted:

The foreach method seems retarded and wastes a lot of memory if $store happens to be very large.
"$result = $store;" does not actually make a full copy of the contents of $store, it'll just make $result a reference to $store, (until and unless you modify the array via the $result reference, then it'll do a copy-on-write, (but you can turn this copy-on-write behaviour off by assigning by reference e.g. "$result=&$store")).

See for yourself

This article is a pretty good explanation of references in PHP.

Standish
May 21, 2001

Yossarko posted:

When using mysql_connect, is there any way to connect without having my password in the PHP files in clear text ?

I'd like to maybe MD5 the password, and when mysql_connect'ing tell it to compare it with an MD5'd version of the database password.
Pointless. Sure, your password can't be stolen if someone gains read access to your PHP source, but they can steal the MD5'ed password, which is just as good as the password itself for the purposes of logging into the DB.

(Also I wouldn't use MD5 for any new security-related code, best practice is to use SHA-2.)

Standish fucked around with this message at 11:00 on Jan 4, 2010

Adbot
ADBOT LOVES YOU

Standish
May 21, 2001

epswing posted:

I'm pulling a couple DECIMAL(10,2) values from the db, but I see warning signs everywhere making sure I never compare floats. How does one do anything related to currency in php? Rounding? BC_Math? String comparison? Keeping dollars and cents as separate integers?
Store everything as cents.

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