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
bt_escm
Jan 10, 2001

functional posted:

If your tests are not time intensive, why not simply run all of them and then check at the end to see if one failed? This is what I usually do. Actually, I keep a stack of error messages and then check to see if it's non-empty.

php:
<?
$err=$array();
if(!$aValid) $err[]="a failed";
if(!$bValid) $err[]="b failed";
if(!$cValid) $err[]="c failed";

if(count($err)) echo "errors";
else echo "we're good";


?>
Alternatively, you can mimic a goto in PHP using this method: http://andy.wordpress.com/2007/06/20/dreaming-of-goto-in-php/

There are some function pointer things you can do, but to be honest it already looks like your situation is too complex for them, and it's a hassle in PHP anyway.

Congratulations, you're smarter than your programming language.

Another way to do this is to iterate over the post array in a loop and use a switch statement like this
php:
<?

$errors = array();
foreach($_POST as $key=>$value){

switch($key){


   case 'email':
     //fancy email validation code
   break;

   case 'ssn':
     //fancy ssn validator
   break;

   default:
     if(empty($value)){
       $errors[$key]=$key.' cannot be empty'; 
     }
   break;
}

}

if(empty($errors)){
   //process post

} else{

  //handle errors

}
?>

Adbot
ADBOT LOVES YOU

bt_escm
Jan 10, 2001

functional posted:

(I would prefer a string solution to this, or something built into the PHP library, and not some big package I have to install.)

I have a string which consists of potentially bad XML.

I have a tag <mytag> which may exist in the XML multiple times.

I want to return the text contained in first instance of <mytag>, or the empty string if it doesn't exist. So in the following instance:

php:
<?
<html>
<mytag>THIS_IS_THE_STRING</mytag>
<span>aaaaaa</span>
<html>
?>
I want to yank out the string "THIS_IS_THE_STRING"

Is there something that already does this or do I have to write it myself?

http://us.php.net/simplexml

bt_escm
Jan 10, 2001

fletcher posted:

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;
}
?>

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.

bt_escm
Jan 10, 2001

fletcher posted:

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?

The simplest way is to do it manually. Alternative you could use an ORM package.
What I done in the past is build an array of the column definitions like this
php:
<?
$props = array(

'username'=>array(
   'type'=>'varchar',
   'length'=>40,
   'required'=>1),
'email'=>array(
   'type'=>'varchar',
   'length'=>255,
   'required'=>0,
   'validator'=>'email'
)

);
?>
That way I've got the full definition and validation all in one place. Then whenever creating or changing anything I can just pass the new values in and they will be full validated based on any criteria I need.

Another thing I've done in the past is use a script that I call one time to generate the above listed array after I've designed my database. It saves a little time.

bt_escm fucked around with this message at 21:09 on Mar 28, 2008

bt_escm
Jan 10, 2001

Finite posted:

I'm writing some authentication code for something I'm mucking around with, while at the same time trying to improve my coding habits. With the example below, CheckPassword() throws an exception if the password is incorrect.

For readabilities sake, should CheckPassword() have a boolean return and form an if block around the rest of the code, even though it won't change anything?

php:
<?
public function SetPassword($oldPassword, $newPassword, $newPassword2)
{
    if ($newPassword != $newPassword2)
    {
        throw new PasswordMismatchException();
    }

    CheckPassword($this->name, $oldPassword);

    // Better?
    // if (CheckPassword($this->name, $oldPassword))
    // {
            
    $salt = CreateSalt();
    $password = CreateSaltedHash($newPassword, $salt);
            
    $sql = 'UPDATE        user
        SET            password = "' . DB::Escape($password) . '"
                    salt = "' . DB::Escape($salt) . '"
        WHERE        name = "' . DB::Escape($this->name) . '"';
                    
    return $this->db->Execute($sql);

    // }
    // return false;
}
?>

What you want to use is a try/catch around the the code after the newPassword to newPassword2 check.

Also your example seems really strange since you are mixing oop and procedural function calls.

bt_escm
Jan 10, 2001
I still think a try catch would be better here because it could tell you why it failed, but after reading over your example some more the if statement would be fine.

I think this would work a lot better for you for logging purposes
php:
<?
try{

$this->CheckPassword($this->name, $oldPassword);

            
    $salt = self::CreateSalt();
    $password = self::CreateSaltedHash($newPassword, $salt);
            
    $sql = 'UPDATE        user
        SET            password = "' . DB::Escape($password) . '"
                    salt = "' . DB::Escape($salt) . '"
        WHERE        name = "' . DB::Escape($this->name) . '"';
                    
    return $this->db->Execute($sql);

} catch(SPECIFIC EXCEPTION $e) {


} catch(Exception $e){


}
?>

