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
sonic bed head
Dec 18, 2003

this is naturual, baby!

royallthefourth posted:

What is this called?
I use it fairly often and I'd really like to have a name for it.

"<<<"

php:
<?php
$s = <<< text
THIS IS A BUNCH OF TEXT

MY FORMATTING IS PRESERVED ACROSS LINES
text;
?>


Heredoc syntax.

http://us.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

royallthefourth posted:

What is this called?
I use it fairly often and I'd really like to have a name for it.

"<<<"

php:
<?php
$s = <<< text
THIS IS A BUNCH OF TEXT

MY FORMATTING IS PRESERVED ACROSS LINES
text;
?>


heredoc

[edit] now with link! http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

eHacked
Sep 30, 2003

CONGRATULATIONS!!! YOU ARE THE 6,127,436,218TH PERSON TO VIEW THIS USELESS POST. CLICK TO CLAIM YOUR PRIZE!!!
How do I extract information from XML?

Say I have this:

code:
<?xml version="1.0"?>
<previewroot>
<category>
  <item Id="6691" websiteid="0" category="2" contentgroup="1"/>
  <item Id="6690" websiteid="0" category="3" contentgroup="1"/>
  <item Id="6689" websiteid="0" category="4" contentgroup="1"/>
</category>
<sites>
  <item Id="117" websiteid="0" siteid="8" contentgroup="1"/>
</sites>
<content>
  <names>
    <name name="jpg" num="520" filesize="87222276"/>
    <name name="thumb" num="525"/>
    <name name="full" num="1" filesize="383874155"/>
    <name name="hdwmv" num="5" filesize="573953501" movie_length="2100.707"/>
    <name name="hswmv" num="5" filesize="381170297" movie_length="2100.815"/>
    <name name="lswmv" num="5" filesize="158266517" movie_length="2100.695"/>
    <name name="mpg" num="5" filesize="305189364" movie_length="2106.967912"/>
  </names>
</content>
</previewroot>
I want whatever the first movie_length is set to:

movie_length="2100.707"

I can do a stupid PHP function to remove everything but that info ... but I know it's got to be easier than that!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

eHacked posted:

How do I extract information from XML?

Say I have this:

code:
<?xml version="1.0"?>
<previewroot>
<category>
  <item Id="6691" websiteid="0" category="2" contentgroup="1"/>
  <item Id="6690" websiteid="0" category="3" contentgroup="1"/>
  <item Id="6689" websiteid="0" category="4" contentgroup="1"/>
</category>
<sites>
  <item Id="117" websiteid="0" siteid="8" contentgroup="1"/>
</sites>
<content>
  <names>
    <name name="jpg" num="520" filesize="87222276"/>
    <name name="thumb" num="525"/>
    <name name="full" num="1" filesize="383874155"/>
    <name name="hdwmv" num="5" filesize="573953501" movie_length="2100.707"/>
    <name name="hswmv" num="5" filesize="381170297" movie_length="2100.815"/>
    <name name="lswmv" num="5" filesize="158266517" movie_length="2100.695"/>
    <name name="mpg" num="5" filesize="305189364" movie_length="2106.967912"/>
  </names>
</content>
</previewroot>
I want whatever the first movie_length is set to:

movie_length="2100.707"

I can do a stupid PHP function to remove everything but that info ... but I know it's got to be easier than that!

Read up on this: http://us.php.net/simplexml

[EDIT] Whipped up some sample code because it's so drat easy.... this uses the XPATH function that was added to simpleXML in PHP5.2, you'll have to do it the slightly more complicated way if you are using a previous version...

php:
<?
$string = <<<XML
<?xml version="1.0"?>
<previewroot>
<category>
  <item Id="6691" websiteid="0" category="2" contentgroup="1"/>
  <item Id="6690" websiteid="0" category="3" contentgroup="1"/>
  <item Id="6689" websiteid="0" category="4" contentgroup="1"/>
</category>
<sites>
  <item Id="117" websiteid="0" siteid="8" contentgroup="1"/>
</sites>
<content>
  <names>
    <name name="jpg" num="520" filesize="87222276"/>
    <name name="thumb" num="525"/>
    <name name="full" num="1" filesize="383874155"/>
    <name name="hdwmv" num="5" filesize="573953501" movie_length="2100.707"/>
    <name name="hswmv" num="5" filesize="381170297" movie_length="2100.815"/>
    <name name="lswmv" num="5" filesize="158266517" movie_length="2100.695"/>
    <name name="mpg" num="5" filesize="305189364" movie_length="2106.967912"/>
  </names>
