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
Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Thirteenth Step posted:

got it (i think):

php:
<?php
    if(!isset($_SESSION["username"])) {
    header("Location: denied.php");
    exit;
   } 
?>

Seems to work. :)

("username" is the session created in the previous page's login form, upon successful login)

Just to make sure you are thinking about this right, "username" is a session variable, not a session in and of itself. $_SESSION is "the session" ( the global session variable / object ) and you assign it session vars to keep track of data between pages:

php:
<?
session_start(); // you have A ( one ) session

$_SESSION['poop'] = 43; // same session, but now it has a variable named 'poop' attached

$_SESSION['blah'] = 'daslkjdja'; // you still only have one session, but now it has another variable

print_r( $_SESSION ); // see all the other stuff hiding in there!
?>

Adbot
ADBOT LOVES YOU

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
So, uh, not that anyone should ever do this, but why does

php:
<?
$foo="bar";
$foo();
?>
work, while

php:
<?
${"bar"}();
?>
doesn't?

the chip
Mar 10, 2002

Fun Shoe
I am having a problem with CodeIgniter. I searched google and there's help that's so close but no cigar.

I am using XAMPP as my localhost and I have made no changes to it's configuration files.

I am trying to work my way through this tutorial: http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-3/

Anyway, I made a controller email.php.
php:
<?php

class Email extends Controller{
    function __construct()
    {
        parent::Controller();
    }
    function index(){
        $config=Array(
            'protocol' => 'smtp''smpt_host'=> 'ssl://smtp.googlemail.com''smtp_port'=>465'smtp_user'=>'username@gmail.com''smtp_pass'=>'password'
        );
        
        $this->load->library('email'$config);
        $this->email->set_newline("\r\n");
        
        $this->email->from('username@gmail.com''Michael');
        $this->email->to('username@gmail.com');
        $this->email->subject('Email subject test');
        $this->email->message('It works!');
        
        if ($this->email->send()){
            echo'YES!';
        }
        else
        {
            show_error($this->email->print_debugger());
        }
    }
}
?>

Got this error:
code:
A PHP Error was encountered

Severity: Warning

Message: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

Filename: libraries/Email.php

Line Number: 1519
Well, I tried changing those lines in PHP.ini and it is spitting out the same error but this time with the new host/port.

I noticed that SMTP is disabled in XAMPP's apache admin. How do I fix this problem?

Small White Dragon
Nov 23, 2007

No relation.

FeloniousDrunk posted:

php:
<?
$foo();
?>
This is a time-honored tradition. It means "call the function whose name is in foo." It actually comes in really handy in complicated code, and its use is condoned by many experienced programmers -- well, provided you handle the security correctly, anyway.

FeloniousDrunk posted:

php:
<?
${"bar"}();
?>
This works for me in PHP 5.3.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dargor posted:

I am having a problem with CodeIgniter. I searched google and there's help that's so close but no cigar.

I am using XAMPP as my localhost and I have made no changes to it's configuration files.
Well, I tried changing those lines in PHP.ini and it is spitting out the same error but this time with the new host/port.

I noticed that SMTP is disabled in XAMPP's apache admin. How do I fix this problem?

I have yet to have any coffee this AM, so I might have mis-read everything, but this sounds like a web server / host configuration thing. Email their support and ask what you can do to allow PHP to send mail.

thedaian
Dec 11, 2005

Blistering idiots.

Dargor posted:

I am having a problem with CodeIgniter. I searched google and there's help that's so close but no cigar.

I am using XAMPP as my localhost and I have made no changes to it's configuration files.

Well, I tried changing those lines in PHP.ini and it is spitting out the same error but this time with the new host/port.

I noticed that SMTP is disabled in XAMPP's apache admin. How do I fix this problem?

XAMPP does not include a mail server. You need a mail server set up and configured to be able to send email through php mail routines. I don't know what type of solutions there are for setting one up on your localhost, though.

rotaryfun
Jun 30, 2008

you can be my wingman anytime
I am attempting to setup two wiki's on the same server. The first wiki is all setup and has quite a few documents in place. I'm running mediawiki and followed this guide to setup the second:

http://www.steverumberg.com/wiki/index.php?title=WikiHelp_-_Method_One

It worked well and I have two valid wikis. The site sets a cookie so that you don't have to pass the 'w' variable in every page call.

I'm having a really tough time getting the cookie part to work correctly. I can navigate the pages/wikis fine as long as I distinguish which wiki I want. There are several functions of the wikis that I can't perform though (such as login) because I can't pass the 'w' variable through the login process... which is where the cookie should come into play.

Code from the LocalSettings.php file that directs which wiki to goto by way of pointing to another LocalSettings file. The only code that I changed is after the else statement so that my users do not have to enter the 'w' variable. Plan on removing that once the cookies are working. The site is an intranet site so I'm not sure if I can even accomplish this with cookies or not.
php:
<?
# The system determines which wiki to display based on either:
#   W parameter passed to INDEX.PHP, or
#   the cookie "wikiCode"
#
# First, test for the W parameter. Was it passed?
$sr_WikiCode = $_REQUEST['w'];  
# Tip: this new variable is prefixed with my initials "sr_" in order 
#      to distinguish it from the variables that are standard within MediaWiki
if ($sr_WikiCode <> "") {
   # Yes, W parameter was passed, so save it in a cookie until it gets changed. 
   # 2008-04-18 Note: MediaWiki sets its cookies using variables, like the following:
   #   setcookie($name,$value,$expire, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
   # I haven't yet tested it using their variables, so I've hard-coded it:
   setcookie('wikiCode', $sr_WikiCode, time()+60*60*24*365, '/', 'cedarpedia');
} elseif ($_COOKIE['wikiCode'] <> "") {
   # the parameter "W" wasn't passed but the cookie wikiCode does have a value, so use it
   $sr_WikiCode = $_COOKIE['wikiCode'];
} else {
   # neither the W parameter was passed nor does the cookie wikiCode have a value, so 
   # we don't know which wiki to display. Let user know that we cannot continue.
   $sr_WikiCode = 'cedarpedia';
}
# We know which wiki to display. Set the configuration variables specific 
# to the individual wiki
require_once ('LocalSettings_' . $sr_WikiCode . '.php');
?>
'cedarpedia' is the dns CNAME that points to the server cdpwiki

Munkeymon
Aug 14, 2003

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



FeloniousDrunk posted:

So, uh, not that anyone should ever do this, but why does

php:
<?
${"bar"}();
?>

Works in 5.2.5 but I kind of wish it didn't anywhere because :psyboom:

epswing
Nov 4, 2003

Soiled Meat

thedaian posted:

XAMPP does not include a mail server. You need a mail server set up and configured to be able to send email through php mail routines. I don't know what type of solutions there are for setting one up on your localhost, though.

This is completely false, of course XAMPP includes a mail server. It's called Mercury. It's right there in the control panel.

Thirteenth Step
Mar 3, 2004

I have a combo box which populates from the DB, code is:

php:
<?php        
$query="SELECT forename,surname,dept FROM staff";

$result mysql_query ($query);
echo "<select name=staff value=''>Staff Name</option>";

while($nt=mysql_fetch_array($result)){
echo "<option value=select_user>$nt[forename] $nt[surname]   - $nt[dept] Staff</option>";
}
echo "</select>";
 ?>

I've searched high and low but what I'm trying to do is create a form button which will DELETE the record the user has selected in the combo box, from the DB.

Is it a lot of code? / complicated?

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Thirteenth Step posted:

I have a combo box which populates from the DB, code is:

php:
<?php
$query="SELECT forename,surname,dept FROM staff";

$result mysql_query ($query);
echo "<select name=staff value=''>Staff Name</option>";

while($nt=mysql_fetch_array($result)){
echo "<option value=select_user>$nt[forename] $nt[surname]   - $nt[dept] Staff</option>";
}
echo "</select>";
?>

I've searched high and low but what I'm trying to do is create a form button which will DELETE the record the user has selected in the combo box, from the DB.

Is it a lot of code? / complicated?
It wouldn't be too bad. Here is an example:

new form:
php:
<?php
$query="SELECT id,forename,surname,dept FROM staff";

$result mysql_query ($query);
echo "<form type=\"post\" action=\"\">";  //This will post to itself
echo "<select name=\"staff\">Staff Name</option>";

while($nt=mysql_fetch_array($result)){
echo "<option value=\"{$nt['id']}\">{$nt['forename']} {$nt['surname']} - {$nt['dept']} Staff</option>";
}
echo "</select>";
echo "<input type=\"submit\" name=\"submit\" value=\"submit\" />";
echo "</form>";
?>

backend code:
php:
<?php
// put this code at the top of your PHP file so when the form posts, it will run before your select list is created.
if ($_POST['submit']) {
  $deleteID mysql_real_escape_string($_POST['id']);
  $deleteQuery "DELETE FROM staff WHERE id = '$deleteID' LIMIT 1";
  $deleteResult mysql_query($deleteQuery) or die(mysql_error());
}
?>

This is a basic example and assumes you have a field called id stored in the staff table as a unique identifier.

DarkLotus fucked around with this message at 19:09 on Mar 25, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Thirteenth Step posted:

I have a combo box which populates from the DB, code is:

php:
<?php        
$query="SELECT forename,surname,dept FROM staff";

$result mysql_query ($query);
echo "<select name=staff value=''>Staff Name</option>";

while($nt=mysql_fetch_array($result)){
echo "<option value=select_user>$nt[forename] $nt[surname]   - $nt[dept] Staff</option>";
}
echo "</select>";
 ?>

I've searched high and low but what I'm trying to do is create a form button which will DELETE the record the user has selected in the combo box, from the DB.

Is it a lot of code? / complicated?

You need some sort of unique identifier for each staff member, then it's easy. DELETE FROM staff WHERE id = someStaffId. Your html is lookin pretty messed up, may want to fix that as well.

revmoo
May 25, 2006

#basta
What's the easiest way to match if statements containing a bunch of possibilities. For example, if $variable contains any one of 30 different possible strings return true otherwise return false?

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

revmoo posted:

What's the easiest way to match if statements containing a bunch of possibilities. For example, if $variable contains any one of 30 different possible strings return true otherwise return false?

put those strings in an array, then use
php:
<?
if (in_array($value, $array)) { 
//do stuff
}
?>
or you can use switch()
php:
<?
switch ($i) {
  case 0:
    echo "i equals 0";
    break;
  case 1:
    echo "i equals 1";
    break;
  case 2:
    echo "i equals 2";
    break;
}
?>
which is the same as:
php:
<?
if ($i == 0) {
  echo "i equals 0";
} elseif ($i == 1) {
  echo "i equals 1";
} elseif ($i == 2) {
  echo "i equals 2";
}
?>

DarkLotus fucked around with this message at 21:06 on Mar 25, 2010

gwar3k1
Jan 10, 2005

Someday soon

revmoo posted:

What's the easiest way to match if statements containing a bunch of possibilities. For example, if $variable contains any one of 30 different possible strings return true otherwise return false?

A switch rather than an if, you can have multiple cases:

php:
<?
  switch($var)
  {
    case "A":
    case "B":
    case "C":
      doThis(0);
      break
    case "D":
    case "E":
    case "F":
      doThis(1);
      break;
  }?>
Edit: Never mind, misunderstood. Or not...

gwar3k1 fucked around with this message at 21:07 on Mar 25, 2010

revmoo
May 25, 2006

#basta
^^I like this idea too, I might go with that. EDIT: Tried this idea and it works the best for what I'm actually trying to do.

DarkLotus posted:

put those strings in an array, then use if (in_array($value, $array)) { do stuff }

Simple enough, thanks a bunch.

I usually stick to the design side of things so I'm pretty novice when it comes to getting things done in PHP.

revmoo fucked around with this message at 21:15 on Mar 25, 2010

KuruMonkey
Jul 23, 2004
In another exciting episode of 'weird ways to do things in PHP', you can also do this instead of using the array version.

The point being that you cannot const or define an array, so you need to define/const a string instread:

php:
<?
class Muppet
{
  const ACCEPTABLE_VALUES = '|1|2|3|'; // note leading and trailing |

  function is_acceptable($a)
  {
    return (strpos(self::ACCEPTABLE_VALUES, "|{$a}|") !== FALSE);
  }
}
?>
Note: very much not saying thats a better way to go about it, but its another option, if you want to be using constants rather than variables to test against

Standish
May 21, 2001

PHP associative arrays are really hash tables underneath, so if you have a lot of valid values or a lot of values to validate it's going to faster to search by key not by value:
php:
<?
$acceptableValues=Array(
   "value1"=>1,
   "value2"=>1,
   "value3"=>1,
   "value4"=>1,
   "value5"=>1,
   ...
);

...
$val=$_REQUEST["something"];
if (isset($acceptableValues[$val]))
  // valid
else
  //invalid
...?>
rather than doing a linear search of the array (or string) every time, like in_array() (or strpos()) do.

But if you only have few values to check and you're only calling it once then use whatever code is clearest.

revmoo
May 25, 2006

#basta
Just did 1100 lines of case statements to translate zip codes into geographical price zones. My hands are tired.

I probably could have done it a little bit smarter, but since the zip code zones were broke up into a ton of different regions there wasn't much that could have been shortened or automated.

Thanks again for the help guys.

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

revmoo posted:

Just did 1100 lines of case statements to translate zip codes into geographical price zones. My hands are tired.

I probably could have done it a little bit smarter, but since the zip code zones were broke up into a ton of different regions there wasn't much that could have been shortened or automated.

Thanks again for the help guys.

I bet if you post your code, minus all 1100 lines of zip codes, someone could help you optimize it better.

gwar3k1
Jan 10, 2005

Someday soon
I know your zipcodes are numeric but there has to be some grouping going on with the numbers. For example: YO24 - YO would be Yorkshire, 2 would be York itself, 4 would then be a district of York...

Is there a number patter you can exploit by using multiple selects with substr?

php:
<?
switch(substr(zip,0,2))
{
  case "01" // Alaska
  {
    switch(substr(zip, 2, 2))
    {
      case "01" // Somewhere in alaska
      {
        // etc.
      }
    }
  }
}?>
I'm not exactly well known for my optimized code by the way, so you may want to ignore me.

revmoo
May 25, 2006

#basta
It's for a pricing engine with several different 'areas' depending on your geographical region. Fortunately the areas are broad enough that I only needed to deal with the first three digits of the zip code. Several states were just one area so all I had to do was get the ranges for those, for example Utah was 84XXX, so that was really easy. A lot of states only have 10 or so different 3-digit prefixes to deal with.

I'm sure that the code could have been less than 1100 lines, but since there was a ton of small ranges, like 902-905, 907-915, etc etc etc it was easier to just put the exact numbers instead of trying to cover each range programatically.

I did want to ask about this piece of code, just to make sure I have no security issues:
code:
$input = $_POST["zip"];
$length = strlen($input);

function validateUSAZip($zip_code)
{
  if(preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code))
    return true;
  else
    return false;
}
if (validateUSAZip($input)) {
} else {
echo 'Please enter a valid 5-digit ZIP Code';
echo '<br /><br /><a href="/form.php">Go back</a>';
exit;
}
$firstthree = substr ( $input, 0, 3  );
$firstthree runs through the case statements to figure out what zone we're in and that's it. The variable is only used for that purpose and it is not stored or computed in any other way. Is this reasonably secure?

