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
Zorilla
Mar 23, 2005

GOING APE SPIT

Whilst farting I posted:

What's the easiest way to get just the current formatted system timestamp?
strtotime() works in the opposite direction you're thinking of. It converts textual representations of date/time into a unix timestamp. The effective opposite of this is date(), which converts unix timestamps into the formatting of your choosing:
php:
<?php echo date("Y-m-d H:i:s"); // If run now, it would return something like 2008-12-06 14:59:22 ?>
If you need to adjust server time to match your timezone or because its just plain wrong, do something like this at the top of your script:
php:
<?php putenv("TZ=US/Eastern"); ?>



Whilst farting I posted:

Sorry, I meant timestamp as in just the time, not the date. :nyoron:
date() can be used for anything that can be derived from a unix timestamp, really. I'm not even sure why strftime() exists:
php:
<?php date("H:i:s"); ?>

Zorilla fucked around with this message at 21:26 on Dec 6, 2008

Adbot
ADBOT LOVES YOU

Whilst farting I
Apr 25, 2006

Sorry, I meant timestamp as in just the time, not the date. :nyoron:

I managed to figure it out not too long after I posted that, after I had already been looking around for a while. :nyoron:

code:
$format = "%H:%M:%S";
  
$justtime = strftime($format);
  
echo("$justtime");

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Whilst farting I posted:

What's the easiest way to get just the current formatted system timestamp?

Read example #4

http://www.php.net/date

Strong Sauce
Jul 2, 2003

You know I am not really your father.





You want to use the date function, not strtotime. Conversly if you just want to get the current time (in your timezone) you can just use date("h:i:s")

Edit: looks like aton of people responded before me!

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Zorilla posted:

date() can be used for anything that can be derived from a unix timestamp, really. I'm not even sure why strftime() exists:

Because it is very useful to turn MySQL's timestamp into a unix time stamp. It's also handy to convert `last monday` into the correct time stamp.

Zorilla
Mar 23, 2005

GOING APE SPIT

duz posted:

Because it is very useful to turn MySQL's timestamp into a unix time stamp. It's also handy to convert `last monday` into the correct time stamp.

Aren't these what strtotime() is for?

Whilst farting I
Apr 25, 2006

fletcher posted:

Read example #4

http://www.php.net/date

Argh, I was just looking at everything with "time" in its name. :doh:

Thanks to everyone who responded.

Here's another thing that seems fairly simple but is stumping me: for connecting to MySQL using a php file, how do I keep the username and password hidden from the users?

I want users to be able insert, delete, etc in a MySQL table, but am not sure how to actually hide this information from the user. Here's an example of a page where I want everything from one table to be displayed to the user, but it needs to connect to the database first.

code:
<?
 $con = mysql_connect("localhost","MYSQLACCOUNTNAME","MYSQLACCOUNTPASSWORD");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("MYSQLDATABASETOUSE", $con);

?>

 <html>
 <head>
  <title>Display All Links</title>
 </head>
 <body>

<?
  $query = "SELECT * FROM links;";

  $result = mysql_query($query);

  if (!$result) 
  { 
    echo(mysql_error()); 
  }

 ....
	
Basically, how do I hide everything in the first php statement from the user? I'm guessing it has something to do with calling a login script that's not readable through http, but I'm not entirely sure.

Zorilla
Mar 23, 2005

GOING APE SPIT

Whilst farting I posted:

Basically, how do I hide everything in the first php statement from the user? I'm guessing it has something to do with calling a login script that's not readable through http, but I'm not entirely sure.

Not even big-time CMSes have a way to secure this as far as I know. WordPress, Joomla and others just put those as plaintext in a central config file.

im_afraid_of_clowns
Nov 28, 2000
I turn my camera on. I cut my fingers on the way.
I want to allow basic access to a site if terms are agreed upon. If the user hasn't agreed, they are re-directed to the terms page.

I'm still learning php and this is what I did:

code:
<?php
$expiresOn = time()+604800; 
$domain = $_SERVER['HTTP_HOST'];
if (isset($_POST['agree']))
{
	setcookie("agree", "yes", $expiresOn, "/", $domain, 0);
}
else 
{
	setcookie("agree", "no", $expiresOn, "/", $domain, 0);
}
?>
To check
code:
<?php
$domain = "http://www.".$_SERVER['HTTP_HOST'];
if ($_COOKIE['agree']==no || $_COOKIE['agree']=="")
{
	header("Location: $domain");
	exit;
}
?>
Will this approach work?

