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
MrEnigma
Aug 30, 2004

Moo!

drcru posted:

What are your thoughts on just using implode/explode?

It should work, but then you have to catch all the special cases (like escpaing characters). My feeling that if someone has already wrote the way it should be and thought of all that, why reinvent the wheel, I'll just use that.

Adbot
ADBOT LOVES YOU

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Thanks for the pointers sirs, now I have another annoyance.

The more questions they answer, the more likely it is that a question they've already answered will come up. If I store which q_ids they do in a string inside a cookie or session, is it possible with a simple query to do a

SELECT * FROM questions WHERE q_id != $IN_THIS_ARRAY() ORDER BY rand( ) LIMIT 1

Or something similar?

stack
Nov 28, 2000

Safety Shaun posted:

Thanks for the pointers sirs, now I have another annoyance.

The more questions they answer, the more likely it is that a question they've already answered will come up. If I store which q_ids they do in a string inside a cookie or session, is it possible with a simple query to do a

SELECT * FROM questions WHERE q_id != $IN_THIS_ARRAY() ORDER BY rand( ) LIMIT 1

Or something similar?

code:
SELECT * FROM questions WHERE q_id NOT IN (x, y, z) ORDER BY RAND() LIMIT 1;
Use implode() to turn your array into a comma separated list which I represented above with 'x, y, z'.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

stack posted:

code:
SELECT * FROM questions WHERE q_id NOT IN (x, y, z) ORDER BY RAND() LIMIT 1;
Use implode() to turn your array into a comma separated list which I represented above with 'x, y, z'.

Thank you so very very much.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Crap, how do I avoid the header already sent spaz out that PHP has when I retrieve and edit (remove) a cookie in the middle of my script. Simply moving it to the top of this script isn't possible because it's an include and the main index.php is outputted before this is called.

php:
<?
{lots of code}
    $prevcorrect = $_COOKIE["cookiename"];
    setcookie("cookiename", 0, time()-604800, "/", ".mydomain.co.uk", 0);
{lots of code}
?>
Or would it be a lot more simple to set a session in the other script, then destory the session here; or would I come up with the same problem?

MrEnigma
Aug 30, 2004

Moo!

Safety Shaun posted:

Crap, how do I avoid the header already sent spaz out that PHP has when I retrieve and edit (remove) a cookie in the middle of my script. Simply moving it to the top of this script isn't possible because it's an include and the main index.php is outputted before this is called.

php:
<?
{lots of code}
    $prevcorrect = $_COOKIE["cookiename"];
    setcookie("cookiename", 0, time()-604800, "/", ".mydomain.co.uk", 0);
{lots of code}
?>
Or would it be a lot more simple to set a session in the other script, then destory the session here; or would I come up with the same problem?

Sessions would fix this, but they also do not persist for a user when they come back (although you could somehow use a cookie to reactivate a session...or other craziness like that).

A cookie has to be sent in the headers, which means it has to go before any output. This means, you'll either need to figure out a way to get that cookie set at the top of the page (or on a new page), or you need to output buffer the page.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

MrEnigma posted:

Sessions would fix this, but they also do not persist for a user when they come back (although you could somehow use a cookie to reactivate a session...or other craziness like that).

A cookie has to be sent in the headers, which means it has to go before any output. This means, you'll either need to figure out a way to get that cookie set at the top of the page (or on a new page), or you need to output buffer the page.

Either way I'll have to recode index.php to and call cookies and/or initiate the session at the top. I'll play around with buffer.

The value is only passed from one page to the other but using session/cookie to avoid any interference with the value. Is there any way I can set the variable in this script, redirect, then request the variable data from the previous page without having to submit a 'form'.

Zorilla
Mar 23, 2005

GOING APE SPIT

Safety Shaun posted:

Either way I'll have to recode index.php to and call cookies and/or initiate the session at the top. I'll play around with buffer.

Yeah, really do try to separate your code from your templating as much as possible by getting most of your code out of the way before output happens. I know it's not totally possible short of using something like Smarty because of stuff like database result loops which end up in the middle of the page, but it does make it much easier to manage things that need to be done before the header gets sent out.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Zorilla posted:

Yeah, really do try to separate your code from your templating as much as possible by getting most of your code out of the way before output happens. I know it's not totally possible short of using something like Smarty because of stuff like database result loops which end up in the middle of the page, but it does make it much easier to manage things that need to be done before the header gets sent out.