I'm not concerned with performance at all, as this is going to be a rarely used site function, probably used less than once a day. Also, I do realize that the zip code checker isn't 100% perfect, for example 00000 is accepted as valid even though it's not. I'll deal with that later on in the code.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

revmoo posted:

I did want to ask about this piece of code, just to make sure I have no security issues:
code:
$input = $_POST["zip"];
$length = strlen($input);

function validateUSAZip($zip_code)
{
  if(preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code))
    return true;
  else
    return false;
}
if (validateUSAZip($input)) {
} else {
echo 'Please enter a valid 5-digit ZIP Code';
echo '<br /><br /><a href="/form.php">Go back</a>';
exit;
}
$firstthree = substr ( $input, 0, 3  );
$firstthree runs through the case statements to figure out what zone we're in and that's it. The variable is only used for that purpose and it is not stored or computed in any other way. Is this reasonably secure?

I'm not concerned with performance at all, as this is going to be a rarely used site function, probably used less than once a day. Also, I do realize that the zip code checker isn't 100% perfect, for example 00000 is accepted as valid even though it's not. I'll deal with that later on in the code.

Just compare what they enter to a list of valid zip codes.

revmoo
May 25, 2006

#basta

fletcher posted:

Just compare what they enter to a list of valid zip codes.