bt_escm
Jan 10, 2001

Treytor posted:

I have since upgrade to PHP 5 and it seems my method of querying a server via a predefined URL no longer works:
code:
copy($url, '/dev/null');
How should this be done, now?

check you fopen wrapper settings. also
http://us3.php.net/manual/en/function.stream-context-create.php

bt_escm
Jan 10, 2001

OlSpazzy posted:

Does anyone see a reason why the "show news comments" section of this code is only displaying the newest comment for each post?

$comments_list_commentbit is being called from within the template for "news_newsbit_commentslink". Note that some classes and variables may not appear to be defined as this is only a portion of the script.

php:
<?
code
?>

I looks like you are assigning $comments_list_commentbit each time. I think you want to use .= instead of =

Also I see no reason to use eval here or anywhere else in your code and it's really just a style and readability thing, but never use select * from table, even when you want to select everything from the table. List out the columns. It will save your sanity in the future.

bt_escm
Jan 10, 2001
I honestly don't know where to begin with this.

To fix the append issues try adding $comments_list_commentbit='' in between the number of rows check and the while loop.


Don't use eval.

bt_escm fucked around with this message at 20:18 on Apr 4, 2008

bt_escm
Jan 10, 2001

Zorilla posted:

So would there be anything wrong with sanitizing as late as the MySQL query string? Right now, I'm getting away with processing form inputs with their original $_POST superglobals, then using htmlspecialchars() at the query function argument to keep form inputs from doing anything too powerful, though I don't know if that would leave you wide open on older, less secure versions of PHP.

htmlspecialchars() won't stop sql injection. You'll need to you mysql_real_escape_string() to properly clean the string for inserting into the database.

bt_escm
Jan 10, 2001

fletcher posted:

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?

Since you already know PHP, writing it PHP would make the most sense. I really don't think it would matter what you write it in.

bt_escm
Jan 10, 2001

Zorilla posted:

I've got a client we're doing a web page redesign for and it turns out he would like to be able to edit basically anything that might need changing on the site on his own. Normally, I would just set up some system like Website Baker or CMS Made Simple, but this site in particular has quite a bit of markup I don't want the client to disturb. Plus, the site has some dynamic content with a backend I wrote a month or so ago to edit its contents.

I'm pretty sure cmsms has a user management system in it that you can use to prevent users from editing certain pages and content blocks. Actually I think most content management systems have that now. You could take a look at http://www.opensourcecms.com/ and look over some of the more popular ones.

bt_escm
Jan 10, 2001

the talent deficit posted:

Is this the right place for Zend questions? I hope so.

I've got an IndexController with four actions. indexAction works fine, the other three give me 404 errors. (I have views setup for all four). Is this because mod_rewrite isn't setup properly? Or my .htaccess is badly written?

It's one of two things
1) mod_rewrite is not enabled
2) your htaccess file is messed up

If it was setup correctly then all requests should be going to the index.php file in the webroot. The framework handles all requests form there.

bt_escm
Jan 10, 2001

drcru posted:

e: php4

I've got a $variable filled with a large amount of text separated by new lines (\n).

I want to split the $variable into two giant chunks after a certain amount of lines, is that possible?

I thought about using split() but that would just make a new array value for every sentence and that might not be an effective way of doing it.

Thanks

You could use strpos to find the nth line break and then substr to grab the first and then second half of the string. I'm sure there's a way to do this with regular expressions too.

bt_escm
Jan 10, 2001

TheHeadSage posted:

I'm writing another small PHP script to amuse myself, and this time I'd like to move away from having SQL sitting in my code. Are there any articles on how to go about this? I'm not looking for a full blown framework as that's just overkill for this but a simple DB class or something would be nice.

Frameworks are a few projects down the track...

Here's an ORM http://propel.phpdb.org/trac/
And here's a tutorial http://codepoets.co.uk/propel_php5_framework_quickstart_howto_guide

bt_escm
Jan 10, 2001

fletcher posted:

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

They're not mutually exclusive. This explains it way better than I could http://en.wikipedia.org/wiki/Object-relational_mapping

bt_escm
Jan 10, 2001

TheHeadSage posted:

I already know SQL. I'd like to move away from having SQL statements littered all throughout my projects where it's hard coded in. Which leads to maintaining multiple versions because my home system runs MySQL and my sever runs PostgreSQL and for added fun a friend uses my scripts and he's got Oracle.