Zorilla
Mar 23, 2005

GOING APE SPIT
Seems like it should, but I would use a session variable in addition to a cookie, just to account for people with cookies disabled:
php:
<?php
// Terms of Service page

$domain $_SERVER["HTTP_HOST"];
$expiresOn time()+604800// 1 week from now

session_start();

if ($_POST["agree"] == "on") {
    $_SESSION["agree"] = true;
    setcookie("agree""yes"$expiresOn"/"$domain0);
    header("Location: http://www.".$domain."/inside-page.php";)
    exit;
} else {
    unset($_SESSION["agree"]);
    setcookie("agree"""time()-3600"/"$domain0); // This erases a cookie
}
?>
php:
<?php
// Inside pages

$domain $_SERVER["HTTP_HOST"];

session_start();

if ($_COOKIE["agree"] != "yes" || $_SESSION["agree"] !== true) {
    header("Location: http://www.".$domain);
    exit;
}
?>

Keep in mind, this is allowing access to inside pages based on a simple "yes" stored in a cookie. If you want to protect pages with a password, you'll need something more robust to keep people from simply looking at a cookie's contents to find out the password.

Zorilla fucked around with this message at 18:35 on Dec 7, 2008

subreality
Oct 4, 2002

I require a cup of tea and a large tray of internets immediately.
edit: Woops I need to refresh the thread before replying

subreality fucked around with this message at 00:55 on Dec 7, 2008

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Zorilla posted:

Aren't these what strtotime() is for?

My bad, I thought that was the function you said. In this case it's probably a remnant of PHP copying a bunch of C/C++ functions.

gibbed
Apr 10, 2006

Zorilla posted:

Not even big-time CMSes have a way to secure this as far as I know. WordPress, Joomla and others just put those as plaintext in a central config file.
#1 reason to provide access to PHP a location outside web root, I usually set up my domains in this manner:

/data/www/somesite.com/www, /data/www/somesite.com/subdomain

I give access to PHP to /data/www/somesite.com

I store things like configs there, or backend related code in /data/www/somesite.com/backend

It saves you the hassle of people getting access to important information / code in the event your HTTP server breaks and starts serving raw content.

ilikechapstick
Jun 17, 2007

very, very notorious.
Ok, I'm back for more XML action. This time it isn't using simpleXML, because after like an hour of searching, I found out that simpleXML cannot delete nodes. This is all using DOM XML PHP functions.

Anyways, same XML structure as before:

code:
<cgt>
<employee>
<username></username>
<firstname></firstname>
<...>
</employee>
</cgt>
So this time I am trying to delete the entire <employee> node based on their username, so I have this so far:

php:
<?
// new XML document
$xml = new DOMDocument();
$xml->load("xml/cgt.xml");

//create DOMXPath object, which allows us to use xpath in the DOM
$xpath = new Domxpath($xml);

//query the document for all username's that match the one we want
$result = $xpath->query("//*[username='" . $id . "']");

// now we go through the query and get to the <employee> tag.
// while the <employee> tag has any children, we delete them
foreach($result as $employee) {
    while($employee->hasChildNodes()) {
        $employee->removeChild($employee->childNodes->item(0));
    }                
}
?>
This code successfully deletes all of the nodes inside of the <employee> tag, but does not delete the <employee> tag themselves. Therefore I am left with a <employee/> tag once that code runs.

How would I delete that entire node? I've tried lots of things, and I came up with a query similar to this:

php:
<?
$emptyEmployees = $xpath->query("/cgt/employee[not(node())]");
?>
Which returns the correct amount, but I don't know how to "delete" the node itself. Would I have to use removeChild from the <cgt> node to access the <employee> node?

jasonbar
Apr 30, 2005
Apr 29, 2005

gibbed posted:

#1 reason to provide access to PHP a location outside web root, I usually set up my domains in this manner:

/data/www/somesite.com/www, /data/www/somesite.com/subdomain

I give access to PHP to /data/www/somesite.com

I store things like configs there, or backend related code in /data/www/somesite.com/backend

It saves you the hassle of people getting access to important information / code in the event your HTTP server breaks and starts serving raw content.

I could be misunderstanding the original request - but what stops them from dumping the content of the variables? This also won't prevent them from dumping the entire script to a browser.