</content>
</previewroot>
XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/previewroot/content/names/name[@movie_length != ""]');
echo "this many nodes have 'movie_length': " . count($result) . "<br />";
echo "the first movie_length is: " .$result[0][@movie_length];
?>

Lumpy fucked around with this message at 03:21 on Apr 1, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Being pretty nitpicky here, but I would use this xpath expression to be a tiny bit cleaner:
//name[@movie_length][1]

For these reasons:
1) More flexible to change in the xml schema (not dependant on /previewroot/content/names/).
2) No need to do a string comparison if we just need to test the existence of @movie_length.
3) Might as well only return the data we need (first result only).



edit: nitpicky as hell

supster fucked around with this message at 04:21 on Apr 1, 2009

booshi
Aug 14, 2004

:tastykake:||||||||||:tastykake:
I am having some problems with getting this code to redirect properly after properly logging in. I've been banging my head over this and I still can't figure out what I'm not doing right (certain things edited / in caps to hide specifics):

code:
<?php 
mysql_connect("localhost", "USERNAME", "PASSWORD") or die(mysql_error()); 
mysql_select_db("DATABASE") or die(mysql_error()); 

//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))

//if there is, it logs you in and directes you to the members page
{ 
$username = $_COOKIE['ID_my_site']; 
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM user WHERE user = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check )) 
{
if ($pass != $info['Password']) 
{
}
else
{
header('Location: http://url.com/view.php'); 

}
}
}

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> 
<table border="0"> 
<tr><td colspan=2><h1>Login</h1></td></tr> 
<tr><td>Username:</td><td> 
<input type="text" name="username" maxlength="40"> 
</td></tr> 
<tr><td>Password:</td><td> 
<input type="password" name="pass" maxlength="50"> 
</td></tr> 
<tr><td colspan="2" align="right"> 
<input type="submit" name="submit" value="Login"> 
</td></tr> 
</table> 
</form> 
<?php
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in
if(!$_POST['username'] | !$_POST['pass']) {
die('You did not fill in a required field.');
}
// checks it against the database

if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysql_query("SELECT * FROM user WHERE user = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check )) 
{
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['Password']);
$_POST['pass'] = encrypt($_POST['pass']);

//gives error if the password is wrong
if ($_POST['pass'] != $info['Password']) {
die('Incorrect password, please try again.');
}

else 
{ 

// if login is ok then we add a cookie 
$_POST['username'] = stripslashes($_POST['username']); 
$hour = time() + 3600; 
setcookie(ID_my_site, $_POST['username'], $hour); 
setcookie(Key_my_site, $_POST['pass'], $hour); 

//then redirect them to the members area 
header('Location: http://url.com/view.php'); 
} 
} 
} 
else 
{ 

// if they are not logged in 
?> 

Any idea why this won't forward correctly after a correct login?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

supster posted:

Being pretty nitpicky here, but I would use this xpath expression to be a tiny bit cleaner:
//name[@movie_length][1]

For these reasons:
1) More flexible to change in the xml schema (not dependant on /previewroot/content/names/).
2) No need to do a string comparison if we just need to test the existence of @movie_length.
3) Might as well only return the data we need (first result only).



edit: nitpicky as hell

Next time, I'll just post the link. :colbert:

I kid, I kid: You are correct on every point, I just "spelled it all out" for the learnin'

Lumpy fucked around with this message at 06:29 on Apr 1, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

booshi posted:

I am having some problems with getting this code to redirect properly after properly logging in. I've been banging my head over this and I still can't figure out what I'm not doing right (certain things edited / in caps to hide specifics):


Any idea why this won't forward correctly after a correct login?

If there is any whitespace before the second header() it won't work. For example:

code:
<?php
$var = "on noe!";
// more code blah blah blah
?>

<?php
header("Location: /wee.php");
?>
Will not work since the whitespace between the end of the first PHP tag and the start of the second was output to the browser. That might not be your problem, but you didn't give any error messages it's giving you to make any better guesses and it's 1:30am and I should have been in bed hours ago :(

booshi
Aug 14, 2004

:tastykake:||||||||||:tastykake:

Lumpy posted:

If there is any whitespace before the second header() it won't work. For example:

code:
<?php
$var = "on noe!";
// more code blah blah blah
?>

<?php
header("Location: /wee.php");
?>
Will not work since the whitespace between the end of the first PHP tag and the start of the second was output to the browser. That might not be your problem, but you didn't give any error messages it's giving you to make any better guesses and it's 1:30am and I should have been in bed hours ago :(

