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
Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

e: ignore this.

Something else was broken.

Acer Pilot fucked around with this message at 07:10 on Mar 23, 2012

Adbot
ADBOT LOVES YOU

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
When working with CodeIgniter, how in the world do I get form post variables to use in my application? $_POST isn't working, and neither is $this->input->post('');.

code:
<div>

<?
$this->load->helper('form');

if(isset($_Post['name']))
{
$quality = $this->input->post('quality');
$level = $this->input->post('level');
$name = $this->input->post('name');
$notes = $this->input->post('notes');
$gold = $this->input->post('gold');
$rmah = $this->input->post('rmah');
$tag = $this->input->post('tag');

echo '<p>' . $name . $level . $quality . '</p>';

if($quality != null && $name != null)
{
	$query = "INSERT INTO items_softcore (Quality, Level, Name, Notes, Gold, RMAH, Tag) 
        VALUES ('$quality', '$level', '$name', '$notes', '$gold', '$rmah', '$tag')";

	$this->db->query($query);

	$query = "INSERT INTO items_hardcore(Quality, Level, Name, Notes, Gold, RMAH, Tag) 
        VALUES ('$quality', '$level', '$name', '$notes', '$gold', '$rmah', '$tag')";

	$this->db->query($query);

	echo '<p>Added item: ' . $name . ' successfully.</p>';
}
}

// Build form
// Form action = Self
echo form_open();