So, it's getting to the point where I need database abstraction.

I'll have a look at this ORM stuff.

What do you mean by hard coded? Technically if you have sql anywhere in your code it could be considered hard coded since sql is frequently tied to the specific database server you are using. If you just want to be able to execute sql statements using the same set of commands across multiple script regardless of the database then pear's mdb2 would be better suited for that.

If you want code to dynamically know the structure of your tables and handle all of the basic manipulations for you then propel would be ideal for that.

bt_escm
Jan 10, 2001

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!

Zend_Mail has a really nice way of doing this http://framework.zend.com/manual/en/zend.mail.read.html

bt_escm
Jan 10, 2001

MrEnigma posted:

Is there any extension/package that will do form creation, and then auto detect if the form values were tampered with (ie with firebug or rewriting the page).

I know .NET has something either built in or available, but was wondering besides rolling your own, if there was anything people use with PHP.

I know there is Filter, but that only validates inputs.

There's Zend_Form that does both form creation and validation. I'm pretty sure it won't autodetect tampering. There's also something in the PEAR libraries, but it doesn't do tampering either. I'm pretty sure you're going to have to write your own for that.

bt_escm
Jan 10, 2001

fletcher posted:

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?

I get the database connection from within the static function.

bt_escm
Jan 10, 2001

Grigori Rasputin posted:


As far as the user authentication/session system, my intuitive approach seems a little clunky. Basically, I have a header.php and footer.php included to fill out the bulk of the base HTML between pages. I have a check inside header.php that checks to see if a user has logged in and if there is a valid session. If there is, the user proceeds as normal, if not then the user is redirected to my login page and told they need to login to perform that action. I know that there are probably a million ways to do this, but my solution doesn't seem quite optimal. What kind of strategies have other people adopted for user sessions after authenticating?

Quick bonus question: how do you set a session to expire after x minutes of inactivity?

Your authentication scheme is fine for a basic site. I'm assuming you have a collection of php pages that contain the layout and any processing logic in them. Doing that is fine for a smaller site or a site that doesn't really do anything. If you goal is to try and build something more complicated than a site with bunch of content and a few contact forms, then I recommend looking into a framework.