Yeah I figured I'd do something like that. That list is incomplete though! Just off the top of my head I noticed it's missing Puerto Rico entirely.

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

:dukedog:

So I'm trying to come up with a way to get players to cat with each other while playing a game. I looked up some of those PHP/ajax/json scripts that are out for free but they all look like they'd kill my server if there were too many clients on.

Any suggestions for a lightweight chat system? And I likely don't want to use IRC because my host doesn't allow that and I need to force players to keep their assigned name in chat.

gwar3k1
Jan 10, 2005

Someday soon

drcru posted:

So I'm trying to come up with a way to get players to cat with each other while playing a game. I looked up some of those PHP/ajax/json scripts that are out for free but they all look like they'd kill my server if there were too many clients on.

Any suggestions for a lightweight chat system? And I likely don't want to use IRC because my host doesn't allow that and I need to force players to keep their assigned name in chat.

Could you use a java applet instead? Or frames for the chat screen and reload the frame with each post (and refresh every 30 seconds).

N.Z.'s Champion
Jun 8, 2003

Yam Slacker
I've got a PHP/MySQL app. Is there a way of bundling that with a WAMP server so that Windows users can download an .exe and install it?

The exe would need to set up a mysql user too, obviously.

DoctorScurvy
Nov 11, 2005
More of a passing curiosity, really