I will try that in future, thanks for the advice. Although I am still learning, I'm pretty confident what I am coding now (with assistance from you guys) is going to work pretty well. I appreciate all the pointers you guys have given me so far.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


MrEnigma posted:

Sessions would fix this, but they also do not persist for a user when they come back (although you could somehow use a cookie to reactivate a session...or other craziness like that).

You can also set the session time out and gc to something longer then 24 minutes if you want to.

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.
Can anyone think of a way to detect whether a class is abstract in PHP? I don't care if it's kinda hacky just as long as it's fool-proof and preferably doesn't involve digging into the source itself :shobon:

Edit: reflection duh :downs:

Inquisitus fucked around with this message at 15:25 on Aug 5, 2008

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
$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?
It's changing a local path of an image into a location of an image on the server

Safety Shaun fucked around with this message at 23:00 on Aug 6, 2008

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

Stephen
Feb 6, 2004

Stoned
Is it possible to do a redirect with POST values in PHP? I've learned from Google that it's not possible with header(), but I haven't found any other way to do this.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Stephen posted:

Is it possible to do a redirect with POST values in PHP? I've learned from Google that it's not possible with header(), but I haven't found any other way to do this.

I could never figure out a way to, I had this same question a couple weeks ago.

DaTroof
Nov 16, 2000

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

Stephen posted:

Is it possible to do a redirect with POST values in PHP? I've learned from Google that it's not possible with header(), but I haven't found any other way to do this.

Redirects don't POST. One workaround is to store the POST values in a session variable.

php:
<?
// form.php
session_start();
if ($_POST['submit'] == 'Submit') {
    $_SESSION['posted'] = $_POST;
    header('Location: redirect.php');
}
?>
<form action="" method="post">
    <input type="text" name="sometext" />
    <input type="submit" name="submit" value="Submit" />
</form>
php:
<?
// redirect.php
session_start();
print_r($_SESSION['posted']);
unset($_SESSION['posted']);
?>

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Stephen posted:

Is it possible to do a redirect with POST values in PHP? I've learned from Google that it's not possible with header(), but I haven't found any other way to do this.

It's not supposed to be done. Either convert the POST values into GET and forward or use sessions.

Stephen
Feb 6, 2004

Stoned

duz posted:

It's not supposed to be done. Either convert the POST values into GET and forward or use sessions.

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.

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

Stephen
Feb 6, 2004

Stoned

bt_escm posted:

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.
That's a great idea! I really actually feel quite dirty doing any of this since it deals with pricing and amounts. Weren't hidden HTML inputs deemed insecure about 10 loving minutes after the Internet was invented? How the gently caress are huge companies with multiple national banking partners still using this type of poo poo for money processing?

Grigori Rasputin
Aug 21, 2000
WE DON'T NEED ROME TELLING US WHAT TO DO
Uh, dumb question but: what is the syntax to do PHP IF blocks with HTML? I've seen it before but have rarely used it, and can't think of a place where to find it and my searches have failed.

Syntax is like:

<?php if $state true ?>
<div> blah_true....</div>
<?php else ?>
<<div>blah_false,,,</div>
...

chocojosh
Jun 9, 2007

D00D.
That should work although I would add braces

code:

<?php if (<boolean condition>) { ?>
   <div> blah_true....</div>
<?php } else { ?>
   <<div>blah_false,,,</div>
<?php } ?>
I'm pretty sure though this is bad coding practice and you should be using templates and other stuff instead.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

chocojosh posted:

I'm pretty sure though this is bad coding practice and you should be using templates and other stuff instead.

Yeah, use smarty

code:
{if $something}
    <div>something is true</div>
{else}
    <div>something is false</div>
{/if}

illamint
Jun 26, 2005

According to The Oxford English Dictionary, the word "snapshot" was originally a hunting term.

chocojosh posted:

I'm pretty sure though this is bad coding practice and you should be using templates and other stuff instead.
It's not always necessary or the best choice to add in a templating language on top of a templating language. As far as the original question goes, check out PHP's alternative syntax for control structures:
code:
<?php if (condition): ?>
<b>conditioN!</b>
<?php elseif (condition2): ?>
<i>conditioN!</i>
<?php else: ?>
hurrr! <img ...>
<?php endif; ?>

Zorilla
Mar 23, 2005

GOING APE SPIT

Grigori Rasputin posted:

Uh, dumb question but: what is the syntax to do PHP IF blocks with HTML? I've seen it before but have rarely used it, and can't think of a place where to find it and my searches have failed.