To force the sessions to time out set session.gc_maxlifetime in your php.ini to however many seconds you want before the session file is erased. If you are on a shared host then you may need to use ini_set('session.gc_maxlifetime',#seconds) before you call session start or set it in a .htaccess file for your whole site.

bt_escm
Jan 10, 2001

MonkeyMaker posted:

I'm trying to use the PHP-native result from the Flickr API and I have everything working well enough except when I try to display results from more than one photoset on the same page. It returns the same images for all photoset calls. Any ideas?

Here's my code on pastie: http://pastie.caboo.se/202515

change line 60 to
php:
<?
$rsp = hitFlickr('',$photoset);
?>
Also you can change lines 17 - 23 to just this
php:
<?
$url = "http://api.flickr.com/services/rest/?".http_build_query($params);
?>

bt_escm
Jan 10, 2001

nbv4 posted:

I have a PHP array with each item being an airport identifier. "KBOS", "KTEB", "KMIA", "MMIO", etc. These are wordwide airports, not just US airports. I want to get the longitude/latitude coordinates of each item. It's a long shot, but is there a tool that already does such a thing? I can probably swing together a function that crawls some other page for the info, but I don't want to waste my time if something already exists.

Once I get the longitude/latitude coordinates, I want to map them all on a map with lines connecting some of them. Whats a good tool for doing this? Would the Google Maps API be the only way to achieve this? I'd rather have it be a static image that can be saved.

I found this http://www.webservicex.com/airport.asmx and I was able to get a couple of coordinates for a few airports.

I think google maps would be ideal for this.

bt_escm
Jan 10, 2001

magicalblender posted:

How about something like this:
code:
$hyphenatedstring = substr($string,0,3) . "-" . substr($string, 3,3) . "-" . substr($string,6,4);
edit: whoops, forgot my $s and ;s

This would be so much better as a regular expression
php:
<?
$phone = '2145551212';
$formattedString = preg_replace('/(\d{3})(\d{3})(\d{4})/','$1-$2-$3',$phone);
?>

bt_escm
Jan 10, 2001

Evil Angry Cat posted:

Although I think considering the user is so new to php that he thought splitting a string required some sort of loop, substr() is a better method than reg exps.

Perhaps, but at least now they've seen two ways to do it, and have been given some exposure to a valuable tool.

bt_escm fucked around with this message at 15:51 on May 26, 2008

bt_escm
Jan 10, 2001

Grigori Rasputin posted:

When you say framework, would something like PEAR's Auth be adequate?

Yes, pear_auth would be fine. By framework I was talking about a framework like the zend framework, cake or syphony or any of the other dozen or so php frameworks.

bt_escm
Jan 10, 2001

MrEnigma posted:

PDFLib is the one you want, it's not easy at all to do things though...well anything besides just a block of text.

http://pecl.php.net/package/pdflib

It's free for non-commercial use (or at least there is a free alternative for non-commercial use).

Edit: Also check out http://us3.php.net/manual/en/book.pdf.php (and the comments).

take a look at http://www.digitaljunkies.ca/dompdf/

It will convert html + css2.1 to a pdf document and is a crap load easier than directly using PDFLib.

bt_escm
Jan 10, 2001

iamstinky posted:

I am trying to implement a reversible sort a 2d array by an arbitrary key in the second level function.

So I used an insertion sort (or it's based on an insertion sort rather):


Is there a better way to do this if I need to be able to sort on class or person_id etc? $array size won't ever be more than a couple thousand elements.

I have to question where you're getting the data from that you would need to sort it in php?

bt_escm
Jan 10, 2001

willjo3 posted:

I'm having a problem using the php mail() function. I've been googling and experimenting for two days trying to figure it out to no avail.

Basically, I'm unable to send an email using the mail() function. The interesting part is that our company website (which we bought from a third party) uses the function and it works just fine. To make matters even more fun, my code works on another webserver. I've checked the php.ini sections on mail, and there dont seem to be any relevant differences.

Here is the relevant part of the company website that works:
code:
while(list($SID, $Email) = mysql_fetch_array($sql2)) {
				$unsubscribe_link = "<a href='$siteurl/obituaries.php?op=unsubscribe&Email=$Email'>here</a>";
				if(ereg("\[Unsubscribe_Link\]", $mailbody)) $mailbody = ereg_replace("\[Unsubscribe_Link\]", $unsubscribe_link, $mailbody);
					if((@mail($Email, $subject, $mailbody, $mailheader))) {
						//echo "<font color=green>Emailed to $Email</font><br>";
					} else {
						//echo "<font color=red>Email failed to $Email</font><br>";
					}
				}
			}
Any suggestions?

what is the value of $mailheader in the original script?

bt_escm
Jan 10, 2001

Treytor posted:

I have a file upload script based on this - http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2293&lngWId=8

but I need it to remove spaces in the file names before it uploads it to the server. How would this be done?

To just remove spaces use this
php:
<?

   $string = str_replace(' ','',$string);

?>
regex is kind of a waste when you know exactly what you want to remove.

However if you are looking to make the filename safe for your file system then you should use a regular expression to replace any non-aplhanumeric characters like this
php:
<?

$string = preg_replace('/[^A-Za-z0-9\\.\\-_]/','',$string);
?>
This will remove anything that isn't a-z,0-9, a period,a dash or an underscore.

bt_escm fucked around with this message at 22:26 on Jun 17, 2008

bt_escm
Jan 10, 2001

iamstinky posted:

It is a combination of physical file data and stuff from db, sortable by the user as needed. As some of it isn't db related I can't let the DB sort the data for me. But if you have any suggestions, feel free to offer them.

Ok, the solution posted earlier will work. It's just unusual to have to sort a large block of data in php like that.

bt_escm
Jan 10, 2001

passionate dongs posted:

Really dumb question:

I'm outputting the results of a mysql query into a page and loading it into a javascript array. Right now it is essentially like this:

code:
var myArray = [ 
<? while(mysql results) {
  echo("{name: $result},");
} ?>
];
problem is, that there is always one stray comma at the end of the last entry into the array, which makes sense. Outside of writing some really bad code, I am fairly certain there has to be an easy way to output "a, b, c, d, e" instead of "a, b, c, d, e, "

The code works in IE/Firefox/Safari, but of course it produces javascript errors. What is an easy way to say "on the last record truncate the comma" ?

put the resultset into an array and then have a look at http://www.php.net/json_encode

bt_escm
Jan 10, 2001

Dirk Pitt posted:

I need to find a library that allows for the creation of php to pdf on the fly. So far I have found fpdf.org and tcpdf.org to be the best, does anyone have any experience with either library? The built-in pdf support in php5 is not good enough for what i need to create. thanks!

domPDF will take an html page formatted with css2.1 and convert it to a pdf. It's really nice and it's free.

http://www.digitaljunkies.ca/dompdf/

bt_escm
Jan 10, 2001

Stephen posted:

Yeah, this is what I thought, but I was still hoping there was a workaround. Unfortunately sessions won't work because I'm not redirecting to an internal page. Basically I'm using a grossly insecure 3rd party web app that accepts confidential information via POST. My solution was to use an internal database as a proxy to accept a coded value, and then query a database with a list of the confidential values and redirect to the 3rd party site with those values in a POST header.
While this solution is also vulnerable, it's 100x more secure than using hidden form inputs to pass information and since I can't use an alternative to the lovely 3rd party app, it was the best I could come up with.

It seems like you could use curl to take the original form on your site and then resubmit to the other server, capture the results and spit them back to the user. You may need to parse all of the src and href in the result html to the full url, but that's pretty easy.

This can also be done without curl depending on the version of php you're using. The code for that is
php:
<?
function do_post_request($url, $data, $optional_headers = null)
  {
     $params = array('http' => array(
                  'method' => 'POST',
               'content' => $data
               ));
     if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
     }
     $ctx = stream_context_create($params);
     $fp = fopen($url, 'rb', false, $ctx);
     if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
     }
     $response = stream_get_contents($fp);
     if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
     }
     return $response;

  }