N.Z.'s Champion posted:

I've got a PHP/MySQL app. Is there a way of bundling that with a WAMP server so that Windows users can download an .exe and install it?

The exe would need to set up a mysql user too, obviously.
I would consider moving the project to XAMPP, which is portable by nature, then distributing the whole folder as one ZIP file.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

N.Z.'s Champion posted:

I've got a PHP/MySQL app. Is there a way of bundling that with a WAMP server so that Windows users can download an .exe and install it?

The exe would need to set up a mysql user too, obviously.

What sort of app are you making that users need to download and install all that extra stuff to use it? Seems like you may be introducing unnecessary security headaches for people. Is SQLite an option?

J. Elliot Razorledgeball
Jan 28, 2005
What's the general consensus on CakePHP? It's got a lot of pretty hooks for jQuery stuff and seems to be well documented. I've tried symfony but the learning curve just seems like too much for me.

Or Yii...that looks to be getting a lot of solid reviews lately.

J. Elliot Razorledgeball fucked around with this message at 05:21 on Mar 31, 2010

N.Z.'s Champion
Jun 8, 2003

Yam Slacker

fletcher posted:

What sort of app are you making that users need to download and install all that extra stuff to use it?
This one. It's just a conventional webapp but some people don't know how to set up a personal webserver/php/mysql so I was looking to automate some of the steps; hence the question.

