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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
YES! A php megathread. I was tempted to ask why there wasn't one the other day.

Can you combine a function call that returns an array with the array index you want like:

$something = $this->arrayReturningMethod()[0];

I tried it and it didn't work. Am I doing it wrong or can you not do this in PHP? Are there languages where this does work?

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

gi- posted:

So I just upgraded my hosting environment. Went from PHP4 to PHP5 and getting this error 'Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource'

for this piece of code:


Is the mysql_query failing? Add this after it.

php:
<?
if (!$rs) {
    die('Invalid query: ' . mysql_error());
}
?>

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Super 3 posted:

Dont have access to the php.ini over here.


More like a charting tool.

Essentially it's 12 stores that all have a sales goal, that I want to show via a progress bar/graph/visual thing.

http://code.google.com/apis/chart/

I used this for a project recently and absolutely loved it. Let me know if you have any questions about it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
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?

fletcher fucked around with this message at 19:27 on Mar 27, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

functional posted:

php:
<?
$a=array(aValid,bValid,cValid);
$b=array("a error","b error","c error");
function test($a,$b)
{
 for($i=0;$i<count($a);$i++)if(!$a[$i])return $b[$i];
 return "all clear!";
}
?>

How do I put my test cases in the array? Let's say I'm doing a ctype_digit() on aValid and making sure it's < someValue. Or do I do that before and just stuff the result in the array?

fletcher fucked around with this message at 19:51 on Mar 27, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Thanks for all the replies guys, very helpful and appreciated.

Another question, is it a bad idea to use an existing php function name as the name of a method in a class? Like if I want to use $obj->delete(), wasn't sure if that's frowned upon.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's the point of declaring public variables in a class? If I remove them all, my application will behave the same, correct?

php:
<?
class User {
    public $id;
    public $username;
}
?>

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bt_escm posted:

With the way php currently handles objects there's no difference. However removing public or even not declaring the variables is just plain bad practice and could possibly break in future versions of php.

What's a good way to maintain my public variable declarations if they are all the exact same as my field names in the database, or do I have to just do it manually?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bt_escm posted:


What I done in the past is build an array of the column definitions like this

Wow I like that way. That makes validating all the input so much easier, thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Foolio882 posted:

True, but getting rid of my "html nonsense" changes nothing as well:

php:
<?php header('Content-type: image/jpeg');
 
include("functions.inc");
 
displayPictureTable(shedsgable);
 
?>


What exactly does displayPictureTable spit out? You can't output any text or html with that header set.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Foolio882 posted:

Is there any way to mix html and php to output a table of pictures?

Like this?

code:
<table>
<?php
for ($i=0;$i<sizeof($whatever);$i++) {
echo '<tr><td><img src="'.$whatever[$i].'"></td></tr>';
}
?>
</table>
If you want thumbnails created automatically, when you read the directory of pictures also look or the <filename>_thumbnail.jpg, if it's not there, then create it, save it, and move on. You can use GD (built into PHP) to resize the images. I'm still kinda confused on what you are trying to do though.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Foolio882 posted:

But that's what I am trying to avoid, having seperate thumbnails.

You can use width and height on the <img> tag (which is a horrible way to do it) otherwise you are going to have to create separate thumbnails. Why is that such a bad solution if it's done automatically?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's a clean/efficient way to do bbcode replacements for format tags like [b], [i], etc?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Begby posted:

This has been done a lot. It would probably be a good idea to check out the source for a php package that has already implemented this.

On the surface it looks easy, you could just replace all the [ b]'s with <strong> and all the [/b]'s with </strong>. But if you want it to be right you need to make sure there is a matching closing tag for every open tag and vice versa. Otherwise you could break the rest of your layout. You also need to check if the tags are nested properly. I am sure there are other issues as well.

It does get quite confusing quickly trying to keep track of matching tags, nested tags, etc.

What if I did the simple replace [ b] and [/b] with the corresponding html not paying any attention to if it's properly formatted at the end, and then use DOMDocument to correct any html problems?

For example, this code:
php:
<?
    $doc = new DOMDocument();
    $doc->loadHTML("<strong>test<i>italic");
    echo $doc->saveHTML();
?>
outputs this:

code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><strong>test<i>italic</i></strong></body></html>
Which has corrected the malformed html. Is this a bad solution?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
All my classes refer to $this->database to interact with the database. Is there any way to avoid having to pass it in as a parameter to a static function of a different class that needs the db?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

OlSpazzy posted:

php:
<?
$newsid = $news['newsid'];
?>

I might be alone on this, but I don't understand the point of doing that. It adds lines to the code and makes it less readable, in my opinion.