If the goal is just out of sight, out of mind, this would work perfectly. If you are trying to prevent the disclosure of sensitive information there really isn't a way to - especially if the end user has the source available.

Not that keeping config files outside of the webroot is a bad idea..

edit: unless by users you just mean people who are accessing the final page as output - and not altering the source. In that case, what gibbed said is spot on.

jasonbar fucked around with this message at 02:04 on Dec 7, 2008

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


jasonbar posted:

I could be misunderstanding the original request - but what stops them from dumping the content of the variables? This also won't prevent them from dumping the entire script to a browser.

Hopefully not executing user data stops that.

Zorilla
Mar 23, 2005

GOING APE SPIT

ilikechapstick posted:

Which returns the correct amount, but I don't know how to "delete" the node itself. Would I have to use removeChild from the <cgt> node to access the <employee> node?
I've never tried this in PHP, but the Javascript equivalent has worked for me in the past.
php:
<?php
foreach($result as $employee) {
    $employee->parentNode->removeChild($employee);
}
?>

Zorilla fucked around with this message at 02:18 on Dec 7, 2008

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

:dukedog:

Why is this:

php:
<?
while ( preg_match( "#<span style=['\"]font-size:?(.+?)pt;?\s+?line-height:?\s+?100%['\"]>(.+?)</span>#is", $txt ) )
?>
Not catching this:
<span style='font-size:10pt;line-height:100%'>[color=red]Click everyday & feed the hungry for free!:[/color]</span> <span style='font-size:10pt;line-height:100%'>thehungersite.com</span>

Acer Pilot fucked around with this message at 04:28 on Dec 8, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

drcru posted:

Note: It's [url], the forums just parsed it into a link.

Uncheck "Automatically parse URLs" and edit those out.

jasonbar
Apr 30, 2005
Apr 29, 2005

drcru posted:

php:
<?
while ( preg_match( "#<span style=['\"]font-size:?(.+?)pt;?\s+?line-height:?\s+?100%['\"]>(.+?)</span>#is", $txt ) )
?>

edit: I am retarded.

jasonbar fucked around with this message at 05:22 on Dec 8, 2008

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

:dukedog:

Zorilla posted:

Uncheck "Automatically parse URLs" and edit those out.

That didn't work :( Bug on the forum?

jasonbar posted:

I don't know if this is why, but your "\s" needs to be "\\s"

I'll give it a shot in a second.

edit that didn't work. HEre's more of the code

php:
<?
            while ( preg_match( "#<span style=['\"]font-size:?(.+?)pt;?\s+?line-height:?\s+?100%['\"]>(.+?)</span>#is", $txt ) )
            {
                $txt = preg_replace_callback( "#<span style=['\"]font-size:?(.+?)pt;?\s+?line-height:?\s+?100%['\"]>(.+?)</span>#is" , array( &$this, 'unconvert_size' ), $txt );
            }?>

Acer Pilot fucked around with this message at 04:35 on Dec 8, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

jasonbar posted:

I don't know if this is why, but your "\s" needs to be "\\s"

\s matches a whitespace character. Unless he's trying to match a literal "\s", he doesn't need to add another slash.

Zorilla fucked around with this message at 05:12 on Dec 8, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

drcru posted:

That didn't work :( Bug on the forum?
Oh, I thought it was automatically adding [url] to an URL without vB markup. I didn't know [url] was there to begin with. You could add open and closing bold tags inside the tag to gently caress up parsing (just for posting here):

<span style='font-size:10pt;line-height:100%'>[color=red]Click everyday & feed the hungry for free!:[/color]</span>[url="http://www.thehungersite.com"]<span style='font-size:10pt;line-height:100%'>thehungersite.com</span>[/url]

Another thought: you don't need to put that in a while loop. Like most functions in PHP that do callbacks, it gets applied to every $needle found in $haystack. So basically, all you need to do is:

php:
<?php
$txt preg_replace_callback("/superlongregex/" "unconvert_size"$txt);
?>
...and it should apply unconvert_size() to every match in $txt.

Zorilla fucked around with this message at 06:10 on Dec 8, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT
...gonna use this double post to break up my thoughts...

This expression should be closer to what you need, I don't know if it will work, but it seems to check out on regextester.com:

/<span style=(['"])font-size:\s*\d+(?:pt|%|em|px)\s*;\s*line-height:\s*\d+(?:%|em|px);?(?:\1)>(.*?)<\/span>/is

In PHP and Javascript, I've always seen regexes start and end with /, so your use of # may have been a problem unless there's something I don't know.

edit: I just found this, which is probably the most helpful thing I've found to date on learning regular expressions.

Zorilla fucked around with this message at 09:26 on Dec 8, 2008

Supervillin
Feb 6, 2005

Pillbug

Zorilla posted:

\s matches a whitespace character. Unless he's trying to match a literal "\s", he doesn't need to add another slash.

But when \s gets to the function, it's no longer \s, it's s. One slash for the PHP string, one for the regex. Not sure which cases that applies to and which it doesn't, but I do know I've run into issues where it ate regex stuff if I didn't double the slashes.

Supervillin fucked around with this message at 09:00 on Dec 8, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

Supervillin posted:

But when \s gets to the function, it's no longer \s, it's s. One slash for the PHP string, one for the regex. Not sure which cases that applies to and which it doesn't, but I do know I've run into issues where it ate regex stuff if I didn't double the slashes.

Take a look at this, skip to "The preg Function Set" and read paragraph 2. I guess wrapping your regex in single-quoted strings is the answer to avoiding this problem.

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

:dukedog:

Zorilla posted:

...gonna use this double post to break up my thoughts...

This expression should be closer to what you need, I don't know if it will work, but it seems to check out on regextester.com:

/<span style=(['"])font-size:\s*\d+(?:pt|%|em|px)\s*;\s*line-height:\s*\d+(?:%|em|px);?(\1)>(.*?)<\/span>/is

In PHP and Javascript, I've always seen regexes start and end with /, so your use of # may have been a problem unless there's something I don't know.

edit: I just found this, which is probably the most helpful thing I've found to date on learning regular expressions.

Hm. I got an error about the first ] (it being unexpected). Regex continues to hurt my brain.

Thanks for trying though.

Zorilla
Mar 23, 2005

GOING APE SPIT

drcru posted:

Hm. I got an error about the first ] (it being unexpected). Regex continues to hurt my brain.

Thanks for trying though.
Oops, I started taking escape slashes out of your original regex without thinking. As a result, the string was closed prematurely when it hit the first quotation mark and the rest was trying to be parsed as PHP code (hence the unexpected "]").

Did your finished product look similar to this?

php:
<?php
// Replaces <span> tags with some vB-esque equivalent
$txt preg_replace(
    '/<span style=([\'"])font-size:\s*\d+(?:pt|%|em|px)\s*;\s*line-height:\s*\d+(?:%|em|px);?(?:\1)>(.*?)<\/span>/',
    '[sometag]\2[/sometag]',
    $txt
);
?>
If this doesn't work, my recommendation is to load up that regex tester site, start with an example of a string you want to match, then start turning pieces of it into regex one by one until it breaks. That's basically how I built the one here.

Zorilla fucked around with this message at 09:43 on Dec 8, 2008

zergstain
Dec 15, 2005

How do you free all the memory allocated to an array before the script ends?

$q = array(); doesn't work, and neither does unset($q);

Internet Headache
May 14, 2007

zergstain posted:

How do you free all the memory allocated to an array before the script ends?

$q = array(); doesn't work, and neither does unset($q);
If you meant "right before the script ends", PHP has garbage collection.

If you meant "freeing memory during script execution, before script ends", unset() should work. If you aren't sure, check the script's memory usage with memory_get_usage() before and after an unset.

Zorilla
Mar 23, 2005

GOING APE SPIT

zergstain posted:

How do you free all the memory allocated to an array before the script ends?

$q = array(); doesn't work, and neither does unset($q);

If you're worried about variables taking up a lot of memory, you're handling images I bet. I think you're supposed to use imagedestroy($q) for that.

zergstain
Dec 15, 2005

Internet Headache posted:

If you meant "right before the script ends", PHP has garbage collection.

If you meant "freeing memory during script execution, before script ends", unset() should work. If you aren't sure, check the script's memory usage with memory_get_usage() before and after an unset.

unset() definitely wasn't working. I ended up running the script, having it stop when the memory usage hit 50MB, then updating it with the user id it got to, and repeating. Ran it about 6 times for 3.5 million users. I just wanted to know for next time if necessary.

shrughes
Oct 11, 2008

(call/cc call/cc)
PHP 5.2.7 has been removed from distribution.

quote:

Due to a security bug found in the PHP 5.2.7 release, it has been removed from distribution. The bug affects configurations where magic_quotes_gpc is enabled, because it remains off even when set to on. In the meantime, use PHP 5.2.6 until PHP 5.2.8 is later released.

Whilst farting I
Apr 25, 2006

I want a very simple login system and system to check for logins, and reading the post not too far above my earlier post gives me an idea, but I'm still stuck.

I'm setting cookies like

code:
setcookie("user", $username, $expire);
and checking if they're valid on each page with this if

code:
if (isset($_COOKIE["user"]))
and I'm logging them out like this, logout.php

code:
<?php
setcookie("user", gone, mktime(12,0,0,1, 1, 1970), "/");
>
However, the permissions checking using that if loop isn't working and anybody can access anything if they've logged in once. The logout doesn't seem to be working. I can go to the logout page, go to that page with the if statement and it'll act as if I'm logged in.

Once I clear my cookies, however, then I can't view anything on the page with the if loop.

I know this is probably full of security holes, but right now I'm most concerned with getting the drat thing working in any form.

Edit: I viewed the cookie's contents both before and after clicking logout, and they didn't change at all.

Whilst farting I fucked around with this message at 03:55 on Dec 10, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT
Why do you have gone in there? For one thing, I don't think that's syntactically correct. You probably want this:

php:
<?php setcookie("user"""time()-3600"/"); // time()-3600 is just a personal preference. ?>
edit: wait, wouldn't it just be easier to write "0" instead of mktime(12,0,0,1, 1, 1970)?

Zorilla fucked around with this message at 04:37 on Dec 10, 2008

Whilst farting I
Apr 25, 2006

I've tried a bunch of different variations from a bunch of different tutorial websites, that was the one I was currently at.

I tried the one you gave me on IE and Firefox and the cookie's contents still remain unchanged.

Could it be because $username is not a global variable, or the comparison?

keveh
Sep 14, 2004

If you have a problem.....
I've had a look around for the answer to this problem, but can't seem to nail it down.

Basically I've made a small content management site, using Spaw as the text editor. The guy who is using it wants to put some script tags and functions in there, which is fine as he just enters it in the html tab.

But when he saves the page via a post, a 403 error page displays.

With any other kind of html tags, forms, text etc the page will save fine, it's only with script tags that it gets a 403 page. I've testing the php file that it posts to by echoing out some dummy text with an exit at the top, but the post isn't even reaching that file.

Has anybody come across this before, is it a setting on the server that will need to be changed?

ante
Apr 9, 2005

SUNSHINE AND RAINBOWS

Whilst farting I posted:

I've tried a bunch of different variations from a bunch of different tutorial websites, that was the one I was currently at.

I tried the one you gave me on IE and Firefox and the cookie's contents still remain unchanged.

Could it be because $username is not a global variable, or the comparison?
Are you running it before any output in the script?

Is the setcookie function returning true or false?

Whilst farting I
Apr 25, 2006

ante posted:

Are you running it before any output in the script?

Is the setcookie function returning true or false?

This is the entirety of logout.php

code:
<?php
	setcookie("user", "", time()-3600, "/");
>
When I set the cookie initially, here's some surrounding code.

code:
$expire = time()+60*60*24*30;
setcookie("user", $username, $expire);
echo "Hello $username, you are now logged in!";
echo "<meta http-equiv='Refresh' content='0; url=linkform.php'>";

Adbot
ADBOT LOVES YOU

sonic bed head
Dec 18, 2003

this is naturual, baby!

Whilst farting I posted:

This is the entirety of logout.php

code:
<?php
	setcookie("user", "", time()-3600, "/");
>
When I set the cookie initially, here's some surrounding code.

code:
$expire = time()+60*60*24*30;
setcookie("user", $username, $expire);
echo "Hello $username, you are now logged in!";
echo "<meta http-equiv='Refresh' content='0; url=linkform.php'>";

Make sure that the domain is exactly the same. If you have https://www. on one and no https://www. on the logout, the client won't send the cookie because it's not the same domain. Also make sure that cookies are enabled in the client options.

If you have firefox & firebug, you can type document.cookie into the console to see a string representation of the cookie. You can look in there to see if the "user" cookie exists.

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