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

roachfiend posted:

That fixed the syntax error, but now it doesn't redirect.

Redirects can only happen if no HTML has been sent out yet, so your example would probably work if your PHP and HTML were reversed. Do this:

php:
<?php
function is_valid_login($username$password) {
    /* This is obviously for demonstration purposes only.
    You'll probably be doing a MySQL query for an salted & SHA1'ed password here */
    if ( ($username == "fn_action") && ($password == "yourpassword") ) {
        return true;
    }
}

if ($_POST["submit"]) {
    if ( is_valid_login($_POST["username"], $_POST["password"]) ) {
        header("location: http[b][/b]://erichamiter.com/news/");
        exit;
    } else {
        $error "Invalid username or password. Please try again.";
    }
} 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Login</title>

<style type="text/css">
label {margin-right: 1em;}
</style>
</head>

<body>
<?php
if ($error) {
?>
<div class="error">
    <?php echo $error?>
</div>
<?php
}
?>
<h3>Login</h3>
<form method="post" action="fastnews-code.php">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" value="fn_action" disabled="disabled" /><br />
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" size="24" /><br />
    <input type="submit" value="Login" />
</form>
</body>
Ideally, you want to do as much processing as possible before sending any output at all. Also, there's no reason to die() the script after setting the HTTP header. PHP knows to stop it right there on its own. (edit: learn something every day. I'll fix my example)

Zorilla fucked around with this message at 20:55 on Nov 9, 2008

Adbot
ADBOT LOVES YOU

MononcQc
May 29, 2007

Zorilla posted:

Also, there's no reason to die() the script after setting the HTTP header. PHP knows to stop it right there on its own.

No it doesn't. It will keep processing and just send the header when it's done.
Try this:
php:
<?php
header('location: http://google.com');
fopen('file.txt','w'); // if you need file.txt, it will be overwritten
?>

If the permissions are set right in your php folder, you'll now have a 'file.txt' in your directory.

To make it better:
php:
<?php
header('location: http://google.com');
exit;
fopen('file.txt','w'); // The script died before this.
?>

Now there should be no file added.

duck monster
Dec 15, 2004

Khorne posted:

Are there any extremely light-weight CMS systems that are easy to modify to fit in to an existing framework?

Things I am looking for:

Very simple user table (accountId, Username, Password, Email, Access) so it can just use the existing one
News posts/static pages (updates / information pages)
Article types with varying access requirements and an easy way for admins to revert edits (wiki-like system for documentation)
Loads a php file and passes it an array or object with page information (no smarty, no intricate templating systems)

All requirements don't have to be met. I know I am going to have to modify whatever I do choose to use. I cringe at the sight of most CMS systems I've checked out. TikiWiki and MediaWiki are bloated and geared more toward lame wiki sites than practical applications. Most of the smaller CMS projects seem poorly implemented or downright bad.

I'm fairly close to coding it myself, but it's a bad idea for me to take on another project. I have far too many left unfinished and an ever decreasing amount of free time.
CMS Made simple is what I use, partly because its basically just a tiny little CMS for use with smarty templates.

Its got a pretty configurable user auth system, but you might be on your own regarding an audit trail for edits.

I guess you could just add your own.

roachfiend
Mar 5, 2002

Zorilla posted:

Redirects can only happen if no HTML has been sent out yet, so your example would probably work if your PHP and HTML were reversed. Do this:
stuff
Thank you for your help- unfortunately it still doesn't redirect to the right page. It accepts the password, then leaves it on the page that did the action- fastnews-code.php.

This seems mind bogglingly complex to me. Isn't there an easier way to do this?

SuckerPunched
Dec 20, 2006

roachfiend posted:

This seems mind bogglingly complex to me. Isn't there an easier way to do this?

It's pretty simple, I think your problem is this:

roachfiend posted:

the problem is I don't know what the hell I'm doing.


:v:

Can you post your full code?

roachfiend
Mar 5, 2002
it's what zorilla just posted.

this seems like a wanker way out, but is there some javascript i could use that would take the place of all of this? i know this is a php thread but i think i'm over-complicating things.

since, indeed, i don't know what the hell i'm doing, i don't know what is editable and what is not- what is considered global variables, what the syntax rules are for mixing php and html- and i just don't really have the time to learn the basics of php. i just want a simple little thing that will redirect me.

Roctor
Aug 23, 2005

The doctor of rock.

roachfiend posted:

That fixed the syntax error, but now it doesn't redirect.

