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

Cad_Monkey2 posted:

Should I dismiss the idea of passing data through multiple hidden values or should I go through sessions?
If I were doing a multipage form, I would strongly recommend sessions. In the mean time, do either of these work?

php:
<?php
echo "<input type='hidden' name='address_line1' value='".$address_line1."' />";
?>
Or this? (which I would recommend since using echo statements to output HTML produces really lovely code)

php:
<?php
// code
?>
<input type="hidden" name="address_line1" value="<?php echo $address_line1?>" />
<?php
// more code
?>
Get Firebug and turn on the Net console so you can see what fields get sent when you post.

Zorilla fucked around with this message at 20:46 on Jan 26, 2009

Adbot
ADBOT LOVES YOU

Zorilla
Mar 23, 2005

GOING APE SPIT

Cad_Monkey2 posted:

Do you mean it produces lovely HTML code or just hard to read php code?

Both. You end up with a whole lot of the word "echo" in your PHP and the HTML output likely won't be tabbed properly, and if you didn't litter your code with "\n" all over the place, the output will likely all on one line too.

If you want to assign large blocks of HTML to variables, either use output buffers or heredoc statements (I recommend the first since it will keep your HTML context highlighted in most editors).

Zorilla fucked around with this message at 14:04 on Jan 27, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Golbez posted:

When I catch an Exception, doesn't the rest of the program continue to execute?

I generally see exceptions handled when one of the possible outcomes of the function you're using is having it throw an exception. For instance, maybe you're using a function that reads a file or makes a connection, but throws an exception when it fails. You'll want to handle each of these situations since things don't work perfectly all the time in the real world. If a file can't be read or a connection can't be made, it's much better to give the user a friendly error message rather than having it puke right where the exception happens.

In my amateurish opinion, if you're writing object methods, it's probably up to your judgment if you want it to either return false, present a warning, or cause a fatal error.

Zorilla fucked around with this message at 03:29 on Jan 30, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

agscala posted:

I want to make a website that would take an RSS feed, parse the information and do things like notify users when a specific event occurs so they wouldn't need to wade though a bunch of stuff they don't want. What libraries would be good for doing something along these lines?

Parse XML? SimpleXML or DOMDocument.

Zorilla
Mar 23, 2005

GOING APE SPIT

royallthefourth posted:

I don't know what exactly is causing that, but if I was typing it then it would look like
code:
DELETE FROM spaces.stores st WHERE st.id = 4
I wish I could provide a better explanation, but your syntax just looks wrong to me.

In the infinite genius of how PHP parses things, it's probably totally unaware of the "st" alias until it reaches "spaces.stores AS st", which is why royallthefourth's syntax works instead.

Zorilla
Mar 23, 2005

GOING APE SPIT
Yeah, thinking about it again, I should have realized I was waaay off.

Zorilla
Mar 23, 2005

GOING APE SPIT

Darrish posted:

Sorry for the wall of code.

Use [php] for code blocks. I can't read what you posted as it appears now.

Zorilla
Mar 23, 2005

GOING APE SPIT

Jo3sh posted:

Clearly, then, this creates a series of buttons whose names are unique. How can I pass that unique string to removebeer.php?

Rrraaagh echo statements for HTML! A pet peeve of mine. Any reason you're not doing this?

php:
<?php
// snip the part where I connect to the database and retrieve the table
?>
<form name="form1" method="post" action="removebeer.php">
    <table border="1">
        <tr>
            <th>Brewer or Brewery</th>
            <th>Name of Beer</th>
            <th>Size</th>
            <th>GUID</th>
        </tr>