Also, if you are using an object oriented DB layer instead of building the SQL manually like "SELECT * FROM `unp_comments` WHERE newsid='$newsid'" you should consider using prepared statements.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Finite posted:

I do it in a few places to do things like...

code:
$colour = $data['colour'];
$string = "The lazy $colour fox jumps over the I can't remember the rest of this."
But I decided that was a little stupid the other day and I'm trying to use sprintf instead.

What is wrong with

php:
<?
$string = "The lazy ".$data['color']." fox jumps over ...";
?>
Why introduce another variable?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

nbv4 posted:

I'm not worried about that, I'm worried about actually running the queries twice, one for each object. I'm kind of a performance stickler like that. Is there anyway to easily copy a bunch of member variables from one object to another? I admit I'm not really an OOP expert.

Not really sure how you are instantiating them, but this should work fine. Or if you are instantiating Bar inside of Foo's construct, $bar->fields = $this->fields, etc. I'm new to oop as well, so hopefully somebody else will weigh in on this too.

php:
<?
$foo = new Foo();
$bar = new Bar();

$foo->fields = $bar->fields;?>
This is also pretty neat:
php:
<?
get_class_vars(get_class($this));?>

fletcher fucked around with this message at 18:56 on Apr 7, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is it a bad idea to write a backup script in PHP? I just need it to dump the database, tar.gz a folder, delete the oldest backup on the backup server, and upload the new one. It seems like it would be cake to write it in PHP, but should I? Is there a reason I have to write this as a bash script?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bt_escm posted:

Here's an ORM http://propel.phpdb.org/trac/

I don't really understand what that helps with. Isn't it more beneficial to just learn/practice SQL?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Sewer Adventure posted:

If you use raw SQL then you will have to escape strings every time you input them and then remember to stripslashes every time you output them, you will have to build big rear end queries by concating strings and it eventually gets very ugly.

That's not true at all. I used PDO and didn't use a single string concatenation for SQL or have to worry about escaping ANY input throughout my entire application. Don't use addslashes, stripslashes, magic quotes, concatenation, or any of that other crap, that's the wrong way to do it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've been playing around with this s3 script and can't seem to figure out how to list more than 1,000 objects in a bucket.

Amazon mentions this here as the expected behavior and what you need to do.

In s3.php:
php:
<?
public function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null)
?>
So it looks like I should be able to, I just don't know what to pass into $marker. Any ideas?

edit: this seems to work

php:
<?
    $pictures = array();
    $done = false;
    $marker = null;
    while (!$done) {
        $set = $s3->getBucket(S3_BUCKET_PICTURES, null, $marker, null);
        if (sizeof($set) > 0) {
            $pictures = array_merge($pictures, $set);
            $marker = end(array_keys($pictures));
        } else
            $done = true;
    }
?>

fletcher fucked around with this message at 23:06 on Apr 12, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Safety Shaun posted:

I'm looking to stop image leeching on my server by using a fancypants URL hiding script.

You will need to know how to set the header of a document to let it know you will be outputting image data. You will need to pass something into the script, maybe a md5sum of a salted filename, like:

http://domain.com?script.php?id=9e107d9d372bb6826bd81d3542a419d6

script.php gets that id input using $_GET['id']. Using that, do whatever you need to do in the script to get back to a filename. Set the header and output the appropriate file.

fletcher fucked around with this message at 04:25 on Apr 14, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Grigori Rasputin posted:

Since zero evalutes to false, it fails even though I can tell the difference between a month that never occurs and a month at the zero position - I just can't test for it.

http://us3.php.net/strpos

php.net posted:

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

awdio posted:

Here's the code I used to validate a $_GET:

code:
<?php
if (strpos(strtolower($_SERVER['HTTP_REFERER']), 'mywebsite.com') !== false){
echo $_POST["sentVar"];
}
?>

I thought HTTP_REFERER couldn't be trusted?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Kaluza-Klein posted:

I've just never seen syntax like that. And the bit at the end there: ltrim() . $new : $string;? What is the colon doing?