php:
<?
<H3>Login</H3>
<FORM METHOD="post" ACTION="http://erichamiter.com/news/fastnews-code.php">
<INPUT TYPE="hidden" NAME="fn_action" VALUE="login">
Password: <INPUT TYPE="password" SIZE="24" NAME="password" VALUE=""><BR>
<INPUT TYPE="submit" VALUE="Login">
</FORM>

<?php
if ( isset($_POST['fn_action'])) 
 {
 header('location:  http ://erichamiter.com/news/');
 die();
 } 
?> 
?>

e: I posted to explain why this didn't work, but apparently there's a whole other page to this thread with explanations that I didn't see.

Zorilla
Mar 23, 2005

GOING APE SPIT

roachfiend posted:

Thank you for your help- unfortunately it still doesn't redirect to the right page. It accepts the password, then leaves it on the page that did the action- fastnews-code.php.

This seems mind bogglingly complex to me. Isn't there an easier way to do this?

Sounds like it's almost working. By looking at the line that says header("location: blahblahblah");, you know that it should go to http://erichamiter.com/news/, right? You're saying it's staying on the login page instead with the fields filled out? If it's not saying "Invalid username or password. Please try again." at the top, that seems to suggest that the login is working, but the redirect isn't.

Zorilla fucked around with this message at 21:31 on Nov 9, 2008

Hammerite
Mar 9, 2007

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

Zorilla posted:

Well maybe if your code was tabbed sanely...

Also, is there no way for you to perform those queries outside of a loop instead of potentially hundreds of times, each one for a single row of results? The current way seems really inefficient (e.g. you could instead do "SELECT blah FROM table WHERE UserID IN(w, x, y, z)" and put them into an array).

The thread has moved on from my question that prompted this post, but I wanted to say that I spent a couple of hours reading up on how to do "JOINs" and incorporating them into the code I'd already produced, and I'm pleased I did!

KuruMonkey
Jul 23, 2004

roachfiend posted:

this seems like a wanker way out, but is there some javascript i could use that would take the place of all of this? i know this is a php thread but i think i'm over-complicating things.

No. There is no way to do logon authorisation in javascript that is any more secure than a milk chocolate flak jacket. (and a thin one at that)

php:
<?php
    //where shall we redirect?
    define('REDIRECT_URL''http://www.google.com');


    // pull in your vars:
    $q '';
    if(isset($_REQUEST['q']))
    {
        $q $_REQUEST['q'];
    }
    
    // check for validity, replace with something non-trivial
    if($q != '')
    {
        // do stuff
        // whatever it may be
        // but NOT html output
        
        // redirect
        header('Location: '.REDIRECT_URL);
        // die
        exit;
    }
?>
<!-- Stuff here is HTML and only happens if the check for validity fails -->
<form action='YOUR START URL' method='post'>
<input type='text' name='q' value='' />
<input type='submit' name='submit' value='submit' />
</form>
Start by playing with something really simplem like that, so you can see whats going on, and get the test / redirect logic right. Then add in the testing and stuff you actually need to do bit by bit.

There's no point pissing around when you're doing the secure bit of your site; you need to spend the time to do it properly and get to understand it, or you need to stop and use an off the shelf system rather than write your own.

roachfiend posted:

since, indeed, i don't know what the hell i'm doing, i don't know what is editable and what is not- what is considered global variables, what the syntax rules are for mixing php and html- and i just don't really have the time to learn the basics of php. i just want a simple little thing that will redirect me.

if its between
php:
 <?php and ?>
then its PHP, if its outside, its just text (so in your case its HTML).

if you're not using you own functions, then all variables are global in that file. So you can do:
php:
<?php
  $myvar 'hello world';
?>
<p>This is html now, and php says: <?php echo $myvar?></p>
That is enough for you to get going.

SpaceAceJase
Nov 8, 2008

and you
have proved
to be...