//call
$post = http_build_query($_POST);

   
try{
 
$response = do_post_request('http://www.XXX.com/form.html',$post);

echo $response;

} catch(Exception $e) {

 die($e->getMessage());
}
?>

bt_escm fucked around with this message at 21:08 on Aug 7, 2008

bt_escm
Jan 10, 2001

iamstinky posted:

php:
<?
$_SESSION['current_vendor'] or $_SESSION['current_vendor']    = $r[2];
?>
Can someone explain to me what the person who wrote this might have thought they were doing? I mean it makes me feel like a billion of my brain cells just committed suicide every time I try to figure what he was doing here. For what it's worth $r[2] is part of a result set that should contain the vendor information.

:saddowns:

if $_SESSION['cuerrent_vendor'] doesn't have a value or is equal to '' or 0, set $_SESSION['current_vendor'] to the value of $r[2]?

bt_escm
Jan 10, 2001
change all the
php:
<?
echo $row;
?>
to
php:
<?
echo $row['URl']
?>

bt_escm
Jan 10, 2001

Emo Businessman posted:

I'm having tons of issues with CakePHP. It seems like if you ever venture out of the realms that tutorials and the inadequate manual covers, it has a 'right' way to do things, but good luck finding the 'right way' that fits what you're trying to accomplish, and trying to figure out that 'right way' involves a ton of source diving and refactoring of code you've already written to something 'acceptable' that you hope to god you can fix later on down the line. I find myself blindly following tutorials almost to the letter, and trying to do something 'clever' or apply anything I've learned in a Cake tutorial or manual to something else always seems to get me in trouble.

Are there frameworks out there that allow a little more flexibility, or is this sort of thing indicative of all of the frameworks out there?

I think the Zend Framework (http://framework.zend.com/) is all kinds of awesome.

Adbot
ADBOT LOVES YOU

bt_escm
Jan 10, 2001

gibbed posted:

php:
<?php
    $files = array();
    $paths = array(realpath('.'));

//I don't understand why you have this while statement.  Won't realpath('.'); always resolve to a single pathname?

///Yes, what's happening here is that, as the inner loop runs,
///it will add more paths to the $paths array. The first loop will always 
///happen of course, because I put a starting element in the 
///array (realpath('.'))
    while (count($paths) > 0)
    {
        $path array_shift($paths);

//Here you are taking the current directory, and searching for any subfolders (I think)
//Now I start to get lost.  I think I'm too tired, and I've been trying to figure out too many things at once today.  What exactly is the statement $paths[] = $dir doing?

///This was dumb code on my behalf, I should have just used array_merge. What I'm doing is adding
///found subdirectories to the paths array, so the while loop will search them too, this results
///in every subdirectory from the top directory is searched for files.
///
///The original code, $paths[] = $dir. '$var[] = $thing' is basically syntax magic for array_push($var, $thing).
        $paths array_merge($pathsglob($path '/*'GLOB_ONLYDIR));

//Can you break down what this merge is doing also?
///It's adding all found .jpg/.gif/.png files to the files array (array_merge combines two or more arrays into a single array)
        $files array_merge($filesglob($path '/{*.jpg,*.gif,*.png}'GLOB_BRACE));
    }
    
    var_dump($files);
?>



If you are using php5, then please use the spl directoryIterator (http://www.phpro.org/tutorials/Introduction-to-SPL-DirectoryIterator.html).

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