fletcher posted:

Seems like you may be introducing unnecessary security headaches for people.
Yep, could be.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

N.Z.'s Champion posted:

This one. It's just a conventional webapp but some people don't know how to set up a personal webserver/php/mysql so I was looking to automate some of the steps; hence the question.

Yep, could be.

I think it's a cool idea but if you're not going to invest the necessary resources to securely host it yourself I would rewrite it as a desktop application. Having people running their own WAMP stack to host their financial data (even without any account identifiers) sounds like a scary scenario.

N.Z.'s Champion
Jun 8, 2003

Yam Slacker

fletcher posted:

I think it's a cool idea but if you're not going to invest the necessary resources to securely host it yourself I would rewrite it as a desktop application. Having people running their own WAMP stack to host their financial data (even without any account identifiers) sounds like a scary scenario.
I completely agree. Subaccounting is an app that I developed for myself and I'm not maintaining it anymore (it says that on the webpage). I'm only asking this for a few non-techy friends who want to try themselves. I'll set it up so that they need to manually start Apache each time and I've told them to use htpasswd so hopefully that's enough to keep it safe on a local network.

Thirteenth Step
Mar 3, 2004

Here's a bit of a mad one which i'm sure shouldn't bee too hard for somebody in here.

Im trying to set up a very quick demo on how SQL Injection works, I've never created an SQL Injection vulnerable form before (obviously) and i've been furiously pasting the common strings (1=1 and the like) into here and it's not working.

