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
A loop?

php:
<?
for ($i=0;$i<sizeof($node->field_images);$i++) {
    if ($node->field_images[$i]['view'] > '') //the hell does this line even mean?
         print $node->field_images[$i]['view'];
}
?>

fletcher fucked around with this message at 19:56 on Apr 21, 2009

Adbot
ADBOT LOVES YOU

Roctor
Aug 23, 2005

The doctor of rock.

milieu posted:

OK, I've got a retard simple php question, I'm sure. But here it goes anyway

I have a huge list of IF->Then type statements in a page template. The reason is I have no idea how many items need to be displayed...could be anywhere from 0 - 200.

So what I'm doing now is putting a huge list like this:

code:
<?php if ($node->field_images[0]['view'] > '') : ?><?php print $node->field_images[0]['view'] ?><?php endif; ?> 
<?php if ($node->field_images[1]['view'] > '') : ?><?php print $node->field_images[1]['view'] ?><?php endif; ?>
...etc. on to 200
Now this is horrible for performance but I don't know any other way to do it. Is there a better way?

you're just incrementing the array index, right? This is why loops exist.

php:
<?php
foreach($node->field_images as $field_image){
   if($field_images['view'] > ''){
      print $field_image['view'];
   }
}
?>

e: beaten

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Note that putting that in a loop won't really increase performance - but performance should be fine up until a couple thousand entries in the array.

Also, why are you doing a greater than comparison to an empty string? I think are probably looking for something like if(!empty($node->field_images[$i])).

milieu
Apr 26, 2003
Vizier of Allah

fletcher posted:

A loop?

php:
<?
for ($i=0;$i<sizeof($node->field_images);$i++) {
    if ($node->field_images[$i]['view'] > '') //the hell does this line even mean?
         print $node->field_images[$i]['view'];
}
?>

Sweet! That works perfectly, thanks! I have no idea what the line you commented is for, I copied it from somewhere else. It works though so whatever!

MononcQc
May 29, 2007

milieu posted:

Sweet! That works perfectly, thanks! I have no idea what the line you commented is for, I copied it from somewhere else. It works though so whatever!

The original dev most likely tried to see if the text was longer than en empty string (0 character).

This is not a really nice way to do it. There are many more ways to test this nicely:

php:
<?
if ($node->field_images[$i]['view'] !== '')  // cleaner and stricter
if (!empty($node->field_images[$i]['view'])) // shows what you mean better than > ''
if ($node->field_images[$i]['view'])         // overall cleanest IMO
?>
The last one is the cleanest one. That's because PHP will evaluate an empty string,0,false, an empty array and something that is NULL to FALSE and anything else to TRUE. This means if there's content in your entry, it will show it.

I suggest you go to php.net and read the documentation there. It's concise, won't show too much to stop you from 'getting things done', and while PHP's certainly not the best you could do to learn, it'll at least be better than copy/pasting stuff at random hoping it works.

EDIT: also note that 'print' is rather rarely used. read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40 for the difference with 'echo'

MononcQc fucked around with this message at 20:16 on Apr 21, 2009

milieu
Apr 26, 2003
Vizier of Allah

MononcQc posted:

The original dev most likely tried to see if the text was longer than en empty string (0 character).

This is not a really nice way to do it. There are many more ways to test this nicely:

php:
<?
if ($node->field_images[$i]['view'] !== '')  // cleaner and stricter
if (!empty($node->field_images[$i]['view'])) // shows what you mean better than > ''
if ($node->field_images[$i]['view'])         // overall cleanest IMO
?>
The last one is the cleanest one. That's because PHP will evaluate an empty string,0,false, an empty array and something that is NULL to FALSE and anything else to TRUE. This means if there's content in your entry, it will show it.

I suggest you go to php.net and read the documentation there. It's concise, won't show too much to stop you from 'getting things done', and while PHP's certainly not the best you could do to learn, it'll at least be better than copy/pasting stuff at random hoping it works.