Nuts to what others have said so far. If your project is a really small one, it doesn't make sense to include major frameworks like Smarty. I usually just do this:

php:
<?php
$crap "poo";

if ($state === true) {
    // comment to demonstratoe PHP tabbing inside "if" statement
?>
<div>
    blah_true....<br />
    The value of $crap is &quot;<?php echo $crap?>&quot;
</div>
<?php
    // another comment
} else {
?>
<div>
    blah_false,,,
</div>
<?php
}
?>

I put line breaks between template starts and stops. This way, indentation of PHP and HTML are independent of each other and don't influence each other. The result is very clean HTML output.

I strongly recommend using PHP's templating system instead of straight-up using echo statements since it context highlights properly in code editors and is tabbed out the way it appears in your browser's "View Source" window.

Zorilla fucked around with this message at 01:41 on Aug 8, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Zorilla posted:

Nuts to what others have said so far. If your project is a really small one, it doesn't make sense to include major frameworks like Smarty.

I don't think the size of the project really matters, it's very beneficial and easy to implement, you might as well. Plus there's always the rule about projects starting small and quickly growing when you never thought they were going to.

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss
How do I create and pass variables inside of php files?

Here is an example:

for the top of index.php
php:
<?php
extract($_REQUEST);

$mainvars "mainvars.php";
include($mainvars);

mainvars.php
php:
<?
$var1 = "hey"; //hey
$header = "header.php"; //header files
$footer = "footer.php"; //do comments mess things up here?
?>
later in index.php
php:
<?
<a href="/$header">The Header!</a>
?>
I notice this is not working on my site.

How do I create variables that will pass through the php code?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


cannibustacap posted:

php:
<?
<a href="/$header">The Header!</a>
?>
I notice this is not working on my site.

Because that's not PHP code, that's HTML. You'll need an echo or something there if you want to print out the values of your variables.

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss

duz posted:

Because that's not PHP code, that's HTML. You'll need an echo or something there if you want to print out the values of your variables.

Oh no, the entire thing is within the "<?php .... ?>" brackets.

Zorilla
Mar 23, 2005

GOING APE SPIT

cannibustacap posted:

Oh no, the entire thing is within the "<?php .... ?>" brackets.

Then shouldn't it be like this?

php:
<?php
?>
<a href="/<?php echo $header?>">The Header!</a>
<?php
?>

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Zorilla posted:

Then shouldn't it be like this?

php:
<?php
?>
<a href="/<?php echo $header?>">The Header!</a>
<?php
?>


Why would you put the top and bottom PHP tags in there? :)

I vote be really lazy:
code:
<?= "<a href='$header'>The Header!</a>";?>

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Lumpy posted:

Why would you put the top and bottom PHP tags in there? :)

I vote be really lazy:
code:
<?= "<a href='$header'>The Header!</a>";?>

Using [php] bbcode automatically puts them there.

functional
Feb 12, 2008

Poker Sort

Assume an array of non-negative integers. They should be sorted in descending order, except if an integer A is present X times in the list, all A should come before all B present Y<X times in the list, and all A should come after all C present Z>X times in the list, and all A should be sorted descending versus any D present X times in the lest. Bonus Credit given for the best and shortest answer.

Example:

php:
<?
L   =52126723644689 //These are actually arrays and not strings
S(L)=66622244987531
?>

functional fucked around with this message at 15:20 on Aug 11, 2008

chocojosh
Jun 9, 2007

D00D.

functional posted:

Poker Sort

Assume an array of non-negative integers. They should be sorted in descending order, except if an integer A is present X times in the list, all A should come before all B present Y<X times in the list, and all A should come after all C present Z>X times in the list, and all A should be sorted descending versus any D present X times in the lest. Bonus Credit given for the best and shortest answer.

Example:

php:
<?
L   =52126723644689 //These are actually arrays and not strings
S(L)=66622244987531
?>

Does this look like the homework help thread?

functional
Feb 12, 2008

chocojosh posted:

Does this look like the homework help thread?

You may be confused because I took the time to write a nice problem description. (Nobody does homework in PHP. And I am not a student.)

thedaian
Dec 11, 2005

Blistering idiots.

functional posted:

You may be confused because I took the time to write a nice problem description. (Nobody does homework in PHP. And I am not a student.)

We are confused. It's formated exactly like a generic homework problem, or a job interview problem.

Anyway, there's a ton of different php sort functions. Try one of those. If you've got a specific issue with your code, then we can probably help. We're not here to do all your work for you.