a real shitty poster,
and a real james
What's the best and easiest way to parse an RSS feed? I don't want to do anything advanced, just add a weather feature to the side of my web application that downloads its information from an Aussie weather site. (It's necessary for the kind of work that we do).

Zorilla
Mar 23, 2005

GOING APE SPIT

SpaceAceJase posted:

What's the best and easiest way to parse an RSS feed? I don't want to do anything advanced, just add a weather feature to the side of my web application that downloads its information from an Aussie weather site. (It's necessary for the kind of work that we do).

If you're familiar with DOM in Javascript, this should be trivial. PHP also has a DOM implementation.

These are probably more helpful in learning this:
http://www.w3schools.com/php/php_xml_dom.asp
http://www.ibm.com/developerworks/library/os-xmldomphp/

roachfiend
Mar 5, 2002

KuruMonkey posted:

That is enough for you to get going.

Thank you for the assistance. I haven't had a chance to try this out, but I will, and report back.

roachfiend
Mar 5, 2002

Zorilla posted:

...that seems to suggest that the login is working, but the redirect isn't.
Agreed.

jasonbar
Apr 30, 2005
Apr 29, 2005

SpaceAceJase posted:

What's the best and easiest way to parse an RSS feed? I don't want to do anything advanced, just add a weather feature to the side of my web application that downloads its information from an Aussie weather site. (It's necessary for the kind of work that we do).

I don't know if it will work for you, but check out http://www.php.net/xml_parse_into_struct

Munkeymon
Aug 14, 2003

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



SpaceAceJase posted:

What's the best and easiest way to parse an RSS feed? I don't want to do anything advanced, just add a weather feature to the side of my web application that downloads its information from an Aussie weather site. (It's necessary for the kind of work that we do).

http://simplepie.org/ is probably even easier than parsing the feed with your own DOM inspector.

Foran
Apr 19, 2008

Garry's Mod is an Art
Hey, I'm developing the framework for a small php/flash combo game.
I'm currentley stuck, becuase I can't figure out how to make flash adhere to a php $_SESSION. Right now, I have something like this as my link from mysql -> php -> Flash.

php:
<?PHP
include "base.php";

if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
$user $_SESSION['Username'];
$stats mysql_query("SELECT * FROM users WHERE Username='$user'") or die(mysql_error());
while($f mysql_fetch_array$stats )) { //Fetch User data from users table.
$col $f['Colony'];
// Open the file and erase the contents if any
$fp fopen("${user}.txt""w");
// Write the data to the file
fwrite($fp$col);
// Close the file
fclose($fp);
}
}
?>

The php file takes the $col var, transfers it to a text file named for the user
(I.E. rsugar.txt), and that text file is loaded into flash, where it is split up and transformed into a tiled map for colony/city management.

I need to have flash load the correct text file based on the the user using the flash app.

Does anyone know how to do this? I'm thinking it would be an addition to the php script, but I'm not sure.

Foran fucked around with this message at 19:13 on Nov 11, 2008

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Rsugar posted:

Hey, I'm developing the framework for a small php/flash combo game.
I'm currentley stuck, becuase I can't figure out how to make flash adhere to a php $_SESSION. Right now, I have something like this as my link from mysql -> php -> Flash.

php:
<?PHP
include "base.php";

if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
$user $_SESSION['Username'];
$stats mysql_query("SELECT * FROM users WHERE Username='$user'") or die(mysql_error());
while($f mysql_fetch_array$stats )) { //Fetch User data from users table.
$col $f['Colony'];
// Open the file and erase the contents if any
$fp fopen("${user}.txt""w");
// Write the data to the file
fwrite($fp$col);
// Close the file
fclose($fp);
}
}
?>

The php file takes the $col var, transfers it to a text file named for the user
(I.E. rsugar.txt), and that text file is loaded into flash, where it is split up and transformed into a tiled map for colony/city management.

I need to have flash load the correct text file based on the the user using the flash app.

Does anyone know how to do this? I'm thinking it would be an addition to the php script, but I'm not sure.

Pass the session number (or username, or whatever) to Flash as a parameter when you embed the object. Then flash can use it as part of it's data requests.

Foran
Apr 19, 2008

Garry's Mod is an Art

Lumpy posted:

Pass the session number (or username, or whatever) to Flash as a parameter when you embed the object. Then flash can use it as part of it's data requests.

Thanks, that worked.

Supervillin
Feb 6, 2005

Pillbug

jasonbar posted:

I don't know if it will work for you, but check out http://www.php.net/xml_parse_into_struct

I used xml_parse_into_struct for months before finding simplexml_load_file and simplexml_load_string. Then I wept for joy. Lots easier, in my opinion.



Edit: vvv Yeah, it's just a matter of what you need.

Supervillin fucked around with this message at 08:37 on Nov 12, 2008

jasonbar
Apr 30, 2005
Apr 29, 2005

Supervillin posted:

I used xml_parse_into_struct for months before finding simplexml_load_file and simplexml_load_string. Then I wept for joy. Lots easier, in my opinion.

Cool, I didn't know about those. I can't say that I've found xml_parse_to_struct difficult to work with, but it fits my requirements exactly. How do the simplexml_* functions handle documents with multiple elements of the same name? I couldn't find any information about it with a quick search, and I am too lazy to setup a test.

Zorilla
Mar 23, 2005