EDIT: also note that 'print' is rather rarely used. read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40 for the difference with 'echo'


Thanks a lot for taking the time to write this up. I'm checking out the link right now and have changed the code to the
code:
if ($node->field_images[$i]['view'])
method. I'm just happy to have a stream of code three lines long rather than hundreds and hundreds of lines long!

KuruMonkey
Jul 23, 2004
A couple of piffling tweaks: but, once we've moved to setting up a loop, and we're wondering why we're using less than on a string, we should be moving from:

php:
<?
for ($i=0;$i<sizeof($node->field_images);$i++) {
    if ($node->field_images[$i]['view'] > '') //the hell does this line even mean?
         print $node->field_images[$i]['view'];
}
?>
through:
php:
<?
$limit = count($node->field_images);
for($i=0; $i<$limit; $i++)
{
  if($node->field_images[$i]['view'])
  {
    echo $node->field_images[$i]['view'];
  }
}
?>
The point there being that unless we have a good reason to suspect the array changes during the loop, its inefficient to retest its length each iteration.

and moving towards:

php:
<?
foreach($node->field_images as $image)
{
  echo $image['view']; 
}
?>
making use of these two facts; an empty array triggers no iterations in a foreach loop, and echo ''; causes no output...

still use a test if you need to echo the view AND append something ("\n" or "<br />" or something)

Also; as someone mentioned above, writing each variation out seperately is actually the 'optimised' version; it has no overhead of an iterating value, no repeated boundary check. Unwinding a loop is not that unusual as a simple optimisation.

Vedder
Jun 20, 2006

Got a bit of a weird on here. I have a newsletter to do and normally it has around 5 articles, each on in a seperate coloured div. I have found a tutorial which tells you how to make alternate coloured table rows and I have adapted this and it works fine with two colours, however I have 4. The code looks like this:

code:
$grey = 'grey';
$blue = 'blue';
$yellow = 'yellow';
$green = 'green';

$count = 0;