Thank you for helping, I am just simple :(.

Are you talking about the Ternary Operator?

http://www.php.net/operators.comparison

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is it better to let the database (mysql) handle timezone conversions by setting the session timezone than to do it in PHP?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Grigori Rasputin posted:

I have a question that might be a little involved, but maybe someone can point me in the right direction.

Basically, I want to create a system that will automatically download an email (whenever I receive it) to the php webserver, parse it for relevant data and toss it in the db.

Basically, I have no idea how to connect to a mail server or locate the email whatsoever. I can think of a couple clunky ways to do it, just about all of which involve manual intervention. I'm looking to automate as much as possible.

Thanks!

Use this to get the mail
http://us2.php.net/imap

Use these functions to find information in the email
http://us2.php.net/manual/en/ref.strings.php

Use this to stuff it into a database
http://us2.php.net/pdo

Use a cron job to run it every x minutes

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

A Flaming Chicken posted:

MySQL only supports a single timezone - UTC?

Can't you do a SET time_zone = +10:00?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Do you guys pass in a database connection in to a static function or do you get the database connection from within the static function?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

ilikechapstick posted:

Quick question about PHP, I have used it only a couple times and have very limited PHP knowledge.

I have a phone number (of type string) in a database formatted as xxxxxxxxx.

I would like it to be printed as xxx-xxx-xxxx.

My job is to design the webpages, however this is pissing me off from a design standpoint so I need to figure it out. I can only assume I would need some kind of loop, but help me please!

I hope you don't get paid much to "design the webpages" since you can't even google 3 words.

http://www.google.com/search?hl=en&safe=off&q=php+phone+format&btnG=Search

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MrEnigma posted:

To be fair design and development although sometimes combined (sometimes in the same person) are usually at opposite ends of the spectrum. I wouldn't ever expect our design team to be able to do that.

You can just google it and copy paste the examples with 0 knowledge

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

ilikechapstick posted:

I've been scouring the internet for even tutorials on how to write a system like that but haven't found any. Was wondering if maybe you guys knew of anything out there like this?

Did you not like these?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
The PEAR Calendar object may also be useful to you.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

drcru posted:

What's the best or easiest way to add language support? By language support I mean we can display an error message in English or maybe French rather than just English.

In the past I've used some sort of a Message Catalog table in the DB with fields id, language, message. Then create a way to access that, like:

php:
<?
echo MessageCatalog->getMessage("hello", "es");?>
code:
hola
You will probably want to implement some sort of cache so you can store the messages in memory rather than querying the DB for each message every time you use it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

ryanbruce posted:

What would be the best way to attack something like this?

Why bother putting it in a text file and the parsing that to build your database? Why not just insert it directly into the database?

php:
<?
//do whatever you to to get the $vesrion, $ip, and $referrer variables filled

$database = new PDO('mysql:host=localhost;dbname=mysite', 'username', 'password');
$insert = $database->prepare("INSERT INTO ad_hits (version, ip, referrer) VALUES (:version, :ip, :referrer)");
$insert->bindParam(":version", $version);
$insert->bindParam(":ip", $ip);
$insert->bindParam(":referrer", $referrer);
$insert->execute();

?>
Don't bother inserting the date, make MySQL do that automatically for you when you insert the row. If you want your existing logs to be put in your database, use fgets to read a line, and then some string functions to widdle away at the line to exactly what you want. In the future, store something like this in a common format like CSV, so you can import it into ANY database with ZERO effort (or just straight into the database)

fletcher fucked around with this message at 22:53 on Jun 9, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

drcru posted:

I saw a thread about this a long time ago but I can't find it anymore so...

How do you do the authentication system like they have on AwfulYearbook.

If you don't know what I'm talking about, it's where a website checks to see if you have a specific line of text written onto a certain page.

I hope that made sense.

Use something shorter than an MD5 hash, as some of the profile fields don't let you put in 32 chars, causing people problems.

Use cURL to fetch the profile page. You will need to use cookies and your own bbuserid and bbpassword (find these by going through your cookies in firefox). Once you have the page loaded, just do a preg_match('/'.$code.'/', $page) and it will return true or false if $code is found in $page or not. Replace &userid=x to &username=x to search for a username.

php:
<?
   $ch = curl_init(EXTERNAL_PROFILE_USERID_URL.urlencode($id));
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_COOKIE, EXTERNAL_FORUM_COOKIE);
   $result = curl_exec($ch);
   curl_close($ch);
   return preg_match('/'.$code.'/', $result);
?>
I hope once genericadmin is done with the new search stuff we can get some sort of SA API to use, that would be awesome.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

cannibustacap posted:

Nah I want to use the servers of HostMonster so that way I know what I am previewing is what will be shown online.

Do you know how to set it up?

Use Editplus and edit it directly on the server

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Treytor posted:

Could a PHP script be used to ping a server, and redirect to two different pages depending on whether the pinged server responds or not?

PEAR Ping

Redirect with this

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Treytor posted:

Thanks for this, but I am having problems getting PEAR to work with my web host, I think they may be blocking some functions required by PEAR to operate...

Email your host and ask them to fix this. If they don't, find a new web host.

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