<?php while($row mysql_fetch_array($result)) { ?>
        <tr>
            <td><?=$row['brewer']?></td>
            <td><?=$row['name']?></td>
            <td><?=$row['size']?></td>
            <td><input type="submit" name="<?=$row['guid']?>" value="Remove this Beer" /></td>
        </tr>
<?php // while ?>
    </table>
</form>
By the way, when fixing your code, I also noticed you're looping the form over and over again. That can't be good.

Zorilla fucked around with this message at 10:06 on Feb 15, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Golbez posted:

Not necessarily. If he wanted a distinct submit button for each line, creating a new form for each line is the way to do it, and so far as I can tell has no deleterious effects. Now, sure, your method works too, since the value is included in the name of the submit button, but it doesn't work if each row had an editable field or what not.

One of the things I meant that it was invalid HTML to put <form> tags inside <table>. You either have to start and stop them outside <table> or put them inside <td>.

Besides, it's still bad practice to use multiple forms on a page where all the information looks like it belongs to one form. What happens when you edit information on one row, then hit Submit on another? You lose the other row. Not good.

If he were to end up using text input fields later on like you brought up, that's when he should start considering using arrayed input names like description[somenumber] and checkboxes for deletion instead.

Zorilla fucked around with this message at 20:28 on Feb 15, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

KuruMonkey posted:

Got any rational reason behind having that pet peeve?

Since my preference runs the exact opposite to yours for most involved html rendering, I'd be interested if there was an actual reason to do things one way rather than the other; I'm not aware of a reason using echo is 'wrong'?
I'm surprised anyone has to ask. Look at Jo3sh's code, then look at mine. Which is easier to look at?

Using echo statements:
  • Produces lots of code garbage that clutters up HTML like quotation marks, escape characters, \n, semicolons, the word "echo" all over the place, etc.
  • Doesn't color-code the HTML in editors like Notepad++, TextMate, Dreamweaver, etc.
  • You're probably not tabbing the output or using line breaks at the end of each string, so you end up with poo poo like <table><tr><td>Poop</td><td><table><tr><td>Holy poo poo a table within a table</td></tr></table></td></tr></table> when you view source
Really, MVC code is best, but for projects way too small for frameworks like Zend or CodeIgniter, decent output templating is still strongly encouraged even if there is processing in the same file. Someone may want to edit the layout in the future and it's a real bitch to do that if everything is an echo statement.

Zorilla fucked around with this message at 20:31 on Feb 15, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

KuruMonkey posted:

(thats a Joomla view, by the way).

Yeah, that's when things get a little hairy, though I really don't see how using echo statements does anything but exacerbate this problem. I'm not sure your example is very fair since it exaggerates the problem by cramming a lot into a small space. No wonder you can't read it. It gets a lot better if you tabs things sanely:
php:
<?php
if (
    $canEdit ||
    $this->params->get('show_title') ||
    $this->params->get('show_pdf_icon') ||
    $this->params->get('show_print_icon') ||
    $this->params->get('show_email_icon')
    ) {
?>
<table class="contentpaneopen<?=$this->params->get'pageclass_sfx' )?>">
    <tr>
<?php
    if ($this->params->get('show_title')) {
?>
        <td class="contentheading<?=$this->params->get'pageclass_sfx' )?>" width="100%">
<?php
        if ($this->params->get('link_titles') && $this->article->readmore_link != '') {
?>
            <a href="<?=$this->article->readmore_link?>" class="contentpagetitle<?=$this->params->get'pageclass_sfx' )?>">
                <?=$this->escape($this->article->title)?>
            </a>
<?php
        } else {
?>
            <?=$this->escape($this->article->title)?>
<?php
        }
?>
        </td>
<?php
    }
 ?>
<?php
    if (!$this->print && $this->params->get('show_pdf_icon') {
?>
        <td align="right" width="100%" class="buttonheading">
            <?=JHTML::_('icon.pdf',  $this->article$this->params$this->access)?>
        </td>
<?php
    }
?>
</table>
<?php
}
?>

There. Now I have a pretty good idea what's going on with just a glance. Notice how I'm putting each <?php and ?> on a new line. This way, the indentation for PHP and HTML stay independent of one another. I really recommend doing it this way for documents this large. Tabs never end up in the right spot if you don't.

I build and edit WordPress templates all the time, and this is about as complex as it gets. The few times I've messed with Joomla were no different. If things get any more complicated than this, you really should consider splitting up the views into multiple templates as its layout is probably far too dynamic for just one. Also consider preparing variables into cleaner objects/arrays first that get used in the view portion of the code (I know this usually isn't an option in CMSes like this where things like $this->params->get('link_titles') have known meanings to designers and $output["title"] may not).

If you are totally against PHP templating for certain situations, I still recommend exploring heredoc for outputting large blocks of HTML with little clutter. I think it still lets you inject variables into them like echo "words word $string words"; would, so it's still somewhat suitable for templating.

Zorilla fucked around with this message at 01:12 on Feb 17, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

KuruMonkey posted:

I'm not looking to change for any reason that resolves to 'person X thinks it looks better'. I was asking if there was a functional/optimisation reason to do things the other way I wasn't aware of.

If there ain't one, I'll keep on truckin'
That's kind of why I broke out into a bullet list of reasons why I think it's better. It's my opinion that how the code looks has everything to do with practicality and readability.

For me, separating the control logic and the view as much as possible is pretty important. However, I've seen instances where forms or sections of pages get assigned to variables and then get used in simplistic templates. This sounds closer to the approach you prefer and is also reasonable.

Definitely not looking for a flame war, but I was curious to see why somebody would use code constructs designed to output text line-by-line for entire pages for reasons other than inexperience, carelessness, or worse, malice.

KuruMonkey posted:

Edit; I wonder if its that my background is programming->websites not websites->programming? Is yours the opposite? Or is that irrelevant? I'm just thinking that coming from "cout >> blah >> blah >>endl;" for hundreds of lines might color what is 'readable' for output code, or rather that lines upon lines of printf("%s\n", name); is just what I'm used to / expect
It could be- I can see why some habits would have to be relearned if you're suddenly dealing with whole HTML pages instead of a few lines at a time written to a console. Since this is PHP, I rely heavily on the templating system, but even if I were to move on to Python or something else with no built-in template system, templates are usually still the answer because somebody will have ported Smarty (or similar) to whatever you're using.

Zorilla fucked around with this message at 02:26 on Feb 17, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT
Heh, so basically what I said already (except for Allman-style indentation)

Zorilla
Mar 23, 2005

GOING APE SPIT
Couldn't you just use in_array()

php:
<?php
$stuff $_POST['stuff'];
?>
<!-- start of form -->
<?php while ($row mysql_fetch_assoc($queryresults)) { ?>
    <input type="checkbox" name="stuff[]" value=<?php echo $row['information']; ?>"<?php if (in_array($row['information'], $stuff)) { ?> checked="checked"<?php ?> />
<?php ?>
<!-- end of form -->

Zorilla fucked around with this message at 03:18 on Feb 20, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Golbez posted:

Then Zorilla may have the solution for both of us, seems much more 'pure', but that's assuming in_array is more efficient than a foreach. Which I'd have to assume it is.

People in this thread seem to be way too obsessed with the performance of small bits of code. By the time an application is big enough for optimizations to matter, the database will always, always, always be your performance bottleneck, not some loop or echo statement that could be 0.0000000018 seconds faster if done a certain way.

Zorilla
Mar 23, 2005

GOING APE SPIT

Tots posted:

Is that the security problem you were talking about? If not then I'm not sure what it is. I'll try to think over a way to fix this, and if I can't I'll be back here. :)
The problem is that you've just built a front end for anybody on the internet to access files on your web server with the same permissions your web server user account/group has. Even if there were a way to limit access to just files inside the document root, there's still the possibility of being able to print out raw PHP scripts or other files with sensitive information like database usernames and passwords.

I'm not sure there's a good way to do exactly what you're doing. Any file management I've seen in PHP applications (such as WordPress) involves presenting you with a list of files and abstracting the input it expects back.

By abstracting, I mean that even if you're given just a checkbox or a delete button or something, those parts of the form never reference the name of a file directly because that can be tampered. Instead, it could be called something like "delete[]". If "delete[5]" gets checked, for instance, it's up to the program to figure out that the 5th checkbox is associated with file you intend to delete.

Edit: I got carried away and made an example (totally untested):
php:
<?php

$file_path dirname(__FILE__) . "/safe_directory";

if ( !file_exists($file_path) ) {
    $error "The path &quot;".$file_path."&quot; could not be found.";
} else if ( !is_writable($file_path) ) { // a bit unreliable in Windows. Consider downloadig the is_really_writable() script.
    $error "The path &quot;".$file_path."&quot; could not be opened for writing. Please check file permissions.";
} else {
    
    $file_list glob($file_path);

    if ( isset($_POST["submit"]) && is_array($_POST["delete"]) ) {
        for ($i 0;$i count($_POST["delete"]);$i++) {
            if ($_POST["delete"][$i] != "") {
                unlink($file_path."/".$file_list[$i]);
            }
        }
        $message "File(s) deleted.";
    }
    
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<title>File Deleter</title>
<style type="text/css">
table {margin: 0 auto 1em;}
table td {border: 1px solid #000;}

.message, .error {padding: 10px;text-align: center;}
.message {background-color: #cdc;border: 1px solid #bca;}
.error {background-color: #fcc;border: 1px solid #faa;}
</style>
</head>
<body>

<?php
if ($error) {
?>
<p class="error"><?php echo $error?></p>

<?php
}

if ($message) {
?>
<p class="message"><?php echo $message?></p>

<?php
}

if (!$error) {
?>
<form name="files" action="<?php echo basename(__FILE__); ?>" method="post">
    <table>
<?php
    foreach ($file_list as $file) {
?>
        <tr>
            <td><?php echo $file?></td>
            <td>
                <input type="checkbox" name="delete[]" id="delete[]" value="Delete" />
                <label for="delete[]">Delete</label>
            </td>
        </tr>
<?php
    }
?>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Delete Selected" /></td>
        </tr>
    </table>
</form>
<?php
}
?>
</body>
</html>

Zorilla fucked around with this message at 23:37 on Feb 22, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Tots posted:

All I want is a listing of files in a directory.

...

Can someone give me a hint?
Way late, I know, but this is much easier than others have demonstrated:
php:
<?php

$list glob('/home/thetotsn/public_html/BunnyPics/');

foreach ($list as $file) {
    echo $file."<br />\n";
}

?>

Zorilla fucked around with this message at 00:34 on Feb 24, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Tots posted:

Does anyone know how to search directories other than the current with glob?

I see a lot of code examples so far, but am I missing something in assuming the solution is much simpler than what I'm seeing others post?

php:
<?php

$files glob("BunnyPics/{*.gif,*.jpg,*.jpeg,*.png}"GLOB_BRACE);
$selected_image rand(0count($files));

?>
<img src="BunnyPics/<?php echo $files[$selected_image]; ?>" alt="" style="margin: 0 auto;" />
If you need recursive file listings like gibbed seemed to be doing, include this function and use it instead (pulled from the comments section of glob() in php.net)
php:
<?php

function rglob($pattern='*'$flags 0$path='') {
    $paths=glob($path.'*'GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT);
    $files=glob($path.$pattern$flags);
    foreach ($paths as $path) { $files=array_merge($files,rglob($pattern$flags$path)); }
    return $files;
}

?>

Zorilla fucked around with this message at 00:26 on Feb 26, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

gibbed posted:

Yeah, what I was doing avoided having to define a function (and would work with any amount of subdirectories, where a recursive function would hit the stack limit eventually).

By stack limit, you mean the number of functions running simultaneously, right? One would think you'd hit the limit of the filesystem much sooner than you'd run out of recursions. I can't think of any situation where you'd go 255 directories deep looking for things (or is this limit much lower? I can't find any information about it on Google)

Zorilla fucked around with this message at 00:56 on Feb 26, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

This is what I have so far.
Can anyone point me to a method to do what I want to do? I'd love for it to be neat and use AJAX (which I also know nothing about) so the page isn't autorefreshing all the time.
You can either do what my cable modem diagnostics page does and use meta refresh tags in the HTML head (which is really annoying and makes nonstop clicking noises in IE) or look into jQuery for really simplified AJAX calls. I made a sloppy example:

php:
<?php
mysql_connect(".""..""...") or die(mysql_error());
mysql_select_db("METERDB") or die(mysql_error());

$result mysql_query("SELECT kwnowdsp, VrmsNowDsp FROM meter ORDER BY ID DESC LIMIT 1;");
$row mysql_fetch_array$result );

if ($_GET["ajax"] == "true") { // Simplified AJAX response
?>
<p>Current Usage: <?php echo $row['KWUsage']; ?><br />
Current Voltage: <?php echo $row['VRMS-Usage']; ?></p>
<?php
} else { // Full synchronous response
?>
<!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>
<title>Meter</title>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="info">
    <p>Current Usage: <?php echo $row['KWUsage']; ?><br />
    Current Voltage: <?php echo $row['VRMS-Usage']; ?></p>
</div>
<script type="text/javascript">
//<![CDATA[
setInterval(function() {
    $.ajax({
        type: "GET",
        url: "<?php echo basename(__FILE__); ?>",
        data: "ajax=true",
        success: function(response) {
            $('#info').html(response);
        }
    });
}, 10000); // Every 10 seconds
//]]>
</script>
</body>
</html>
<?php
}
?>

More jQuery help can be found here. I definitely think it's the way to go, especially if you're going to be doing charts.

Zorilla fucked around with this message at 04:19 on Mar 8, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

Thanks for your example, but it's not working; it's not refreshing.

Remember, I'm a complete newb when it comes to this, how can I troubleshoot what the problem might be?

Thanks again.

I do have jquery installed in js/jquery.js; its a symlink to the real version I downloaded.

Open Firefox's error console. Clear the errors and watch what comes in when you refresh the page. I never tested my example, so it could be full of typos. Ignore "Error in parsing value for property 'filter'" if you see it. jQuery just does that sometimes for some reason.

Also, on the line that says url: "<?php echo basename(__FILE__); ?>", is the resulting output correct? i.e., if your page is index.php, does that line say url: "index.php" when you view source?

edit: I just found and fixed a missing comma, so yeah, full of typos. All it takes is something like this for Javascript to completely stop, so if something isn't working, check for fatal errors first.

Zorilla fucked around with this message at 23:22 on Mar 7, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

nitrogen posted:

Rock on, I'm closer. It refreshes once, but then quits. NOthing in the error console when it does.
EDIT: I got it working by removing the ajax test at the top, and just using the jquery bits at the bottom. As I progress with this project, I'm sure I'll have more stupid questions. I appreciate your patience so far.

Oops, I used setTimeout when I should have used setInterval. I was cribbing from old code of mine where I was calling setTimeout recursively to get something to run on an interval instead (needed to reset the timer when the user clicked something). This is why it was only updating once. I'll change my example.

When you said you got rid of the ajax test, you mean the line that says if ($_GET["ajax"] == "true")? If so, I'm not sure I'm following. The idea was to call index.php?ajax=true, and it would return just the part inside <div id="info">, and then only that section would get updated.

Zorilla fucked around with this message at 04:25 on Mar 8, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT
Also, constants are almost always in all-caps.

cannibustacap posted:

What is the best way to detect if the end-user is using IE within PHP (not the html trick, but just PHP)

I am doing this so far

if (stristr((string)$_SERVER['HTTP_USER_AGENT'],'MSIE')) {...}

Sounds about right. This is what Google tells me, and it looks like it's functionally identical:
php:
<?
if (preg_match("/MSIE/i", $_SERVER["HTTP_USER_AGENT"])) {
    // stuff
}?>

Zorilla
Mar 23, 2005

GOING APE SPIT

duck monster posted:

Hmm. Maybe my regex question needs a thread

This subforum has regexes coverered too. Post here and somebody should be able to help.

Zorilla
Mar 23, 2005

GOING APE SPIT

KarmaticStylee posted:

Question: Have any of you used any affordable shopping cart systems that are not opensource (Zen Cart, osCommerce)? If so, which would you recommend?
Shopp is probably your best bet if you want to avoid really confusing templates and want integration with WordPress. I've actually been beta testing it since December. Avoid WP e-Commerce; it's free, but it's buggy and incredibly badly coded. We actually moved from WP e-Commerce to Shopp because it is designed as a replacement for it (and so did a lot of other people, as you'd find out if you hit up the Shopp forums).

Zorilla fucked around with this message at 23:48 on Mar 17, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT
I'm not sure the QSA flag works as expected when you're already manually rewriting into a query string. I don't too regexes very often, so I don't know if/how well this would work:

code:
RewriteRule ^(.*)\?(.*)$ index.php?urlVariables=$1&$2
If you wanted to request page.html?webmaster_id=2165&track=TRACK, this should rewrite to index.php?urlVariables=page.html&webmaster_id=2165&track=TRACK

Zorilla fucked around with this message at 00:29 on Mar 18, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Sylink posted:

What is the common way to set up a dynamic page with php? By this I mean I have an index.php which contains the basic layout and I have the content in separate php files.


I have seen where you can use the page variable and switch statements but I can't get it to work right. If this question is too long and anyone knows a good tutorial/resource on it I would take that.


In this case I have form included on the index page. If submitted it queries a database and returns some data. I want the search result to appear in the same html template basically.

Most people use a header.php and footer.php and include them at the top and bottom of each file. I usually do this instead because it's a little more flexible.

Zorilla
Mar 23, 2005

GOING APE SPIT

Corla Plankun posted:

I am making a really ghetto shoutbox as we speak. It is basically the least sanitized code in history. All I intend to do with it is input something, save it to a text file, and echo it back on the same page. OBVIOUSLY this is about as secure as spreading my rear end cheeks apart with both hands, but is there any other reason why I shouldn't do this?

It's probably not that bad. Here is my assessment:
  • If you read the file in by using include() or require(), the text file gets interpreted as code. Not good, as you can imagine. Using fopen(), fread(), etc. is fine.
  • You will need to use htmlspecialchars() when preparing output to prevent XSS attempts or users breaking HTML.
  • Since this has controlled access, you'll probably want to keep the text file from being served over the web by using an .htaccess rule

Zorilla fucked around with this message at 00:14 on Mar 25, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

eHacked posted:

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

I couldn't help myself:

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

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

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

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

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

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

Zorilla
Mar 23, 2005

GOING APE SPIT

duz posted:

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

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

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

Zorilla
Mar 23, 2005

GOING APE SPIT

Sylink posted:

Any reason to this? I can only imagine its restricted name related or something, its very odd.

This question is probably 90% jQuery and 10% PHP. I think you might have your arguments set up wrong for jQuery.post()

php:
<?php
//files to include, will later link to only a master file listing all includes.
include('C:\wamp\www\config\classDB.php');
include('C:\wamp\www\config\databaseconfig.php');

$db = new dbLib();

/*$db->get_dbinfo($dblocation,$dbuser,$dbpasswd);
$db->connect();
$db->select_DB("cookbook");*/

?>
<html> 
<head>
<title>CookBook</title>

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    $("#login").click(function() {
        var login.username = $("#username").val();
        var login.password = $("#password").val();
        
        $.post("serverTime.php", login, function() {
                alert("oval office");
        });
        
        return false;
    });
});
//]]>
</script>
</head>
<body>
<div class="main">
    <form id="loginform" method="post">
        <label for="username">Username:</label> <input type="text" id="username" name="username" /><br />
        <label for="password">Password:</label> <input id="password" type="password" name="userpass" /><br />
        <input id="login" type="submit" value="Login" />
    </form>
</div>
</body>
</html>


A wild guess is that maybe jQuery.post() was sending postdata in a way that made serverTime.php toally screw up, but index.html wasn't (since it doesn't handle it at all).

Zorilla fucked around with this message at 23:05 on Apr 29, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

Sylink posted:

I figured it out for other idiots in the same situation. By removing the form tags and the method="post" it now works. Apparently that submit button was tied to something else who knows but that was the conflict.

EDIT: So I guess the problem was I was posting twice perhaps? Weird poo poo happening then.

Crap, I should have caught that one. You need to use return false; to keep the conventional action from also running if Javascript is bound to the same item. For instance:

code:
<!-- Simulating target="_blank" in strict doctypes -->
<a href="http://crap.com/stuff.html" onclick="window.open{this.href);return false;">Link</a>
If you removed return false;, it would open the link in a new window/tab and still follow it in the same window at the same time.

I edited my example to reflect this.

Zorilla fucked around with this message at 23:04 on Apr 29, 2009

Zorilla
Mar 23, 2005

GOING APE SPIT

supster posted:

Are there any CMS systems that are as elegant and simple as Wordpress that are ideal for simple mostly-static non-blog sites? I like alot of the functionality that Wordpress provides (namely the creating pages on the fly and site-wide settings), but am just curious if there's a better option to use for non-blog sites than to just hide the blog portion of Wordpress.

Probably CMS Made Simple. It's decent and the only real downside I've noticed is that templates and CSS are stored in the database and there is no separate storage for template images and content images.

I've used Website Baker as well, but its backend is pretty crude in comparison.

Zorilla
Mar 23, 2005

GOING APE SPIT

Begby posted:


I thought $y =& $x does a reference, not $y = $x . Does it work differently in your example?

Adbot
ADBOT LOVES YOU

Zorilla
Mar 23, 2005

GOING APE SPIT

supster posted:

Are there any decent PHP CSS "compilers"? The only thing I could really find is the following and it's not very feature filled...
http://interfacelab.com/variables-in-css-via-php/

Interesting idea, but it seems kind of over-engineered in my opinion. I'm pulling this out of my rear end, but would something like this work? Sorry if I'm missing your point by a mile:

style.css.php
php:
<?php
$red "#f00";

$column1_width 400;
$column2_width 300;

header('Content-type: text/css');
?>
.fart_container {width: <?php echo ($column1_width $column2_width); ?>px;}
.fart {color: <?php echo $red?>;}

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