while ($row = mysql_fetch_array($news))
{
$count++;
$colour = ($count % 2) ? $grey : $blue;

echo '<p>$colour</p>';
If I change the line of code from

code:
$colour = ($count % 2) ? $grey : $blue;

to

$colour = ($count % 4) ? $grey : $blue : $yellow : $green;
My IDE has a fit and tells me its a syntax error. I have also tried setting up an array of colours and doing a for each loop but that just creates the number in the array (the 4 colours) matching the articles in the database (so it will display 4 article 1's, 4 article 2's, 4 article 3's etc).

It's normally dead simple when I am involved so no doubt you will spot whats going wrong straight away.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Vedder posted:

Got a bit of a weird on here. I have a newsletter to do and normally it has around 5 articles, each on in a seperate coloured div. I have found a tutorial which tells you how to make alternate coloured table rows and I have adapted this and it works fine with two colours, however I have 4. The code looks like this:

code:
$grey = 'grey';
$blue = 'blue';
$yellow = 'yellow';
$green = 'green';

$count = 0;


while ($row = mysql_fetch_array($news))
{
$count++;
$colour = ($count % 2) ? $grey : $blue;

echo '<p>$colour</p>';
If I change the line of code from

code:
$colour = ($count % 2) ? $grey : $blue;

to

$colour = ($count % 4) ? $grey : $blue : $yellow : $green;
My IDE has a fit and tells me its a syntax error. I have also tried setting up an array of colours and doing a for each loop but that just creates the number in the array (the 4 colours) matching the articles in the database (so it will display 4 article 1's, 4 article 2's, 4 article 3's etc).

It's normally dead simple when I am involved so no doubt you will spot whats going wrong straight away.

You are using the operator horribly wrong. The () ? : ; means "If what is in the parenthesis is true, do the thing after the question mark, if not, do the thing on the other side of the colon"

You can't just add more colons :)

You want to do something like:

php:
<?
$count = 0;
$colors = array('grey','blue','yellow','green');
while ($row = mysql_fetch_array($news))
{
  $count++;
  echo "<p>{$colors[$count % 4]}</p>";
}
?>
EDIT: link to ternary operator page: http://us2.php.net/ternary

Lumpy fucked around with this message at 16:12 on Apr 22, 2009

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Thank you for your post, I welcomed the laugh that resulted. :)

code:
$colours = array();

$colours[] = 'grey';
$colours[] = 'blue';
$colours[] = 'yellow';
$colours[] = 'green';


$len = len($colors);
while ($row = mysql_fetch_array($news))
{
    $count++;
    $colour = $colours[$count % $len];
    
    echo '<p>$colour</p>';
}
edit: mine's better. :mad:

Vedder
Jun 20, 2006

Thanks for that, and I hope you enjoyed the laugh (I'm a right newbie at this PHP stuff).

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mercator posted:

Thank you for your post, I welcomed the laugh that resulted. :)

code:
$colours = array();

$colours[] = 'grey';
$colours[] = 'blue';
$colours[] = 'yellow';
$colours[] = 'green';


$len = len($colors);
while ($row = mysql_fetch_array($news))
{
    $count++;
    $colour = $colours[$count % $len];
    
    echo '<p>$colour</p>';
}
edit: mine's better. :mad:
Yes, but leaving off the count() made my post first! Muahahahaha....


Why do you have the same avatar as Yodzilla? Every time I see one of your posts, I get all confused :)

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

Lumpy posted:

Why do you have the same avatar as Yodzilla? Every time I see one of your posts, I get all confused :)

We loving love The Woz.

Aredna
Mar 17, 2007
Nap Ghost
This is probably just going to show how bad I am at google today...

Where can I find a regex that will check if a string is a valid regex for use with preg_match?

e: To give some more context, I'm validating data in an array and rather than rewrite the code several dozen times to check, I created a function. I need to validate both the key and value are either an exact value or they match a certain regex, but it will vary by what I'm expecting to see for that row in the array so I could have any combination of regex/plain text for the key and value. Rather than creating 4 functions to handle each situation or making the plain text checks into regex, I want to check if the string is a valid $pattern for preg_match and then use either that or an equality check.

I was going to just check for starting and ending with a slash, but that failed as soon as I wanted a case-insensitive check so I realized someone has to have written this before so I should just find and use theirs rather than trying to write one myself that is all inclusive.

e2: Also, the database this reads from will have some custom regexs for input validation, and I'll need to validate them before use.

Aredna fucked around with this message at 00:54 on Apr 25, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Aredna posted:

This is probably just going to show how bad I am at google today...

Where can I find a regex that will check if a string is a valid regex for use with preg_match?

e: To give some more context, I'm validating data in an array and rather than rewrite the code several dozen times to check, I created a function. I need to validate both the key and value are either an exact value or they match a certain regex, but it will vary by what I'm expecting to see for that row in the array so I could have any combination of regex/plain text for the key and value. Rather than creating 4 functions to handle each situation or making the plain text checks into regex, I want to check if the string is a valid $pattern for preg_match and then use either that or an equality check.

I was going to just check for starting and ending with a slash, but that failed as soon as I wanted a case-insensitive check so I realized someone has to have written this before so I should just find and use theirs rather than trying to write one myself that is all inclusive.

Here I thought I was the only one perverse enough to think of writing a regex to validate regexes. I gave up after a bit (checking for matching brackets is really hard). The cheap-rear end PHP way to do it might be something like:
code:
$test=@preg_match($maybe_valid_regex,"some string or other");
if(!$test===false){// preg_match returns false, 0, or 1
  //invalid regex 
}else{
  //valid
}
... or something with a try - catch, maybe.

or, maybe you can get away with just
code:
preg_match('/^\/.*\/[imsux...]?$/', $maybe_regex)
if you can trust that if it looks like a regex, then it's a valid regex ("imsux" would be the valid pattern modifiers you want to use).

Aredna
Mar 17, 2007
Nap Ghost

FeloniousDrunk posted:

Here I thought I was the only one perverse enough to think of writing a regex to validate regexes. I gave up after a bit (checking for matching brackets is really hard).
Yeah, that hadn't crossed my mind. I haven't done any research, but a friend taking a programming languages class was telling me recently that his teacher said that it's impossible for a regex to validate nested matching brackets.

quote:

The cheap-rear end PHP way to do it might be something like:
code:
$test=@preg_match($maybe_valid_regex,"some string or other");
if(!$test===false){// preg_match returns false, 0, or 1
  //invalid regex 
}else{
  //valid
}
... or something with a try - catch, maybe.

or, maybe you can get away with just
code:
preg_match('/^\/.*\/[imsux...]?$/', $maybe_regex)
if you can trust that if it looks like a regex, then it's a valid regex ("imsux" would be the valid pattern modifiers you want to use).

Thanks, I'm gonna give the try-catch a go. It seems ugly, but preg_match throws an error when it receives an invalid regex and I can't be sure of what regex pattern someone will try or want to use in the future.

Supervillin
Feb 6, 2005

Pillbug

Aredna posted:

I was going to just check for starting and ending with a slash, but that failed as soon as I wanted a case-insensitive check

Since you were fine with testing for slashes, then here's one that does that but allows the case-insensitive modifier and the other regex modifiers:

code:
$isCheapoRegex = preg_match('#^/.*/([imsxeADSUXJu])?$#', $input);
Tested with a couple right and couple wrong inputs, but obviously it's not guaranteed to work for 100% of cases.

Edit: Oops, that's almost the same as what was posted above. Consider this agreement, then.

Supervillin fucked around with this message at 07:19 on Apr 25, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
For the sake of the discussion here's the BNF grammar for Perl style regular expressions: http://www.cs.sfu.ca/~cameron/Teaching/384/99-3/regexp-plg.html. Using this it shouldn't be too difficult to put together a regex (although rather tedious).

spiritual bypass
Feb 19, 2008

Grimey Drawer
Any time I'm writing a regex, I test it in my browser first. This thing is pretty slick.
http://regexpal.com/

Mine GO BOOM
Apr 18, 2002
If it isn't broken, fix it till it is.

royallthefourth posted:

Any time I'm writing a regex, I test it in my browser first. This thing is pretty slick.
http://regexpal.com/
I use http://rexv.org/, less letters to type.

aslewofmice
Dec 22, 2003
I'm trying to hack together a crude script to force people to enter their Name, Phone Number, Email in order to download a PDF file from our company website. Upon completion of the form and pushing the submit button, I'd like to have a "save as" dialog box popup for the PDF. I've read up on how to do this by editing the headers, but it refuses to work for me. Can anyone tell me what I might be missing?

*Forgot a couple things
- the script works, in that it will download the correct file. The problem is that it displays the PDF in-browser when in fact I want to force it to a "save as" dialog.
- Where it says: "header("Content-type: application/octet-stream");", I've also tried "application/force-download" and a couple others to no avail.

download.php
code:
<?php
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Email = $_POST['Email'];
$PhoneNumber = $_POST['PhoneNumber'];
$Company = $_POST['Company'];
$ID = $_POST['propid'];
$Subscribe = $_POST['Subscribe'];
$Date = date("Y/m/d");

$link = mysql_connect('localhost', 'user', 'pass');

/* Inserts user info */	
mysql_select_db("database", $link) or die("Could not connect");
mysql_query("INSERT INTO user_temp (firstName, lastName, email, phoneNumber, company, id, subscribe, date)
VALUES ('$FirstName', '$LastName', '$Email', '$PhoneNumber', '$Company', '$ID', '$Subscribe', '$Date')") or die('Error: '.mysql_error());

/*Provides download */
$query = mysql_query("SELECT packageLink FROM properties WHERE propertyid = $ID");
$filename = mysql_result($query,0);
header("Location: /packages/".$filename);
header("Content-disposition: attachment; filename=".$filename);
header("Content-type: application/octet-stream");
header("Content-Length: ".filesize($file));
readfile($file);


mysql_close($link);

?>
the above "download.php" obtains it's variables from:
form.php
code:
<html>
<head></head>
<body>
<h2>Request A Marketing Package for: </h2>

<?php

    $id = $_GET['propid'];

    $link = mysql_connect('localhost', 'user', 'password') or die(mysql_error());

    mysql_select_db("database", $link);

    $query = mysql_query("SELECT name FROM properties WHERE propertyID = $id");

    echo mysql_result($query, 0);
?>


	<form id="form" action="download.php" method="post">
	<input id="" type="hidden" name ="propid" value="<?php echo $_GET['propid']; ?>">
	<ul>
		<li>
			<label>First Name</label><br>
			<input id="" type="text" name="FirstName">
		</li>
		<li>
			<label>Last Name</label><br>
			<input id="" type="text" name="LastName">
		</li>
		<li>
			<label>Company</label><br>
			<input id="" type="text" name="Company">
		</li>
		<li>
			<label>Email</label><br>
			<input id="" type="text" name="Email">
		</li>
		<li>
			<label>Phone Number</label><br>
			<input id="" type="text" name="PhoneNumber">
		</li>
		<li>
			<input type="checkbox" value="1" name="Subscribe" checked >
			<label>Keep me updated about future investments.</label>
		</li>
		<li>
			<input type="submit" value="Submit" name="submit">
			<a href="#" class="lbAction" rel="deactivate"><button>Cancel</button></a>
		</li>
	</ul>
	</form>
</body>
</html>

aslewofmice fucked around with this message at 00:58 on Apr 28, 2009

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

ABombInABowl posted:

code:
header("Location: /packages/".$filename);
header("Content-disposition: attachment; filename=".$filename);

I think that Location: might be just sending you directly to a nonexistent file, try taking it out. Also, because this bit me once, it's best to put the filename in quotes in that Content-disposition, i.e.
code:
header('Content-disposition: attachment; filename="'.$filename.'"');

aslewofmice
Dec 22, 2003

FeloniousDrunk posted:

I think that Location: might be just sending you directly to a nonexistent file, try taking it out. Also, because this bit me once, it's best to put the filename in quotes in that Content-disposition, i.e.
code:
header('Content-disposition: attachment; filename="'.$filename.'"');

The script actually finds the files fine (although it may be an ugly hack). The problem is that it downloads to view in-browser and refuses to show a "save as" dialog box.

I just tried your suggestion and nothing changed. :/

indulgenthipster
Mar 16, 2004
Make that a pour over
Right now I'm pulling a large amount of items from the database and displaying them on the page. What I intend to do is make this more efficient, as the items towards the top will be the most accessed.

Is pagination the way to go? From what I'm reading it will first need to perform a count to figure out how many total pages there will be, then order and pull out the first set of results. Is this the only way to do it, or are there better and more optimized ways?


edit: What about having a separate "count" table that adds every time an item is added. Then it would just be a matter of dividing from that number to figure out how many pages are required. If there are still better solutions out there, please let me know!

indulgenthipster fucked around with this message at 04:34 on Apr 28, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

VerySolidSnake posted:

Right now I'm pulling a large amount of items from the database and displaying them on the page. What I intend to do is make this more efficient, as the items towards the top will be the most accessed.

Is pagination the way to go? From what I'm reading it will first need to perform a count to figure out how many total pages there will be, then order and pull out the first set of results. Is this the only way to do it, or are there better and more optimized ways?


edit: What about having a separate "count" table that adds every time an item is added. Then it would just be a matter of dividing from that number to figure out how many pages are required. If there are still better solutions out there, please let me know!

You don't need to keep a separate table to keep count, just use count(*) (i.e., select count(*) from items) to get the total count and then use the ceil of that count divided by the number of items you want to display per page to get the total number of pages (i.e., ceil($countTotal / $countPerPage).

To get the the right rows for displaying use limit and offset (assuming you are using MySQL. limitwill return you only the number of rows you specify. So if you are on the first page and you want the first 10 rows you can query like so: select * from items limit 10. offset will shift the returned rows by the specified amount. So if you're on the second page and you want rows 10-19 you can query like so: select * from items limit 10 offset 10.

aksuur
Nov 9, 2003
I'm trying to follow this tutorial. After saving the code and changing what I need to, this is what I get on execution:

code:
Parse error: syntax error, unexpected T_STRING in /home/virtual/site293/fst/var/www/html/test/login.php on line 23
this is line 23:

code:
$result = @mysql_query('SELECT name, email FROM `users` WHERE username = \".mysql_real_escape_string($_POST['username']).'\" AND password = \".mysql_real_escape_string(md5($_POST['password'])).'\");
I remember why I hated making websites :(.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

aksuur posted:

I'm trying to follow this tutorial. After saving the code and changing what I need to, this is what I get on execution:

code:
Parse error: syntax error, unexpected T_STRING in /home/virtual/site293/fst/var/www/html/test/login.php on line 23
this is line 23:

code:
$result = @mysql_query('SELECT name, email FROM `users` WHERE username = \".mysql_real_escape_string($_POST['username']).'\" AND password = \".mysql_real_escape_string(md5($_POST['password'])).'\");
I remember why I hated making websites :(.

Don't use mysql_query, use something like PDO with prepared statements.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Check your quotes. You are missing a closing single quote before each mysql_real_escape_string() and one at the end of the string.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


ABombInABowl posted:

The script actually finds the files fine (although it may be an ugly hack). The problem is that it downloads to view in-browser and refuses to show a "save as" dialog box.

I just tried your suggestion and nothing changed. :/

Did you remove the Location header?

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

:dukedog:

What would be the best way to setup a bunch of obfuscated links like ?action=150jsZ that work only once and or expire after a few minutes?

I was thinking sessions but I want something more reliable. Maybe storing them onto MySQL or something but I don't want to eat up all my RAM.

Ideas?

Supervillin
Feb 6, 2005

Pillbug

drcru posted:

What would be the best way to setup a bunch of obfuscated links like ?action=150jsZ that work only once and or expire after a few minutes?

I was thinking sessions but I want something more reliable. Maybe storing them onto MySQL or something but I don't want to eat up all my RAM.

Ideas?

Base it on the current timestamp (or some hash of the time if you want it to be less obvious to the end user), then compare the time in your target script.

Edit: vvv Say your link is http://yoursite.com/phatpage.php?action=1240979192 (the number times from PHP's time()). When someone actually goes to that page, your script can do this:

php:
<?
   $link_age = time() - $_GET['action']; // how many seconds old the link is
   $max_age = 60 * 60 * 24 * 7;          // total seconds in one week
   $is_too_old = ($link_age > $max_age); // true if the link is more than one week old
?>
The hash thing was in case you care if someone recognizes 1240979192 as a timestamp and starts loving with the address, typing in other values for action or whatever. You'd need to be able to reverse whatever method used to encode it, then you can compare as above. For example:

php:
<?
    $str = time();              // for example, 1240976426
    $key = 9876543210;          // any number goes here, up to you
    $encoded = $str ^ key;      // XOR operator
    
    echo "$str : $encoded";     // 1240976426 : 88595136

    $decoded = $encoded ^ $key; // XOR again to decode
    echo "$str : $decoded";     // 1240976426 : 1240976426
?>

Supervillin fucked around with this message at 04:44 on Apr 29, 2009

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

:dukedog:

Supervillin posted:

Base it on the current timestamp (or some hash of the time if you want it to be less obvious to the end user), then compare the time in your target script.

How do I measure the differences in time for the hash?

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

drcru posted:

What would be the best way to setup a bunch of obfuscated links like ?action=150jsZ that work only once and or expire after a few minutes?

I was thinking sessions but I want something more reliable. Maybe storing them onto MySQL or something but I don't want to eat up all my RAM.

Ideas?

Store the nonce (in your example, the action value is a nonce) in a MySQL table with a timestamp and delete records older than you want to allow. Delete the nonce when it's requested.

Storing them in MySQL is the exact opposite of eating up all your RAM.

Edit: Sorry, "exact opposite" is an exaggeration. My point was that an RDBMS is supposed to be a scalable datastore, and you might as well take advantage of it for as much as you can, which is a long-rear end way.

DaTroof fucked around with this message at 02:27 on Apr 29, 2009

Sylink
Apr 17, 2004

This is halfway between a php and Jquery question so I'' try it here.

I have an index.php file like so:

code:
<?php
#files to include, will later link to only a master file listing all includes.
include('C:\wamp\www\config\classDB.php');
include('C:\wamp\www\config\databaseconfig.php');

$db = new dbLib();

#$db->get_dbinfo($dblocation,$dbuser,$dbpasswd);
#$db->connect();
#$db->select_DB("cookbook");

?>

<html> 
<head>
<title>CookBook</title>

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
	
<script type="text/javascript">
$(document).ready(function(){

		$("#login").click(function(){
		 var username = $("#username").val();
		 var password = $("#password").val();
		 alert("oval office");
		
		        
	
				$.post("serverTime.php", function(data){
						alert("oval office");
						
					
					
					});
			
		});
		
});

</script>

</head>
<body>
<div class="main" >

<?php

echo '<form id="loginform" method="post">Username: <input type="text" id="username" name="username" />';
echo '<br/>Password: <input id="password" type="password" name="userpass" /><br/><input id="login" type="submit" value="Login" /></form>';
?>


</div>
</body>
</html>
The key part is in the javascript where I use jquery/ajax to run a script. It does not work. I have no idea why but its related to the php somehow. If I rename the file index.html for example it works and the alert inside the post callback goes off. Of course that leaves all kinds of garbage php around but I was just testing. Jquery still works as index.php but the post function does not.

Any reason to this? I can only imagine its restricted name related or something, its very odd.

Zorilla
Mar 23, 2005

GOING APE SPIT

Sylink posted:

Any reason to this? I can only imagine its restricted name related or something, its very odd.

This question is probably 90% jQuery and 10% PHP. I think you might have your arguments set up wrong for jQuery.post()

php:
<?php
//files to include, will later link to only a master file listing all includes.
include('C:\wamp\www\config\classDB.php');
include('C:\wamp\www\config\databaseconfig.php');

$db = new dbLib();

/*$db->get_dbinfo($dblocation,$dbuser,$dbpasswd);
$db->connect();
$db->select_DB("cookbook");*/

?>
<html> 
<head>
<title>CookBook</title>

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    $("#login").click(function() {
        var login.username = $("#username").val();
        var login.password = $("#password").val();
        
        $.post("serverTime.php", login, function() {
                alert("oval office");
        });
        
        return false;
    });
});
//]]>
</script>
</head>
<body>
<div class="main">
    <form id="loginform" method="post">
        <label for="username">Username:</label> <input type="text" id="username" name="username" /><br />
        <label for="password">Password:</label> <input id="password" type="password" name="userpass" /><br />
        <input id="login" type="submit" value="Login" />
    </form>
</div>
</body>
</html>


A wild guess is that maybe jQuery.post() was sending postdata in a way that made serverTime.php toally screw up, but index.html wasn't (since it doesn't handle it at all).

Zorilla fucked around with this message at 23:05 on Apr 29, 2009

Sylink
Apr 17, 2004

I figured it out for other idiots in the same situation. By removing the form tags and the method="post" it now works. Apparently that submit button was tied to something else who knows but that was the conflict.

EDIT: So I guess the problem was I was posting twice perhaps? Weird poo poo happening then.

Zorilla
Mar 23, 2005

GOING APE SPIT

Sylink posted:

I figured it out for other idiots in the same situation. By removing the form tags and the method="post" it now works. Apparently that submit button was tied to something else who knows but that was the conflict.

EDIT: So I guess the problem was I was posting twice perhaps? Weird poo poo happening then.

Crap, I should have caught that one. You need to use return false; to keep the conventional action from also running if Javascript is bound to the same item. For instance:

code:
<!-- Simulating target="_blank" in strict doctypes -->
<a href="http://crap.com/stuff.html" onclick="window.open{this.href);return false;">Link</a>
If you removed return false;, it would open the link in a new window/tab and still follow it in the same window at the same time.

I edited my example to reflect this.

Zorilla fucked around with this message at 23:04 on Apr 29, 2009

sivo
Dec 2, 2003
Life is but a dream
I've been playing with Zend Framework for a while. I wrote a small project with it, simple CRUD interface and a generated PDF report etc. It was my first time working with MVC and at the end, I wasn't very happy with the internal structure of my program. Since then I have been reading (and reading and reading) and now I'm working on another project at the moment to learn how to "do it right" and get a better feel for it, but I can't help but run into various structural questions I just don't have the experience to pick from the various opinions on the matter:

Zend_Form. This class seems to "suffer" from the ZF use-at-will design in that it blurs together aspects of the view (decorators) and the model (validation logic) - I just have no idea where to stick my Zend_Forms.

At the moment I am leaning towards including the form data definition, what information and how to validate it in the Model, (and so the Model provides access to the Forms) and then writing a View Helper to render the form. This seems like the easiest way to maintain separation of concerns and that some people feel this is the way to go but I also saw another website describe including the Forms with the Model as "extreme" .. I can't help but worry that I am just working against the grain by splitting it up after it has been packaged together and creating extra work for myself for no good reason.

Secondly, what exactly are Controllers supposed to do? It seems like everyone agrees that Controllers should do as little as possible, but where you draw the line seems to differ for everyone. It seems to me that it's either:

a. The Controller should mediate all interaction between the View/Model - if the View needs some data from the Model, the Controller should have fetched/provided it. This seems to lead to the View being simpler, just straight formatting. It also seems to be the most popular way of doing it.

b. The Controller can pass the Model to the View, and if the View requires some data from the model, it can query it. This seems to lead to Views that are more dependent on the Model (they assume all the state query logic) and the Controller only decides which View to display (and how to interpret user input)

To me, it looks like B is the way to go, but I can't help but feel worried that I am robbing Controllers of what seems to be, fairly often, their only responsibility (that you write yourself, at least) - that A is so popular doesn't help my confidence in B.

Grinnblade
Sep 24, 2007
So, I'm working on a login system for a project I'm working on. I want the passwords to be as secure as feasibly possible, so I've been reading up on good hashing techniques, and I think I've got the general idea, but I want to just double check my logic with you guys.

1) At registration, the user chooses a password and confirms it.
2) At this time, the script also generates a salt of about 10 characters by using the hash() function:

code:
$rawdata = hash('whirlpool', rand(), false);

$shaker = str_split($rawdata);
$salt = '';

for ($i = 0; $i < 10; $i++)
    $salt .= $shaker[$i];
3) This salt is then both stored in my database for later use in checking the user's credentials at login, and then ALSO added to the plaintext password before hashing THAT and putting it in the database.

code:
/* salt stored, now to hash the password itself */

$splitter = str_split($password,(strlen($password)/2)+1);
$hashedPassword = hash('whirlpool', $splitter[0].$salt.$splitter[1], false);

/* insert code here to store $hashedPassword as the user's password in the database */
4) Then, when the user logs in, take the stored salt out of the database, split the user's provided password in half, put the salt into the middle of those halves, hash that, and check the result against the stored hashedPassword.

Is this about right?

Adbot
ADBOT LOVES YOU

A Flaming Chicken
Feb 4, 2007
I suggest using bcrypt instead of devising your own salt method.

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