$data = array(
              'name'        => 'quality',
              'value'       => 'Quality',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('Quality:', 'quality') . form_input($data);

$data = array(
              'name'        => 'name',
              'value'       => 'Item Name',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('Item Name:', 'name') . form_input($data);

$data = array(
              'name'        => 'notes',
              'value'       => 'Notes',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('Notes:', 'notes') . form_input($data);

$data = array(
              'name'        => 'gold',
              'value'       => 'Est. Gold',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('Est. Gold:', 'gold') . form_input($data);

$data = array(
              'name'        => 'rmah',
              'value'       => 'RMAH',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('RMAH Value:', 'rmah') . form_input($data);

$data = array(
              'name'        => 'tag',
              'value'       => 'Tag',
              'maxlength'   => '500',
              'size'        => '150',
			  'width'		=> '50%',
            );

echo form_label('Tag:', 'tag') . form_input($data);

// Submit
echo form_submit('submit', 'Submit Post!');
echo form_close();

?>

</div>

revmoo
May 25, 2006

#basta
I dunno I've used POST vars in CI without problem, but I know there's an input class that handles it as well, check those docs.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
if(isset($_Post['name']))

I don't know anything about Code Igniter but PHP is case-sensitive and the variable name is $_POST, not $_Post.

Also I hope $this->input->post() does some kind of sanitising of values for your database.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

Hammerite posted:

if(isset($_Post['name']))

I don't know anything about Code Igniter but PHP is case-sensitive and the variable name is $_POST, not $_Post.

Also I hope $this->input->post() does some kind of sanitising of values for your database.

Meh, I just changed everything to get and it worked. :psyduck:. I'm not very worried about pretty since it's a non-public page, so it works I suppose.

Those CI functions do sanitize the form data (for the most part).

qntm
Jun 17, 2009

Knyteguy posted:

Meh, I just changed everything to get and it worked. :psyduck:. I'm not very worried about pretty since it's a non-public page, so it works I suppose.

Those CI functions do sanitize the form data (for the most part).

If $_GET worked then your problem is that your form is using the wrong http method.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

qntm posted:

If $_GET worked then your problem is that your form is using the wrong http method.

Incorrect. The standard form class for code igniter has post as a default (and I verified this in the html source). I had to manually change the form to a get type, and then also change the post variables to get variables to get it to work. I have no idea why it didn't like the post vars.

Xik
Mar 10, 2011

Dinosaur Gum
Help me Goons. I'm playing around with Cakephp unit testing, it's version 2.1 so it uses phpunit. I'm familiar with phpunit and unit testing in general but have never worked with fixtures before.

From what I understand in cakephp the tests will use your test database settings to create a table, insert your fixture data, run the tests and then drop the table again. Is this correct?

When I run my tests I get "Base table or view not found: Table [table name] doesn't exist". I've tried syncing the test database from the main dev database which will create the correct tables and structure. If I then run the tests I get the same error and the table is gone. So I know it's using the correct connection and it is dropping the table but the tests aren't running and it won't create the table....

The Model Tests, Controller Tests and Fixtures were all baked (then later modified to include my tests) so the tests have all the correct fixture references for every relationship. What am I missing here? Is there something crucial I don't understand?

DaTroof
Nov 16, 2000

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

Knyteguy posted:

Those CI functions do sanitize the form data (for the most part).

$this->input()->post() does NOT sanitize for queries. You should either escape the values or use query binding (http://codeigniter.com/user_guide/database/queries.html).

klem_johansen
Jul 11, 2002

[be my e-friend]

Bloembak posted:

Facebook has completely migrated all of the FBML functionality to their Javascript SDK. You can find the docs about this sdk here: https://developers.facebook.com/docs/reference/javascript/

A more specific example about inviting friends (app requests) can be found here:
https://developers.facebook.com/docs/reference/dialogs/requests/

Blammo! Thanks.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Knyteguy posted:

Meh, I just changed everything to get and it worked. :psyduck:. I'm not very worried about pretty since it's a non-public page, so it works I suppose.

Those CI functions do sanitize the form data (for the most part).

It's not just about pretty - it's about common sense. If you're submitting something to enter it into a database you should be using POST. What Hammerite suggested will probably fix your issue - did you try it?

Also, as mentioned you need to either use the active record stuff (http://codeigniter.com/user_guide/database/active_record.html) built into Code Igniter, use query binding or manually sanitise those inputs, $this->input->post() won't sanitise it for use in queries.

revmoo
May 25, 2006

#basta
Something I am curious about--how do ActiveRecord implementations create properties based on DB columns? Do they use variable variables?

Deus Rex
Mar 5, 2005

revmoo posted:

Something I am curious about--how do ActiveRecord implementations create properties based on DB columns? Do they use variable variables?

I don't actually know, but I imagine it's a metaprogramming approach similar to the one used by Ruby's ActiveRecord (which uses method_missing)

http://www.php.net/manual/en/language.oop5.overloading.php#object.get

Fluue
Jan 2, 2008
I'm currently working on an event ticketing system for a small project and I've hit a hitch. One aspect of the project is allowing students to bring guests to events (up to 2). So what I've done is setup $_POST arrays (ie: <input type="text" name="fName[]" value="" /> ) that are in a form which is dynamically generated based on the how many guests the student is choosing to bring.

I'm having trouble getting both SQL queries to insert if there are two guests, however. It should count the number of queries generated from input (using a for loop), then insert each query.

Here's what I'm doing right now:

php:
<?
    for ($i = 0; $i <= $numGuests; $i++ ) 
    {
         
       $sql[] = "INSERT INTO `guestTickets` (`ticketNumber` , `CWID` , `fName` , `lName` , `phone`) VALUES ('{$_POST['tixNumber'][$i]}', '$cwid', '{$_POST['fName'][$i]}', '{$_POST['lName'][$i]}', '{$_POST['phone'][$i]}')";
            $num_inserts = count($sql);

            for($q =0; $q <=$num_inserts-1; $q++)
            {
            $query = mysql_query($sql[$q]);
            
            echo "<h2>Guest ticket(s) submitted successfully.</h2>";
            echo "<a href='index.php'>Return to home</a>";
            echo "</div>";
            }
?>
$sql was declared as an array earlier. Excuse the lack of PDO. Is there any way to correctly do this? Or should I scrap all of this and redo all my mysql queries as PDO?

Thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Scrap it all and use PDO. You are just begging to be hacked via SQL Injection if you are writing queries like that.

Also, no need for backticks in your query (the ` character).

When using for loops on arrays, keep it consistent (avoid the <=, $num_inserts-1, etc), this is what one expects to see 99% of the time:

php:
<?
$something = array("one", "two", "three", "four");
for ($i=0; $i<sizeof($something); $i++) {
    echo $something[$i]."\n";
}
?>
With PDO your operation would be something like:
php:
<?
$db = new PDO("mysql:host=localhost;dbname=my_database", "username", "password");
//prepare the insert statement outside of the loop, it can be re-used for each iteration
$insert = $db->prepare("INSERT INTO guestTickets (ticketNumber, CWID, fName, lName, phone) VALUES (:ticketNumber, :CWID, :fName, :lName, :phone");

for ($i=0; $i<$numGuests; $i++) {
    $insert->bindParam(":ticketNumber", $_POST["tixNumber"][$i]);
    $insert->bindParam(":CWID", $cwid);
    $insert->bindParam(":fName", $_POST["fName"][$i]);
    $insert->bindParam(":lName", $_POST["lName"][$i]);
    $insert->bindParam(":phone", $_POST["phone"][$i]);
    $insert->execute();
}
?>
Also be aware that if the user enters <script>alert('hello!')</script> as their first name, and you are displaying their name somewhere on the page, you need to handle that with htmlspecialchars.

Fluue
Jan 2, 2008
I wasn't sure the entire process for looping transactions was with PDO but now I'll just use that for the project.

Thanks!

Yossarko
Jan 22, 2004

I'm using PHP 5.4's new built in webserver with ChromePortable's KIOSK mode to distribute "offline" web applications to our clients with Windows. Basically, the client runs a .bat file that starts PHP -S and then launches ChromePortable -kiosk "localhost:8000" which runs the content.

All is good except that running PHP webserver starts a CLI with output and a "Hit ctrl-c to exit", and after closing the application the CMD window is still open.

Is there any way to launch the PHP web server silently ? It doesn't matter if it runs until the end of the windows session. Running php-win -S does not work.

Impotence
Nov 8, 2010
Lipstick Apathy
Just run a lightweight actual webserver, don't actually use the thing

Yossarko
Jan 22, 2004

OK I'm trying out XAMPP-Lite (http://xampplite.org). Thanks.

Fluue
Jan 2, 2008
Alright, I've been working on transition my above project to PDO but I keep hitting snags.

Why is this data not submitting to the DB when I run this after collecting all the input? I get no errors, but it doesn't submit the actual data.

http://pastebin.com/DU4ZJQiV

It connects to the db just fine, but no data shows up.

Fluue fucked around with this message at 23:37 on Apr 3, 2012

mewse
May 2, 2006

Fluue posted:

Alright, I've been working on transition my above project to PDO but I keep hitting snags.

Why is this data not submitting to the DB when I run this after collecting all the input? I get no errors, but it doesn't submit the actual data.

http://pastebin.com/DU4ZJQiV

It connects to the db just fine, but no data shows up.

quote:

$query_submit = mysql_query($sql) or die("Could not complete.");

^^-- you've still got this line in there. $sql is a null var because the definition is commented out

Fluue
Jan 2, 2008
Still not passing the data to the database :\ I'm not getting errors though. It says the processes completed successfully, but when I check the db I see nothing.

Sab669
Sep 24, 2009

Here's a pretty simple question, I've this code:

code:
<form action="." method="post">
<input type="hidden" name="action" value="delete_product" />

<?php
$products = get_products();
foreach($products as $product)
{
echo "<tr>";
echo "<td><input type='hidden' name='pCode' value='" .$product['productCode'] . "'/>" .$product['productCode'] . "</td>";
echo "<td>" .$product['name'] . "</td>";
echo "<td>" .$product['version'] . "</td>";
echo "<td>" .$product['releaseDate'] . "</td>";
echo "<td><input type='submit' value='Delete' />";
echo "</tr>";
} ?>
Then back on index I've got this:
code:
else if($action == 'delete_product')
{
	$pCode = $_POST['pCode'];
	$row_count = delete_product($pCode);
	include('product_list.php');
	echo $row_count . " Rows deleted.";
}
$pCode is assigned the value of the last item in the table, regardless of which Delete button I click, and I'm not quite sure why.

*I omitted some HTML in the first block.

Superdawg
Jan 28, 2009
I could be way off on this. But there's no way to determine which pCode is associated with the 'submit' you're sending.

I'm not sure how it is recommended to do, but a quick test to see, would be to change the value of your submit tag to have name="Delete-$product['productCode']" and then you would have to find $_POST['Delete-(.*)'].

Edit: Either that or do a new form for each row, but I think that's completely wrong. But it would work.

revmoo
May 25, 2006

#basta
I'd probably do it w/ jQuery honestly. just add a handler to each delete button and then have it search with before() or closest() for the element value.

Something like this (Probably won't work as-is I'm doing this from memory):

code:
jQuery(document).ready(function() {
    jQuery('.deleteButton').click(function() {
        the_id = jQuery(this).parent().find('.pcode').val();
        jQuery('#idToDelete').val(the_id);
        jQuery('#deleteSubmit').submit();
    });
});

Create one hidden field for the final value and leave it blank:
<input type="hidden" id="idToDelete" value="" />

(add class .deleteButton to submit and .pcode to pcode for this code to work)
(add id #deleteSubmit to the form)
(change submit button to a regular button)
Like I said, this code most likely has some flaws, probably in the selector targeting, but the basic idea should work.

revmoo fucked around with this message at 06:10 on Apr 7, 2012

Sab669
Sep 24, 2009

Superdawg posted:

I could be way off on this. But there's no way to determine which pCode is associated with the 'submit' you're sending.

I'm not sure how it is recommended to do, but a quick test to see, would be to change the value of your submit tag to have name="Delete-$product['productCode']" and then you would have to find $_POST['Delete-(.*)'].

Edit: Either that or do a new form for each row, but I think that's completely wrong. But it would work.

Yea, that was my guess as to what the issue was. The last thing pCode is what it would pull, but I didn't know how to dynamically name a control and then pull that on the next page.

PleasantDilemma
Dec 5, 2006

The Last Hope for Peace
Has anyone here developed plug-ins or modules for any of the popular CMS systems in PHP? Which is the easiest/fastest to develop for? I'm going to need to make a custom app that will also do CMS stuff. I'm wondering if it would be a better idea to extend durpal/joomla/WordPress or just add the CMS features to what I need to make.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
We're running into speed issues with some of our more complex and time-sensitive pages (Customer Service can't very well keep someone on hold just because their Firefox is spinning), and it was suggested to me to try stored procedures. That way, at least, it's not sending huge queries across the network and it could actually save some time. Is there any general school of thought on, in PHP, whether it's better to use stored procedures or just have the queries in code?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Stored procedures were a performance boost about two decades ago in the databases of the time. It was possible for a query planner to spend a much longer time examining the procedure ahead of time and get the order of operations just right.

Modern databases on modern hardware have much more sophisticated query planners -- yes, even MySQL -- which effectively negate the performance gain provided by stored procedures.

Whoever mentioned stored procedures to you as a performance boost hasn't worked with modern practices.

Your time and effort are going to be much better spent performing real profiling of your code to find out what's actually wrong. Give xhprof a try, it was built by the Facebook folks and is designed to run in production with almost no impact.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Not only do you really need to look into where your queries are slowing things down (maybe using prepared statements if you're not already), but stored procedures are a pain to debug and unit test compared to regular code.

In our codebase we have some stored procedures that are over 1000 lines long (that go on to call other stored procs in other schemas) and debugging them is a complete nightmare.

Edit: I will use stored procedures mostly as helpful one line functions or as trigger functions. For example, if I want a value in a field to always be uppercase, I can have an insert and update trigger to always change that value to uppercase so that way the code doesn't have to worry about it or if someone manually updates the record, the data is kept consistent.

musclecoder fucked around with this message at 16:54 on Apr 9, 2012

Sab669
Sep 24, 2009

So I'm new to PHP, this is the second course I'm taking that teaches it. The first one was an intro class and we just used Notepad++. For this one, we're using NetBeans instead. Does Ctrl-S really close the open file, or am I fat-fingering something every loving time and it closes it after saving it? This is truly the most frustrating thing as I habitually hit Ctrl-S every so often because these school computers are terrible and like to shut down at random.

e; yay for learning new languages. Just bashing my head against the keyboard for 20 minutes wondering why
<input type="text" name="cFName" value="<?php $customer['firstName']?>"/>
wasn't working. Didn't realize you needed to echo it out. I kind of felt like since I was already assigning the textbox's value I didn't need to echo it out. Seemed redundant.

Sab669 fucked around with this message at 00:59 on Apr 10, 2012

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Also, unless the value $customer['firstName'] has already been thoroughly sanitized or you're using some very good templating system that will auto-sanitize it, don't just echo out $customer['firstName']. Cross-side-scripting attack waiting to happen.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
We seem to be running into a race condition with session_regenerate_id(). It's called on every page request, so far as I can tell. When people click too fast, I'm guessing it's called twice in quick succession and the thing craps out. The user ends up with two cookies and the login can't comprehend what's going on.

I was thinking, okay, remove it from every request, just run it when security level changes; that's what the internet suggests.

However, we are a health care company and need to be ubersecure. Am I opening myself up attacks by not regenerating on every request? And, if so, how do I solve this problem?

Hammerite
Mar 9, 2007

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

Golbez posted:

We seem to be running into a race condition with session_regenerate_id(). It's called on every page request, so far as I can tell. When people click too fast, I'm guessing it's called twice in quick succession and the thing craps out. The user ends up with two cookies and the login can't comprehend what's going on.

I was thinking, okay, remove it from every request, just run it when security level changes; that's what the internet suggests.

However, we are a health care company and need to be ubersecure. Am I opening myself up attacks by not regenerating on every request? And, if so, how do I solve this problem?

I am an amateur at this, but if I understand correctly, the main reason why you might regenerate the ID at every request is that that way, if someone (say) emails a friend with a URL that has the session ID appended, they won't see the page/won't get access to the first user's session because the session ID will have changed. Kind of an edge case. (I have occasionally been on websites and seen one-off pages where a PHPSESSID did appear in the URL, despite not having disabled cookies and the PHPSESSID not appearing on other pages; I don't know why that happens, I just put it down to "lol PHP".)

I am happy to be corrected if my understanding of this is flawed.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

Golbez posted:

We seem to be running into a race condition with session_regenerate_id(). It's called on every page request, so far as I can tell. When people click too fast, I'm guessing it's called twice in quick succession and the thing craps out. The user ends up with two cookies and the login can't comprehend what's going on.

I was thinking, okay, remove it from every request, just run it when security level changes; that's what the internet suggests.

However, we are a health care company and need to be ubersecure. Am I opening myself up attacks by not regenerating on every request? And, if so, how do I solve this problem?

Are you appending the session ID to every URL or just using the cookie? If you're just using the cookie, why are you regenerating the session on every request?

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

musclecoder posted:

Are you appending the session ID to every URL or just using the cookie? If you're just using the cookie, why are you regenerating the session on every request?
Cookies only. And why? Don't know. I inherited this. I assume whoever wrote it thought it was more secure. We can't be too paranoid about security after all, right?

Hammerite posted:

I am an amateur at this, but if I understand correctly, the main reason why you might regenerate the ID at every request is that that way, if someone (say) emails a friend with a URL that has the session ID appended, they won't see the page/won't get access to the first user's session because the session ID will have changed. Kind of an edge case. (I have occasionally been on websites and seen one-off pages where a PHPSESSID did appear in the URL, despite not having disabled cookies and the PHPSESSID not appearing on other pages; I don't know why that happens, I just put it down to "lol PHP".)
My understanding is:

1) I log in to the server. I get a session ID.
2) I send you a link to log in to same server with that session ID. Note that this requires you to be an idiot.
3) You log in, and now we have the same session ID.
4) Meaning I can now control your account.

If you run session_regenerate_id() on login, when you log in, you'll get a new session ID, and not the one that I gave you, thus the fixation fails. However, I don't think there's any need to run it on every request.

Hammerite
Mar 9, 2007

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

Golbez posted:

My understanding is:

1) I log in to the server. I get a session ID.
2) I send you a link to log in to same server with that session ID. Note that this requires you to be an idiot.
3) You log in, and now we have the same session ID.
4) Meaning I can now control your account.

If you run session_regenerate_id() on login, when you log in, you'll get a new session ID, and not the one that I gave you, thus the fixation fails. However, I don't think there's any need to run it on every request.

But if I am logged in, and I send you a link that contains my session ID, that too lets you in on a session from which you can control my account, though it requires me to inadvertently set up the situation rather than you to intentionally do so.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Hammerite posted:

But if I am logged in, and I send you a link that contains my session ID, that too lets you in on a session from which you can control my account, though it requires me to inadvertently set up the situation rather than you to intentionally do so.

And, if the website regenerates session IDs when they log in, they will get a new session ID, and then when I click with my old session ID it will ask me to relogin. Crisis averted.

Hammerite
Mar 9, 2007

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

Golbez posted:

And, if the website regenerates session IDs when they log in, they will get a new session ID, and then when I click with my old session ID it will ask me to relogin. Crisis averted.

But unless I misunderstand, they won't log in, will they? They'll just join in on a session that's already logged in.

Adbot
ADBOT LOVES YOU

Sab669
Sep 24, 2009

musclecoder posted:

Also, unless the value $customer['firstName'] has already been thoroughly sanitized or you're using some very good templating system that will auto-sanitize it, don't just echo out $customer['firstName']. Cross-side-scripting attack waiting to happen.

Could you elaborate on this? Basically what the page was doing was auto-populating a form with that user's information from the database when they click to view their own profile for editing it. Also, as far as sanitizing input, everything is done through prepared statements.

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