GOING APE SPIT

jasonbar posted:

Cool, I didn't know about those. I can't say that I've found xml_parse_to_struct difficult to work with, but it fits my requirements exactly. How do the simplexml_* functions handle documents with multiple elements of the same name? I couldn't find any information about it with a quick search, and I am too lazy to setup a test.

Arrays, I'm guessing. If you ever do test it, var_dump the resulting variables to see what happens.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Zorilla posted:

Arrays, I'm guessing. If you ever do test it, var_dump the resulting variables to see what happens.

Correct. I really love simplexml. So much so that I wrote a wrapper for it so I can use it to handle all my HTML so I don't have to write it out anymore.

jasonbar
Apr 30, 2005
Apr 29, 2005

Zorilla posted:

Arrays, I'm guessing. If you ever do test it, var_dump the resulting variables to see what happens.

I just tested, and it creates an array "channel" that has an associative array for all of the elements. Pretty nifty, if not unexpected given the documentation.

edit: also, "well formed" in this case is fairly flexible.
edit 2: whoops, "channel" not "attributes" where each channel is a simplexml object.

jasonbar fucked around with this message at 01:30 on Nov 12, 2008

Stephen
Feb 6, 2004

Stoned
I've stored images into a database column and now I'm trying to display them in PHP. This is something I'm new to, so obviously I googled tutorials etc. on displaying images in PHP from a database.

Now from my understanding I need a separate request for my HTML and for the image with different headers. However, if I want to show a lot of images in a loop or something, that means I have to make a new server request, a new database connection and a new query for each and every photo that I want displayed from the database.

Is there something that I'm misunderstanding here, or is this grossly inefficient method the only way?

waffle iron
Jan 16, 2004
Please don't store images in a database. You're better off writing them to a disk and storing the path and filename in the database.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


waffle iron posted:

Please don't store images in a database. You're better off writing them to a disk and storing the path and filename in the database.

There finally was a use case where it would be better to store them in the DB in a post in SHSC. The poster had several million images, all well under 1KB in size, and was having filesystem limitation problems. Putting them in a DB was the only solution posted that worked.


Stephen posted:

Now from my understanding I need a separate request for my HTML and for the image with different headers. However, if I want to show a lot of images in a loop or something, that means I have to make a new server request, a new database connection and a new query for each and every photo that I want displayed from the database.

You should be reusing your connection to the database, not destroying it each time you make only one query. You can even select multiple things from the database with one query too.

Roctor
Aug 23, 2005

The doctor of rock.

waffle iron posted:

Please don't store images in a database. You're better off writing them to a disk and storing the path and filename in the database.

I'm making a replacement for an ad management system at work and the old system stored all the ad images in the database. Legacy code exists to ruin lives.

waffle iron
Jan 16, 2004

Roctor posted:

I'm making a replacement for an ad management system at work and the old system stored all the ad images in the database. Legacy code exists to ruin lives.
The real problem with images in databases is that it creates an IO shitstorm if the web server and database server are the same machine.

At least it's not as bad as storing PHP in a database and then eval'ing.

spiritual bypass
Feb 19, 2008

Grimey Drawer

waffle iron posted:

At least it's not as bad as storing PHP in a database and then eval'ing.

That sounds like a great prank, but I'm sure someone's done it in a real application. :psyduck:

Stephen
Feb 6, 2004

Stoned

duz posted:

You should be reusing your connection to the database, not destroying it each time you make only one query. You can even select multiple things from the database with one query too.

No need to be a prick, I'm not absolutely retarded, just slightly..
The examples I was referring to are all as such:
php:
<?
while ($rows = MYSQL_FETCH_ARRAY($result))   {
    echo "Image - ";
    echo "<img src=\"show_image.php?id=".$rows['id']."\">";
}
?>
Say I've got 20 images. That means show_image.php is requested 20 times which then connects to the database 20 times and queries for that image 20 times.

DaTroof
Nov 16, 2000

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

royallthefourth posted:

That sounds like a great prank, but I'm sure someone's done it in a real application. :psyduck:

I'm pretty sure it used to be common practice in PHP-Nuke.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Stephen posted:

No need to be a prick, I'm not absolutely retarded, just slightly..
The examples I was referring to are all as such:
php:
<?
while ($rows = MYSQL_FETCH_ARRAY($result))   {
    echo "Image - ";
    echo "<img src=\"show_image.php?id=".$rows['id']."\">";
}
?>
Say I've got 20 images. That means show_image.php is requested 20 times which then connects to the database 20 times and queries for that image 20 times.