However, 1=1 is creating a true result, and my form isn't searching for something thats 'true' as far i can tell, its searching for num_rows to equal 1.

How would I go about injecting code into this form to allow access?

Sorry about the horribly set out code. :gonk:


code:
	<form action='' method='post'>
		Username: <input type='text' name='username'><br>
		Password: <input type='password' name='password'><br>
</p>
		<input type='submit' value='Log In'><input type='reset' value='Reset'>
	</form>
</html>
php:
<?php

session_start();

@$username $_POST['username'];
@$password $_POST['password'];

if ($username && $password)
{
$connect mysql_connect("localhost","MY_USERNAME","MY_PASSWORD") or die("Couldn't connect to database!");
mysql_select_db("MY_DATABASE") or die("Couldn't find DB!");

$query mysql_query("SELECT * FROM users WHERE username='$username'");

$numrows mysql_num_rows($query);

if ($numrows!=0)
{    
 while ($row mysql_fetch_assoc($query))
 {
    $dbusername $row['username'];
    $dbpassword $row['password'];
 }
 
 if ($username==$dbusername&&$password==$dbpassword)
 {
    $_SESSION['username']=$username;
    header('Location: members.php');
 }
 else
    echo "Incorrect Password!";
}
else
    die("User does not exist!");
}
else
    die("Please fill out the required fields!");
?>

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Thirteenth Step posted:

Here's a bit of a mad one which i'm sure shouldn't bee too hard for somebody in here.

Im trying to set up a very quick demo on how SQL Injection works, I've never created an SQL Injection vulnerable form before (obviously) and i've been furiously pasting the common strings (1=1 and the like) into here and it's not working.

However, 1=1 is creating a true result, and my form isn't searching for something thats 'true' as far i can tell, its searching for num_rows to equal 1.

How would I go about injecting code into this form to allow access?

Sorry about the horribly set out code. :gonk:


code:
	<form action='' method='post'>
		Username: <input type='text' name='username'><br>
		Password: <input type='password' name='password'><br>
</p>
		<input type='submit' value='Log In'><input type='reset' value='Reset'>
	</form>
</html>
php:
<?php

session_start();

@$username $_POST['username'];
@$password $_POST['password'];

if ($username && $password)
{
$connect mysql_connect("localhost","MY_USERNAME","MY_PASSWORD") or die("Couldn't connect to database!");
mysql_select_db("MY_DATABASE") or die("Couldn't find DB!");

$query mysql_query("SELECT * FROM users WHERE username='$username'");

$numrows mysql_num_rows($query);

if ($numrows!=0)
{    
 while ($row mysql_fetch_assoc($query))
 {
    $dbusername $row['username'];
    $dbpassword $row['password'];
 }
 
 if ($username==$dbusername&&$password==$dbpassword)
 {
    $_SESSION['username']=$username;
    header('Location: members.php');
 }
 else
    echo "Incorrect Password!";
}
else
    die("User does not exist!");
}
else
    die("Please fill out the required fields!");