waffle iron
Jan 16, 2004

functional posted:

You may be confused because I took the time to write a nice problem description. (Nobody does homework in PHP. And I am not a student.)
gently caress you and your bonus credit.

functional
Feb 12, 2008

thedaian posted:

Anyway, there's a ton of different php sort functions. Try one of those. If you've got a specific issue with your code, then we can probably help. We're not here to do all your work for you.

Actually the problem is that all of the PHP sort functions are broken in some way. The natural approach would be to "group" the number of values, for instance, keeping an array with keys for the values 1-9.

php:
<?
[1] => 2
[2] => 0
...
[9] => 1
?>
Which would correspond to a hand 191.

You could then flip the array, and get a sorted map which would solve the problem. Unfortunately PHP won't let you have repeated keys, so if there are two 1s and two 9s, you get a collision and you lose. And instead of lumping those two values into an array under the same key, it just drops one of them, so you also lose. You would think you could do the same thing using asort, but again, PHP will sort the array values, but it's a destructive sort with respect to key order! You can't guarantee 9 will come before or after 1.

Instead of having one nice sort that works, PHP has ten different sorts, none of which works. This is an easy problem in several other languages. It is not trivial in PHP. It is typical though of the kind of thing PHP programmers have to deal with, which is why I posted it here.

functional fucked around with this message at 22:26 on Aug 11, 2008

Grigori Rasputin
Aug 21, 2000
WE DON'T NEED ROME TELLING US WHAT TO DO

Zorilla posted:

Nuts to what others have said so far. If your project is a really small one, it doesn't make sense to include major frameworks like Smarty. I usually just do this:

php:
<?php
$crap "poo";

if ($state === true) {
    // comment to demonstratoe PHP tabbing inside "if" statement
?>
<div>
    blah_true....<br />
    The value of $crap is &quot;<?php echo $crap?>&quot;
</div>
<?php
    // another comment
} else {
?>
<div>
    blah_false,,,
</div>
<?php
}
?>

I put line breaks between template starts and stops. This way, indentation of PHP and HTML are independent of each other and don't influence each other. The result is very clean HTML output.

I strongly recommend using PHP's templating system instead of straight-up using echo statements since it context highlights properly in code editors and is tabbed out the way it appears in your browser's "View Source" window.

Thanks, it's some simple theming for a Drupal View, so it is not very complicated and has about a 99.9% chance of remaining so in the future.

Basically, I'm printing out some info entered into a Drupal site and need to account for formatting if some of that information isn't set.

The first PHP projects I messed with were a tangle of processing/presentation so I'm pretty good about isolating them from each other.

Grigori Rasputin fucked around with this message at 22:31 on Aug 11, 2008

Adbot
ADBOT LOVES YOU

DaTroof
Nov 16, 2000

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

functional posted:

Instead of having one nice sort that works, PHP has ten different sorts, none of which works. This is an easy problem in several other languages. It is not trivial in PHP. It is typical though of the kind of thing PHP programmers have to deal with, which is why I posted it here.

It's really not all that non-trivial. Here's a solution I hacked together in a few minutes.

php:
<?
class IntegerSet {
    var $value;
    var $count;
}
function _pokerSortCmp($a, $b) {
    if ($a->count > $b->count) {
        return -1;
    }
    if ($a->count < $b->count) {
        return 1;        
    }
    if ($a->value > $b->value) {
        return 1;
    }
    if ($a->value < $b->value) {
        return -1;
    }
    return 0;
}
function pokerSort($array) {
    $grouped = array();
    foreach($array as $i) {
        if (isset($grouped["{$i}"])) {
            $grouped["{$i}"]->count +=1;
        } else {
            $grouped["{$i}"] = new IntegerSet();
            $grouped["{$i}"]->value = $i;
            $grouped["{$i}"]->count = 1;
        }
    }
    usort($grouped, '_pokerSortCmp');
    $result = array();
    foreach ($grouped as $i) {
        for ($t = 0; $t < $i->count; $t++) {
            array_push($result, $i->value);
        }
    }
    return $result;
}

$integers = array(1, 3, 3, 4, 5);
$sorted = pokerSort($integers);
echo join(", ", $sorted) . "<br/>";

$integers = array(2, 2, 4, 4, 4, 4, 5, 6, 7, 7, 8, 9);
$sorted = pokerSort($integers);
echo join(", ", $sorted) . "<br/>";
?>
I'm sure it can be improved, but the problem isn't interesting enough for me to waste many more brain cycles on it.

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