You can stick a cache system in front of your database if it can't handle the traffic.

The real problem is, of course, using the database as a filesystem. Anything to fix the shortcomings with that setup is just adding stupid to stupid.

duz fucked around with this message at 23:20 on Nov 13, 2008

Stephen
Feb 6, 2004

Stoned

duz posted:

You can stick a cache system in front of your database if it can't handle the traffic.

The real problem is, of course, using the database as a filesystem. Anything to fix the shortcomings with that setup is just adding stupid to stupid.
Yeah, like I said, it's the first time I've tried anything like this. The idea was to store the images in the database so that I could edit/change it from multiple sites and servers easily.

cka
May 3, 2004

royallthefourth posted:

That sounds like a great prank, but I'm sure someone's done it in a real application. :psyduck:

vBulletin does that for its templating system (and I think the hook system in the 3.5+ releases.) At the very least, it's convenient.

sonic bed head
Dec 18, 2003

this is naturual, baby!
php:
<?
$id = "blah"
$db = new mysqli("localhost", "test", "pwd", "serv_test");
    
    
    $stmt = $db -> prepare("SELECT PASSWORD FROM MY_TABLE WHERE ID=?");
    $stmt -> bind_param("s", $id);
        
    $stmt -> execute();
    $stmt->store_result();
    
    echo $stmt->num_rows;

?>
I am not understanding why, but no matter what, I keep getting 0 for num_rows here but when I try this:

php:
<?
$id = "blah"
$db = new mysqli("localhost", "test", "pwd", "serv_test");
    
    
    $stmt = $db -> prepare("SELECT PASSWORD FROM MY_TABLE WHERE ID='blah'");
    
    $stmt -> execute();
    $stmt->store_result();
    
    echo $stmt->num_rows;

?>
I get num_rows as 1. I've checked my syntax many times and I'm getting no errors in my log. Any idea what I'm doing wrong?

toby
Dec 4, 2002

Do you want $stmt->affected_rows instead?


edit: vv oh right, my bad.

toby fucked around with this message at 19:35 on Nov 18, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

toby posted:

Do you want $stmt->affected_rows instead?

That's for writing to the db when you don't expect to get any results back.

sonic bed head
Dec 18, 2003

this is naturual, baby!

toby posted:

Do you want $stmt->affected_rows instead?


edit: vv oh right, my bad.

Thanks but I had already tried that. This is getting extremely frustrating as I'm just trying to write more correct PHP here instead of my old addslashes. I've found nothing that seems like a similar problem to this.

Is there any way I can debug what SQL is actually receiving for the parameters? I've tried mysqli->show_debug_info or whatever but it isn't printing anything.

Adbot
ADBOT LOVES YOU

me your dad
Jul 25, 2006

I've been working on learning a little PHP for an online reference manual I have created within our company's intranet directory. My main goal with this project is to create webforms which would replace some VBA enhanced Word and Excel files currently being used.

I want these forms to send emails to me or other people but I have not succeeded in getting one to send. I maintain a personal website and I have tested the code on it and it worked fine (except I didn't see a "From" name for some reason).

Here's the HTML I am using:

code:
<html>
   <body>
	<form method='post' action='mailform.php'>
		<p>Email: <input type='text' name='email'></p>
		<p>Subject: <input type='text' name='subject'></p>
		<p>Message:</p>
		<p><textarea name='message' rows='10' cols='30'></textarea></p>
		<input type='submit' value='Submit Form'>
	</form>
   </body>
</html>
And here's the PHP:

php:
<?php
$email_address $_POST['email'] ;
$subject $_POST['subject'] ;
$message $_POST['message'] ;
mail"myemailaddress@gmail.com""Subject: $subject",
$message"From: $email);

echo "Thank you for using our mail form.<br/>";
echo "Your email has been sent.";
?>

*myemailaddress@gmail.com* is set to my work email address on the file I am testing at work.

I took a look at the PHP settings we use at work and I've copied below anywhere mentioning "mail":

From phpinfo.php

code:
mail.force_extra_parameters	no value	        no value
sendmail_from	                no value	        no value
sendmail_path	          /usr/sbin/sendmail -t -i	/usr/sbin/sendmail -t -i
Path to sendmail 	  /usr/sbin/sendmail -t -i 
MAIL 	                  /var/mail/root 
_ENV["MAIL"]	          /var/mail/root
Is there anything within these settings that might be blocking things? The person who configured everything left the company a few while ago and we do not have anyone who can change anything within this configuration right now. Is this something I will have to wait for until we have someone who can do this?

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