?>


Your convoluted PHP is actually protecting you somewhat. If you really want to gently caress things up, try putting in usernames with fun stuff like this: aaa';DELETE FROM users WHERE 1 or aaa';UPDATE users SET password = 'z' WHERE 1;

What your code is doing in the event of a 1=1 "attack" would be to return ALL rows. Your crazy while loop then iterates over ALL of them, and at the end, $dbusername and $dbpass are set to the values of the last row returned form the query.

Also, your script is NOT "searching for num_rows to equal 1", it's looking for number of rows not 0 or FALSE.

A vulnerable script for your form would look like this:

php:
<?
session_start();

@$username = $_POST['username'];
@$password = $_POST['password'];

if ($username && $password)
{
 $connect = mysql_connect("localhost","MY_USERNAME","MY_PASSWORD") or die("Couldn't connect to database!");
 mysql_select_db("MY_DATABASE") or die("Couldn't find DB!");

 $query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
 if( mysql_num_rows( $query ) != 0 )
 {
  // hey it must have been a good log in!
  $_SESSION['username']=$username;
  header('Location: members.php');
 }

}
?>

Lumpy fucked around with this message at 16:13 on Mar 31, 2010

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Quick question, admittedly, I am a new web developer that hasn't mastered PHP yet but I can definitely get around it.

I am looking for a way to have Word documents converted to HTML or PDF or some type of readable form online and possibly cache it so every request doesn't convert the file every time.

Basically, I have the worst user base ever that can't even be bothered to turn Word documents into PDFs on their own.

I develop an intranet site for the company I work for and I need a way to read these Word documents off a network share that the users update.

Is there a good way of doing this?

Note: It is an Apache server running on Windows Server 2003.

Thirteenth Step
Mar 3, 2004

Lumpy posted:

Stuff

" Welcome to the management system ' or 'a'='a! "

:smug:

Thanks for the advice!

Munkeymon
Aug 14, 2003

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



IT Guy posted:

Quick question, admittedly, I am a new web developer that hasn't mastered PHP yet but I can definitely get around it.

I am looking for a way to have Word documents converted to HTML or PDF or some type of readable form online and possibly cache it so every request doesn't convert the file every time.

Basically, I have the worst user base ever that can't even be bothered to turn Word documents into PDFs on their own.

I develop an intranet site for the company I work for and I need a way to read these Word documents off a network share that the users update.

Is there a good way of doing this?

Note: It is an Apache server running on Windows Server 2003.

There are plenty of ways to do it, but I doubt they're all that easy:

http://www.informatik.uni-frankfurt.de/~markus/antiword/

Go do Office interop in .Net to pull out the text yourself (or make office print to a PDF printer)

Take your chances with this http://www.phpclasses.org/browse/package/3553.html.

rotaryfun
Jun 30, 2008

you can be my wingman anytime
Very basic issue that's driving me crazy.

Just inputting very basic data from a mysql query. However, this will not create the newline at the end.

php:
<?
$myFile = "download/report.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
while($row2 = mysql_fetch_array($resultsSELECT)) {
$stringData =  $row2['id'] . " | " . $row2['name'] . " | " . $row2['branch'] . "\n";
fwrite($fh, $stringData);
}
fclose($fh);
?>

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

rotaryfun posted:

Very basic issue that's driving me crazy.

Just inputting very basic data from a mysql query. However, this will not create the newline at the end.

php:
<?
$myFile = "download/report.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
while($row2 = mysql_fetch_array($resultsSELECT)) {
$stringData =  $row2['id'] . " | " . $row2['name'] . " | " . $row2['branch'] . "\n";
fwrite($fh, $stringData);
}
fclose($fh);
?>

Are you writing or reading in a Windows environment? if so, you have so use \r\n

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