Jump to content

maxxd

Gurus
  • Posts

    1,657
  • Joined

  • Last visited

  • Days Won

    51

Posts posted by maxxd

  1. You didn't say you were coding underneath WP.  Not nice.  You should be posting in the CMS forum.

    I did mention it at the end of my original post, but I can imagine skimming by it and I probably should have called it out more. I didn't post in the CMS forum or make more of a deal about the WP usage because I kinda figured it was just me having not used cookies in years and forgetting things as opposed to something WP is injecting or doing behind the scenes. If it's in the wrong forum and a moderator happens to be reading this, any chance you could move it over to the proper location?

     

    Is that two return statements in isLoggedIn? The second one will never be executed.

    The first is commented out and won't be run in this scenario. (It is being run in dev because it actually works.) I just left it there because it's identical and does work...

     

    I gotta Google it, but am I wrong in my recollection that session variables can't be set after output goes to the browser, same as cookies?

  2. I've only been working with WordPress for about two months, so I'm not sure what it's running in addition to the admin_ajax_* hook, but the output in the console shows only the expected JSON, which is output after the cookies are meant to be set. And wouldn't the session version also fail if there was output prior to the setting of the variables? I hadn't thought about checking the error log (duh) so thank you for the reminder!

  3. The browser is forwarded to a target page upon successful login - that's where I'm checking to make sure the cookies are set. Sorry - that's in the JavaScript that I totally forgot to post.

    $('#login-popup #submit').click(function(e){
    	e.preventDefault();
    	$.ajax({
    		type:'post',
    		url:myVar.ajaxUrl,
    		data:{
    			'action':'agent_login',
    			'username':$('#login-popup #username').val(),
    			'password':$('#login-popup #password').val()
    		},
    	}).done(function(ajaxObject){
    		var resp = JSON.parse(ajaxObject);
    		if(resp.success == true){
    			clearLogin();
    			window.location.replace(resp.location);
    		}
    	});
    });
    
  4. Hi y'all. It's been forever and a day since I've dealt with cookies, and I can't get through the cobwebs in my brain about them. I know that cookies have to be set before any output goes to the browser, but if I'm not mistaken, it's the same with sessions and sessions work in this situation. Unfortunately, the client needs cookies for integration with an existing piece of software.

     

    Basically, what's happening is this: You load a page, click the 'login' button, which uses JQuery to change the display on the login screen from 'none' to 'block'. Use the newly-visible login form to enter username and password, which are passed via ajax to my login function. If the login is successful, I set the cookie variable and redirect the user to the protected page. However, despite the ajax reporting a successful login and redirecting the browser as expected, the check on the protected page is kicking the user back to the beginning because the cookie was never actually set.

     

    FunctionsClass.php:

    /**
     *	Logs in the requesting user with the agent and email values supplied via AJAX.
     *	@return		string					JSON-encoded array
     */
    	public function agentLogin(){
    		$ret['success'] = $this->_site->login($_POST['username'],$_POST['password']);
    		$ret['location'] = '/protected-page';
     		print(json_encode($ret));
     		die();
    	 }
    

    Site.php (that's $_site in FunctionsClass):

    /**
     *	Logs in the agent.
     *	Checks to see if the user is already logged in, if not, attempts to do so.
     *	@param		string		$un				username
     *	@param		string		$pw				password
     *	@return		boolean
     */
    	public function logIn($un, $pw){
    		if($this->isLoggedIn()){
    			return true;
    		}
    		return $this->logAgentIn($un,$pw);
    	}
    
    /**
     *	Check to see if the cookie set so we know if the user has logged in.
     *	@return		boolean
     */
    	public function isLoggedIn(){
    //		return !empty($_SESSION['mycheckvariable']);
    		return !empty($_COOKIE['mycheckvariable']);
    	}
    
    /**
     *	Log the user in.
     *	@param		string		$un				username
     *	@param		string		$pw				password
     *	@return		boolean
     */
    	private function logAgentIn($un,$pw){
    //		$_SESSION['mycheckvariable']['email'] = 'me@notmyemail.com';
    		setcookie('mycheckvariable','me@notmyrealemail.com',time()+60*60*8,'/');
    		return true;
    	}
    
    

    It's not as though I'm even actually checking a database - just trying to stub this out for client presentation. And, if I uncomment the two lines using sessions and comment out the cookies, it all works perfectly. I'm not at all sure what I'm missing and would very much appreciate some other eyes on this - any takers?

     

    I'm using WordPress, if that matters at all...

     

    Thanks in advance!

  5. I have this snippet that pulls up a confirmation page and requires a click to confirm before deleting the input member (or gives invalid member error), I have been completely unsuccessful removing the confirmation step and just deleting the member with success...

      case 'deletemember':
        if (!isset($_POST['deletemember']))// && !isset($confirm))
        {
          $delmembername = null;
          print eval(get_template('delete_member'));
        }
        else
        {
          if (/*isset($confirm) && */isset($mid))
          {
            mysql_query("DELETE FROM members WHERE member_id='$mid'") or die(mysql_error());
            mysql_query("UPDATE topics SET topic_rid=0 WHERE topic_rid='$mid'")or die(mysql_error());
            mysql_query("UPDATE topics SET topic_lrid=0 WHERE topic_lrid='$mid'")or die(mysql_error());
            mysql_query("UPDATE replies SET reply_aid=0 WHERE reply_aid='$mid'")or die(mysql_error());
            show_message('Member deleted');
          }
          else
          {
            $result = mysql_query("SELECT member_id FROM members WHERE member_name='$delmembername'");
            if (mysql_num_rows($result) == 0)
              show_message('Member invalid');
    /*
            else
            {
              $mid = mysql_result($result, 0);
              $board_title = sprintf('Delete '.$delmembername.'?');
              $message = $board_title;
              $confirmed_link = '<a href="admin.php?a=deletemember&mid='.$mid.'&confirm=1">Delete</a>';
              print eval(get_template('confirm'));
            }
    */
          }
        }
        break;
    

    Can anyone help me here, I know it has to be something simple, I'm just not that great at PHP.

    You need to remove the check on $_GET['confirm']. The above changes (marked in red) should work - I've not tested them or had my second cup of coffee yet, so no guarantees, but that should do it. I'm assuming that $mid is being validated and sanitized at some point before your switch statement. As a side note, switch from mysql_* to PDO and do the DELETE and UPDATE statements in a transaction so you don't end up with orphaned records.

  6. Just because you're not getting the errors doesn't mean they're not happening - production servers typically do and should suppress error display - the user doesn't need to know that much about your server set-up. Granted, you should be seeing your fatal error.

     

    Have you used session_start() to actually start the browser session and have you defined the constant $site_url in the config class before attempting to use either $_SESSION['role'] or config::site_url?

  7. You don't. What Frank_b is suggesting is putting your included scripts above the web root, where the user can't access them anyway. Anything above the /public_html/ directory (in this server set-up, sometimes it's called /www/, sometimes it's /html_docs/) is inaccessible from the internet. So, by using something like

    require_once('../includes/IncludedFile.php');
    

    from your /var/user_directory/public_html/index.php script, you'll be accessing /var/user_directory/includes/IncludedFile.php, and can use the functions or class in that script in your display file. Of course, Frank_b was recommending an absolute server path to the includes directory instead of the relative that I typed.

  8. One more thing I just thought of - when you say nothing is being returned, do you mean you get no data, or you get no output at all? I'm pretty sure that jcbones' observation should have thrown an error because the referenced array index doesn't exist, but if you're not getting that, then you need to turn on error reporting.

  9. tsangaris, while I'm sure it couldn't hurt, I'd think it more important to make sure at least the sender and recipient IDs are legit, active IDs in your system before sending anything. Keeping the processing php script in a directory above the web root won't immediately make it safe, but it does make it a bit more difficult to call the file directly from outside your server. You should probably create a nonce in the source form html, store it in session, pass the value from the form with the other values and check that in the processing script to make sure that the request is coming from your form and not somewhere else. This doesn't mean a human being isn't logged in to your site sending bad messages, but at least it means you can be a bit more sure of the fact that request originated on your site.

     

    And, of course, sanitize and validate any and all data supplied by an end-user. Or another system. Or anywhere, really.

  10. OK - now we're getting there. It sounds like you're on the right track. Using radio buttons and associating each possible recipient's id to the value attribute is exactly how I'd go in this situation. Pass the user-defined information (recipient(s) and message) via AJAX, but keep the system defined information (your sender's ID) in $_SESSION. That way you're not mucking about too much with the session data and, more importantly, when you go back to the code in six months to a year, you can clearly follow the data chain. In addition, you can then move and repurpose the AJAX script without having to worry about any hard-coded $_SESSION calls. Think of it as decoupling the script from the site.

  11. OK - you're having an issue before the ajax call, right?

     

    So how is the sender (userA) selecting a recipient (userB)? If they're typing a name into a text input, you can use the value of that text input in the sendmessage.php script to find the ID. If you're using a select element, the ID (or a proxy) should be printed directly into the markup as the value of the option element - main.php (or another script that's calling main.php to get the data) is going to print userB's id in the option element value. You'd then send that with $('#recipientSelect')val() from the JS to sendmail.php.

     

    UserA has to be logged in to send a message, right? If so, I'd think you'd have their user ID in session and can grab that in sendmessage.php without having to define it in the javascript at all. And obviously the message value is the $('#message').val() of the message text area.

     

    Is that the question you had, and if so, does that make sense at all?

  12. Basically, your data entry form can be a separate page. Your opening tag for the form should look something like this:

    <form name='myForm' action='processMyForm.php' method='post'>
    

    where the code we've been discussing above is in the file processMyForm.php. Check at the top of that file to make sure the $_POST[] variables that you're expecting are set. If they are, do what you need to do to the values to make sure they're safe and in the format you're expecting, then run the query using those values. If they're not set, you can redirect the user to the form page or display an error or play a fun sound clip or whatever - you just won't be running the query.

     

    That's the easiest way I can think of to handle it - there are many other methods, but you gotta learn to walk before attempting to run.

  13. First off, don't use that code. The mysql_* functions have been deprecated in php for about a decade and are slated for removal at some point. I know it'd break a lot of the internet, but I do wish they'd just remove the darned things already. What you want to do is read up on PDO by following the link I put in my last post. You'll create a new PDO object with your database credentials, query the database for the information you're looking for and use the returned data to populate the table you're building. You can do that last part by combining your last two scripts into one.

    <?php
    $connection = new PDO(/* credentials */);
    $sql = $connection->query(/* query string */);
    $returnArray = $sql->fetchAll(PDO::FETCH_OBJ);
    ?>
    <table>
    	<thead>
    		<th>Company
    		<th>Price
    		<th>Location
    		<th>Review
    	</thead>
    	<tbody>
    <?php foreach($returnArray as $return){ ?>
    		<tr>
    			<td><?= $return->comapny; ?>
    			<td><?= $return->price; ?>
    			<td><?= $return->location; ?>
    			<td><?= $return->review; ?>
    		</tr>
    <?php } ?>
    	</tbody>
    </table>
    

    I have neither tested the above code nor had my second cup of coffee yet this morning, so understand that this is not a copy and paste solution. However, it should point you in the right direction. Once you get to this point, post back here if you're still having problems.

     

    Also (and a bit off topic) don't use 'date' as a column name. I thought it was reserved, but a quick search shows me that it's not. Hunh. However, it is a MySQL function and can make things confusing.

  14. If I'm reading this right, you're asking how to get information from the form into and out of the database, yes? If so, you'll need to look into PDO for database functionality. I'm assuming you've already got the database set up - if not, that's going to have to be step one, obviously.

  15. Turn on error reporting. You've got output to the screen before your redirect call, which won't work. The reason you're seeing the form before it sits there is because the form is the output to the screen that's causing your script not to work.

  16. Given your hand-coded error message, I'd venture a guess that neither resource.serviceName nor resource.resourceName are set, and resource::insert() doesn't exist in the $methods array.

     

    Also, in the future please use the code tags (< > in the toolbar) when posting code as it does make it easier to read. Yours wasn't bad, but it's a good habit to get in to.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.