No, and I double-checked that. I get no error messages from my code, just a blank page (which is not what I should get, I should get bumped to the address located in the header portion. Still banging my head against the wall since I am working on this solo without anyone to look at it.

eHacked
Sep 30, 2003

CONGRATULATIONS!!! YOU ARE THE 6,127,436,218TH PERSON TO VIEW THIS USELESS POST. CLICK TO CLAIM YOUR PRIZE!!!

Lumpy posted:

awesomeness

supster posted:

awesomeness v2

You guys are awesome and your mothers must be very proud of you!

eHacked
Sep 30, 2003

CONGRATULATIONS!!! YOU ARE THE 6,127,436,218TH PERSON TO VIEW THIS USELESS POST. CLICK TO CLAIM YOUR PRIZE!!!

booshi posted:

No, and I double-checked that. I get no error messages from my code, just a blank page (which is not what I should get, I should get bumped to the address located in the header portion. Still banging my head against the wall since I am working on this solo without anyone to look at it.

Your PHP is a mish-mash of syntax formatting ... You're not being consistent across your own script, so you'll come across bugs like this all the time. Keeping organized is the first way to prevent bugs.

Here's your code formatted, and (should be) working:

php:
<?
mysql_connect("localhost", "USERNAME", "PASSWORD") or die(mysql_error()); 
mysql_select_db("DATABASE") or die(mysql_error()); 

//Checks if there is a login cookie
//if there is, it logs you in and directes you to the members page
if(isset($_COOKIE['ID_my_site'])){ 
  $username = $_COOKIE['ID_my_site']; 
  $pass = $_COOKIE['Key_my_site'];
  $check = mysql_query("SELECT * FROM user WHERE user = '$username'")or die(mysql_error());
  while($info = mysql_fetch_array( $check )){
    if($pass != $info['Password']){}
    else{header("Location:http://url.com/view.php");}
  }
}
?>

<form action="<?=$_SERVER['PHP_SELF']?>" method="post"> 
<table border="0"> 
  <tr>
    <td colspan=2><h1>Login</h1></td>
  </tr>
  <tr>
    <td>Username:</td>
    <td><input type="text" name="username" maxlength="40"></td>
  </tr> 
  <tr>
    <td>Password:</td>
    <td><input type="password" name="pass" maxlength="50"></td>
  </tr> 
  <tr>
    <td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td>
  </tr> 
</table> 
</form> 

<?
//if the login form is submitted
if(isset($_POST['submit'])){
  // makes sure they filled it in
  if(!$_POST['username'] || !$_POST['pass']){die('You did not fill in a required field.');}
  // checks it against the database
  if (!get_magic_quotes_gpc()){$_POST['email'] = addslashes($_POST['email']);}

  $check = mysql_query("SELECT * FROM user WHERE user = '".$_POST['username']."'")or die(mysql_error());
  //Gives error if user dosen't exist
  $check2 = mysql_num_rows($check);
  if($check2 == 0){die('That user does not exist in our database. <a href="add.php">Click Here to Register</a>');}
  while($info = mysql_fetch_array($check)){
    $_POST['pass'] = stripslashes($_POST['pass']);
    $info['password'] = stripslashes($info['Password']);
    $_POST['pass'] = encrypt($_POST['pass']);

    //gives error if the password is wrong
    if($_POST['pass'] != $info['Password']){die('Incorrect password, please try again.');}
    else{
      // if login is ok then we add a cookie 
      $_POST['username'] = stripslashes($_POST['username']); 
      $hour = time() + 3600; 
      setcookie(ID_my_site, $_POST['username'], $hour); 
      setcookie(Key_my_site, $_POST['pass'], $hour); 

      //then redirect them to the members area 
      header("Location:http://url.com/view.php");
    } 
  }
} 
else{
// if they are not logged in
}
?>

Supervillin
Feb 6, 2005

Pillbug

eHacked posted:

helpfulness

Also, remember not to just use stuff pulled directly from POST or COOKIE directly in database queries. If someone makes their own form to post to your page, or fakes a cookie, $username could be something that outputs your whole database, deletes from it, anything else people could do with direct access.

Most people use prepared statements (mysqli or PDO) which do the escaping for you, but at the very least there should be a mysql_real_escape_string between user input and the database.

Bensa
Aug 21, 2007

Loyal 'til the end.
This doesn't exactly fit into this thread but I figure the people who can best answer it read this. Working on a project with various php features which are easy enough to do but I'm only lacking some kind of news or blog system.
What I want is to load a set number of previews for articles, 5/10/20, into one part of my main page, the next ones on the next page. Those previews would be one or two sentences followed by a link to the article itself. How the previews are generated isn't imporant since I can do them manually with the amount of content involved. No commenting required as each article will link to a forum section

It is literally like most news or blog sites but I just can't think of a better way to do this than to load a minimalist wordpress page into my main page. Coding this from scratch is a tad above my experience and not really worth the time for what the site is, I'd rather just have a good base to modify.

eHacked
Sep 30, 2003

CONGRATULATIONS!!! YOU ARE THE 6,127,436,218TH PERSON TO VIEW THIS USELESS POST. CLICK TO CLAIM YOUR PRIZE!!!
Is there a reason you can't just use wordpress?

Bensa
Aug 21, 2007

Loyal 'til the end.

eHacked posted:

Is there a reason you can't just use wordpress?
I can use it easily enough, I'm just looking for other options.
I don't need a lot of the functionality, the best option in my limited opinion would be just dropping a html (and possibly an associated preview text) file into a folder with the older articles and having the main page php just load it from there. The associated link would just load that html page inplace of the article preview section.

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss
Is there a way to cause a session variable to expire?

Here is my situation:
I am working with a CMS, drupal, and I am setting a cookie that turns on when a user comes from a certain landing page.

Well, as you know, cookies don't register until the page actually loads. But, in Drupal, a LOT of things happen in the background before the page loads, so when I set that Cookie, I need to be able to use it a little in the progression of the system.

So, what I am doing is setting both a cookie and a session ($_SESSION) to have the exact same data.

But, is there is a way to have the session data expire in the same way as a cookie?

Or, actually, that seems like a bad idea since sessions go away when the broswer is open.

So I guess a better question is how do you use cookie data in your cms/whatever system before the page has loaded?

Another situation is sometimes the cookie will change. So if user enters the site with $_COOKIE['pt'] = 1. But then he enters the site again and causes the $_COOKIE['pt'] = 2 to happen, that won't register until the browser reloads again.

So it seems any solution will involve major trade offs.

How do you deal with using Cookie data actively across the site? Is there a best practice for this?


I would say, if I could go in the PHP and just say unset($_COOKIE['pt']) every time I need to reset it, that would be very helpful... But I don't think it actually works like that? Or does it? Can we actually delete a cookie like that? The PHP.net people say the only way to delete a cookie is by setting it to have an expiration date of some past time, but that still requires the page to reload.

EDIT:

Here is my code because I think what I wrote is confusing a bit. I just took out the $_SESSION business. Here is how I am doing it now:

php:
<?
if ($is_retailer) {
    if (isset($_COOKIE['partner_tracking'])) {
    if (stristr($_SESSION['partner_tracking'], "cob")) { //if the cookie is tracking the wrong thing.
        unset($_COOKIE['partner_tracking']);
        setcookie("partner_tracking", "", time() - 1000000, '/');
        setcookie("partner_tracking", "ret$origin_val", time()+300, '/'); //5 minute timestamp
        $_COOKIE['partner_tracking'] = "ret$origin_val";
    }
    }
    else {
        setcookie("partner_tracking", "ret$origin_val", time()+300, '/'); //5 minute timestamp
        $_COOKIE['partner_tracking'] = "ret$origin_val";
    }
}
elseif ($is_cobrand) {
  if (isset($_COOKIE['partner_tracking'])) {
      if (stristr($_SESSION['partner_tracking'], "ret")) {
          unset($_COOKIE['partner_tracking']);
          setcookie("partner_tracking", "", time() - 1000000, '/');
          setcookie("partner_tracking", "cob$origin_val", time()+300, '/'); //5 minute timestamp
          $_COOKIE['partner_tracking'] = "cob$origin_val";
    }
  }
  else {
    setcookie("partner_tracking", "cob$origin_val", time()+1800, '/'); //30 minute timestamp
    $_COOKIE['partner_tracking'] = "cob$origin_val";
  }
}
?>
Hopefully its easy to follow the logic.

I am basically writing those four lines:
php:
<?
        unset($_COOKIE['partner_tracking']);
        setcookie("partner_tracking", "", time() - 1000000, '/');
        setcookie("partner_tracking", "ret$origin_val", time()+300, '/'); //5 minute timestamp
        $_COOKIE['partner_tracking'] = "ret$origin_val";
?>
To delete and put in a new cookie.

cannibustacap fucked around with this message at 00:17 on Apr 2, 2009

Treytor
Feb 8, 2003

Enjoy, uh... refreshing time!
Is there any way to pass a variable from one page to another within PHP without it being visible to the end user or using a database?

spiritual bypass
Feb 19, 2008

Grimey Drawer

Treytor posted:

Is there any way to pass a variable from one page to another within PHP without it being visible to the end user or using a database?

Write to a temp file?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Treytor posted:

Is there any way to pass a variable from one page to another within PHP without it being visible to the end user or using a database?

Kinda depends on what you are trying to do. Does it make sense to have these as GET variables that are visible in the URL?

If not, you'll have to use cookies. I'd suggest using a PHP Session. This will create a unique cookie for each visitor to identify the session, and you can set variables using $_SESSION['whatever'] without having to worry about creating additional cookie variables manually.

Zorilla
Mar 23, 2005

GOING APE SPIT

eHacked posted:

Here's your code formatted, and (should be) working:

I couldn't help myself:

php:
<?php
mysql_connect("localhost""USERNAME""PASSWORD") or die(mysql_error()); 
mysql_select_db("DATABASE") or die(mysql_error()); 

//Checks if there is a login cookie
//if there is, it logs you in and directs you to the members page
if (isset($_COOKIE['ID_my_site'])) {
    $username $_COOKIE['ID_my_site'];
    $pass $_COOKIE['Key_my_site'];
    $result mysql_query("SELECT * FROM user WHERE user = '".$username."' LIMIT 1") or die(mysql_error());
    
    $row mysql_fetch_array($result);
    if ($pass == $row['Password']) {
        header("Location:view.php");
        exit();
    }
}

//if the login form is submitted
if (isset($_POST['submit'])) {
    // makes sure they filled it in
    if (!$_POST['username'] || !$_POST['pass']) {
        $error "You did not fill in a required field.";
    } else {
        // checks it against the database
        if (function_exists("get_magic_quotes_gpc") && !get_magic_quotes_gpc()) {
            $_POST['email'] = addslashes($_POST['email']);
        }
        
        $result mysql_query("SELECT * FROM user WHERE user = '".$_POST['username']."' LIMIT 1") or die(mysql_error());
        
        //Gives error if user dosen't exist
        if (mysql_num_rows($result) == 0) {
            $error "That user does not exist in our database. <a href=\"add.php\">Click Here to Register</a>";
        } else {
            $row mysql_fetch_array($result);
            $_POST['pass'] = stripslashes($_POST['pass']);
            $_POST['pass'] = encrypt($_POST['pass']);
            $row['password'] = stripslashes($row['Password']);
            
            //gives error if the password is wrong
            if ($_POST['pass'] != $row['Password']) {
                $error "Incorrect password, please try again.";
            } else {
                // if login is ok then we add a cookie 
                $_POST['username'] = stripslashes($_POST['username']); 
                $hour time() + 3600; 
                setcookie("ID_my_site"$_POST['username'], $hour); 
                setcookie("Key_my_site"$_POST['pass'], $hour); 
                
                //then redirect them to the members area 
                header("Location:view.php");
                exit();
            }
        }
    }
// if they are not logged in
}
?>
<html>
<head>
<title></title>
<style type="text/css">
body {font-family: Verdana, Helvetica, sans-serif;font-size: 9pt;}
.error {background-color: #fdd;border: #faa;}
label {float: left;width: 8em;}
</style>
</head>
<body>
<?php if ($error) { ?>
<p class="error"><?php echo $error?></p>

<?php ?>
<form action="<?php echo basename(__FILE__); ?>" method="post">
    <h1>Login</h1>
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" /><br />
    <label for="pass">Password:</label>
    <input type="password" id="pass" name="pass" /><br />
    <input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

Things like postbacks (or really anything for that matter) should be handled before any output happens. Also, I got rid of the while() loops because there's no need to loop through query results if you're only expecting one result. Just grab one row and you're fine. Thirdly, it's better to display an error at the top of the page and display everything else as normal than it is to kill the script if something is wrong with the user's input, so I changed that too.

Zorilla fucked around with this message at 01:12 on Apr 2, 2009

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss
I'm reposting this question because I think I made a huge mess above and wanted to be more clear:

Is this a valid way to set, then unset a cookie variable?

php:
<?
unset($_COOKIE['partner_tracking']);
setcookie("partner_tracking", "", time() - 1000000, '/');
setcookie("partner_tracking", "ret$origin_val", time()+300, '/'); //5 minute timestamp
$_COOKIE['partner_tracking'] = "ret$origin_val";
?>
It seems to work, but can I trust that it will work on all server types and such? (I.e., is this an acceptable, standard way to handle cookie variables in PHP?)

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


cannibustacap posted:

Well, as you know, cookies don't register until the page actually loads. But, in Drupal, a LOT of things happen in the background before the page loads, so when I set that Cookie, I need to be able to use it a little in the progression of the system.
That's not how cookies work at all in PHP. They are available as soon as you put a variable in them or when the PHP is called if there is already one. Sessions are available as soon as you start one.

cannibustacap posted:

But, is there is a way to have the session data expire in the same way as a cookie?
A session is cookie based by default. Also by default it'll expire after 24 minutes of inactivity. If you want to manually remove it use session_destroy

cannibustacap posted:

So I guess a better question is how do you use cookie data in your cms/whatever system before the page has loaded?
Cookies are available as soon as PHP starts since they're sent with the page request.

cannibustacap posted:

Another situation is sometimes the cookie will change. So if user enters the site with $_COOKIE['pt'] = 1. But then he enters the site again and causes the $_COOKIE['pt'] = 2 to happen, that won't register until the browser reloads again.
If the cookie changes, either you changed it or the user did. How you deal with this is up to you.

It really sounds like you don't understand cookies.

keveh
Sep 14, 2004

If you have a problem.....
OK, this is just driving me crazy and I know somebody will be able to tell me why I'm just being stupid!

I have a class which when built gets an array for one of the variables. The array contains the last 40 messages from a database, and a function is used to loop through these messages to display them. For each message I am looping through the array again to check is any of the messages was a reply.

My problem is that in the second function to check for a reply seems to be affecting the first functions array.

That probably doesn't make sense, so here's a miniature version of the class and what I am trying to achieve.


php:
<?

class Build {
        
  var $messages = array();
    
  function Build(){
      $this->messages = $this->getMessages();
  }
  
  function displayMessages(){      
      $list = $this->messages;
      $return = "";
      foreach($list as $msg){
          $return .= 'the message was: '.$msg->message.'<br />';
          $return .= $this->checkReply($msg->msg_id)
      }
      return $return;
  }
  
  function checkReply($id){
      $replies = $this->messages;
      $return = "";
      foreach($replies as $msg){
          if($msg->reply_id == $id){
              $return = 'a reply was: '.$msg->message.'<br />';
          }
      }
      return $return;
  }
  
}

?>


The result would be:

code:
the message was: this is not working<br />
and it would stop.

So it's like that accessing and looping through the array for the second time is putting it to the end of the array.

This is confusing me, because the loops aren't accessing array directly, it's placing it in a new variable inside the two functions.

So, what am I doing that is blindingly wrong. Your help is much appreciated!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

keveh posted:

OK, this is just driving me crazy and I know somebody will be able to tell me why I'm just being stupid!

I have a class which when built gets an array for one of the variables. The array contains the last 40 messages from a database, and a function is used to loop through these messages to display them. For each message I am looping through the array again to check is any of the messages was a reply.

My problem is that in the second function to check for a reply seems to be affecting the first functions array.

That probably doesn't make sense, so here's a miniature version of the class and what I am trying to achieve.


php:
<?

class Build {
        
  var $messages = array();
    
  function Build(){
      $this->messages = $this->getMessages();
  }
  
  function displayMessages(){      
      $list = $this->messages;
      $return = "";
      foreach($list as $msg){
          $return .= 'the message was: '.$msg->message.'<br />';
          $return .= $this->checkReply($msg->msg_id)
      }
      return $return;
  }
  
  function checkReply($id){
      $replies = $this->messages;
      $return = "";
      foreach($replies as $msg){
          if($msg->reply_id == $id){
              $return = 'a reply was: '.$msg->message.'<br />';
          }
      }
      return $return;
  }
  
}

?>


The result would be:

code:
the message was: this is not working<br />
and it would stop.

So it's like that accessing and looping through the array for the second time is putting it to the end of the array.

This is confusing me, because the loops aren't accessing array directly, it's placing it in a new variable inside the two functions.

So, what am I doing that is blindingly wrong. Your help is much appreciated!

I'm not sure I understand what you are asking, but your checkReply() function can only return one reply per message since you set $return to a new value with = instead of appending with .=

Echo the length and type of $this->messages to make sure it's what you think it is. It could be you are returning the database result set, not an array of the actual results in your getMessages() method.

KuruMonkey
Jul 23, 2004

keveh posted:

OK, this is just driving me crazy and I know somebody will be able to tell me why I'm just being stupid!

...

So, what am I doing that is blindingly wrong. Your help is much appreciated!

Well, apart from a missing semi-colon I had to fix, and needing to kludge a set of test data together...

http://www.anwf.co.uk/woot.php

(I'm not guaranteeing that link still workiung past sunday afternoonish GMT, by the way)

It sort of works, mate.

You are, however, printing out the replies as messages in their own right as well as being messages. And you're doing this in a pretty inefficient manner.

My code:

php:
<?php

function getMessages()
{
    $messages = array();
    for($i=0$i<40$i++)
    {
        $msg = (object)null;
        $msg->msg_id $i+1;
        $msg->reply_id = ($i && $i == 0) ? $i-0// i.e. make some have replies
        $msg->message "Message ".($i+1);
        array_push($messages$msg);
    }
    return $messages;
}

class Build {
        
  var $messages = array();
    
  function Build(){
      // this fills $this->messages with 40 messages
      // a message is object(msg_id, reply_id, message) <as far as we know>
      $this->messages getMessages(); // made this global function to test
  }
    
  function displayMessages(){      
      $list $this->messages;
      $return "";
      foreach($list as $msg){
          $return .= 'the message was: '.$msg->message.'<br />';
          $return .= $this->checkReply($msg->msg_id); // you missed this semi-colon out
      }
      return $return;
  }
  
  function checkReply($id){
      $replies $this->messages;
      $return "";
      foreach($replies as $msg){
          if($msg->reply_id == $id){
              $return 'a reply was: '.$msg->message.'<br />';
          }
      }
      return $return;
  }
  
  function dbg()
  {
      return "<br /><br />Debug:<br />".var_dump($this->messagesTRUE)."<br /><br />";
  }
  
}

// test:
echo "Testing Output<br />";
$thing = new Build();
echo $thing->dbg();
echo $thing->displayMessages();

output:
code:
the message was: Message 1
a reply was: Message 6
the message was: Message 2
the message was: Message 3
the message was: Message 4
the message was: Message 5
the message was: Message 6
a reply was: Message 11
...and on to message 40
Note how message 6 is listed as a message and a reply.

So; if your real version from a DB doesn't work like that, the problem is in the DB reading code, not the array looping code...

I know you'll give the normal goon-in-coc response of "I can't change that part", but really the replies should "belong" to the message:

php:
<?
class Message
{
  var $id = 0;
  var $content = '';
  var $replies = array(); // store Message objects in here!

  function Message($id, $content)
  { 
    $this->id = $id;
    $this->content = $content;
  }

  function addReply($msg)
  {
    array_push($this->replies, $msg);
  }

  function render()
  {
    $tmp = '';
    $tmp .= "id={$this->id} / content={$this->content}<br />";
    foreach($this->replies as $reply)
    {
      $tmp .= "Reply to {$this->id}:<br />".$reply->render()."<br />";
      // obviously, for extra credit you make it increment an indent at each level...
    }
    return $tmp;
  }
}
...
class MessageHandler
{
  var $messages = array();

  function showMessages()
  {
    foreach($this->messages as $msg)
    {
      echo "Message:<br />";
      echo $msg->render(); // renders message and all replies in thread!
      echo "<hr />"; // to show end of message-thread
    }
  }
}
?>

KuruMonkey fucked around with this message at 12:52 on Apr 3, 2009

Crazak P
Apr 11, 2003

PUNISHER > SPIDERMAN
this is probably a really dumb question, but I can't seem to find the answer to it. How do you make a link where when you click on it, it automatically gives the save as prompt. I'd like to do this for jpg images.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Crazak P posted:

this is probably a really dumb question, but I can't seem to find the answer to it. How do you make a link where when you click on it, it automatically gives the save as prompt. I'd like to do this for jpg images.

I got 9 good tutorials on it on my first Google search.

I'll copy and paste the code from the first one here:

Some website posted:

php:
<?
// Tells the browser that where going to run a PHP script.
$file = $_GET['file'];
// Get a filename from the GET parameters.
Header ("Content-type: octet/stream");
Header ("Content-disposition: attachment; filename=".$file.";");
Header("Content-Length: ".Filesize($file));
// Sends the brower headers to tell it that its sending that file back to it.
Readfile($file);
// Reads the file from the server and send it to the browser.
Exit;
?>
Call it forcedownload.Php
Then your link would be

code:
<a href="http://www.Sitelocation/mp3s/forcedownload.Php?file=download.Mp3">Song Name</a>

Please note the pasted code there has a huge security hole in it, but it should give you the gist of how to do Save As.. boxes. If you don't want a new window popping up / replacing the current one, put a tiny / invisible eyeFrame on your page, and send the download link to it.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Lumpy posted:

If you don't want a new window popping up / replacing the current one, put a tiny / invisible eyeFrame on your page, and send the download link to it.

Am I missing something or couldn't he just use Content-disposition: inline;... to prevent the browser from leaving the page?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

Am I missing something or couldn't he just use Content-disposition: inline;... to prevent the browser from leaving the page?

I have no idea.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Lumpy posted:

If you don't want a new window popping up / replacing the current one

That won't happen anyways with that link.

Also, you should make sure the content-type header is the correct one.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I have a Daylight Saving Time problem.

On my site when someone makes a move in a game, posts a message, etc. the time it happened is recorded. Then it gets displayed when someone (for example) reads the post. Now that DST has started here (Britain), all the times are displayed one hour later than they should be. This is not what I want; I want all times to be interpreted by the system as GMT and displayed as GMT without the extra hour during summer. (They will be shown as GMT for all users regardless of user's timezone; it's not intended to be a particularly feature-rich site.)

I looked on the internet for the solution to this, and came across recommendations for using the date_default_timezone_set function. So I put the following into my configuration file:

date_default_timezone_set('UTC');

However, this doesn't seem to have worked; it's still misbehaving. What am I doing wrong?

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Has anyone used Wordpress as a backend/framework before?

I'd like to use it to implement a site that needs to let users have a basic profile page with a bio and their own specific simple blog.

I was thinking that can be done pretty easily by just having posts be posted under a category associated with each user and then only show blog posts in that category on the user's page.

Without having given this too much thought, one of the immediate issues I see is giving a way for users to make their posts. I wouldn't exactly want to give them access to the the admin panel.

Does anyone have any experience with making posts to Wordpress from outside of the admin panel? I am mainly concerned with maintaining the functionality of the wysiwyg editor and all the post options.


edit: On second thought, users can just be set up with an account with the Author role - but is there a way I can easily restrict them to posting only under one category or will that involve significant hacking?

supster fucked around with this message at 23:09 on Apr 3, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

duz posted:

Also, you should make sure the content-type header is the correct one.

Should it match the attached file or should it be text/html so as to look like a web page with a file attached?

Zorilla fucked around with this message at 01:56 on Apr 4, 2009

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss

supster posted:

Has anyone used Wordpress as a backend/framework before?

I'd like to use it to implement a site that needs to let users have a basic profile page with a bio and their own specific simple blog.

I was thinking that can be done pretty easily by just having posts be posted under a category associated with each user and then only show blog posts in that category on the user's page.

Without having given this too much thought, one of the immediate issues I see is giving a way for users to make their posts. I wouldn't exactly want to give them access to the the admin panel.

Does anyone have any experience with making posts to Wordpress from outside of the admin panel? I am mainly concerned with maintaining the functionality of the wysiwyg editor and all the post options.


edit: On second thought, users can just be set up with an account with the Author role - but is there a way I can easily restrict them to posting only under one category or will that involve significant hacking?

Use Drupal dude. You are obviously a smart guy, good coder so you can handle it. Drupal will give you the ability to control everything and create any kind of page or content type.

But I am biased, I am a drupal developer.

Wordpress would for sure be easier I bet, though you may need to make lots of compromises if you want to get specific with your goals.

How about this: how many hours are you willing to put in to this site?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Zorilla posted:

Should it match the attached file or should it be text/html so as to look like a web page with a file attached?

It should match the file you're sending.

Epikhigh
Apr 4, 2009

Roloc posted:

We may want to throw in some IDE's too, I dunno.

PDT - http://www.eclipse.org/pdt/ - This is what I use
Aptana - http://www.aptana.com/php - I haven't used this but it looks slick.
Zend Studio - http://www.zend.com/en/products/studio/ - They have an eclipse plugin now too I think

Edit: ohh yeah and about the DIVs and the widths... screw static graphics use GD and draw them :) http://us3.php.net/gd

I use WeBuilder 2008 - http://www.blumentals.net/webuilder/
Multipurpose writer that I couldn't go a day without :)

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Hammerite posted:

I have a Daylight Saving Time problem.

...
Really - nobody knows the solution to my problem?

Is my post missing some key information or something? I'm sure someone here knows what might be going wrong.

486
Jun 15, 2003

Delicious soda

Hammerite posted:

Really - nobody knows the solution to my problem?

Is my post missing some key information or something? I'm sure someone here knows what might be going wrong.

How are you storing the time? What format? You likely need to convert your old times and save your new times with one of PHP's many handy date functions

http://us2.php.net/manual/en/function.gmdate.php

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Smarty question -

Is there a clean way to build a string of html (in the template) and either assign it as a javascript variable or just print it based on some condition? The only ways I can think of doing it make it kind of messy to look at.

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

fletcher posted:

Is there a clean way to build a string of html (in the template) and either assign it as a javascript variable or just print it based on some condition?

That's generally what AJAX is for.

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