Jump to content

maxxd

Gurus
  • Posts

    1,659
  • Joined

  • Last visited

  • Days Won

    52

Posts posted by maxxd

  1. Personally, I'd take this one step further and make it easier on yourself. Create child classes that extend or implement the class listing above and contain only the code specific to the connection type. For instance, create a class called PDOConnection.php that includes the open(), close(), and mysqlSelectToClass() methods using only PDO-specific functionality. Create another class called MysqliConnection.php that includes mysqli-specific implementations of the open(), close(), and mysqlSelectToClass() methods. Then, the connection class above can do something like this:

    class Connection{
    	private	$_dbConn;
    	
    	public function __construct(){
    		if(!class_exists('PDO')){
    			$DB = 'MysqliConnection';
    		}else{
    			$DB = 'PDOConnection';
    		}
    		$this->_dbConn = new $DB();
    		$this->_dbConn->open();
    	}
    	
    	public function close(){
    		$this->_dbConn->close();
    	}
    	
    	public function mysqlSelectToClass($query, $className, $args = null){
    		return $this->_dbConn->mysqlSelectToClass($query, $className, $args);
    	}
    }
    

    That way, if you need to add yet another database choice in the future you can do it without disturbing the current (working) code. Also, you avoid the repeated if-else clauses.

  2. I have to agree with LeJack on this one - taking some time to learn a little HTML, CSS, php, and WordPress is going to help a lot in this situation. The thing about WordPress is that it's great for end-users, but once you start digging into and modifying the code, it's kind of a nightmare from that perspective. The reliance on global functions and variables can make things difficult to follow and really isn't good modern coding, so you should have a decent grounding in php to know when and how to break both php's and WordPress's rules. And no offense, but if you don't know how to assign a class to a DOM element, you're going to be in over your head quickly. The nice thing is, it doesn't take a whole lot of time to learn the basics that you need to know. That being said, you do need to know those basics.

    • Like 1
  3. You just add "class='alignleft'" to the <img /> line. The only reason that the class is 'called' for the thumbnail is that the_post_thumbnail() is a template tag and by default outputs the source code, so the theme developer is passing the class name into the function call as one of the optional parameters.

  4. In WordPress, you include style sheets with the wp_enqueue_style() function that you can call using the wp_enqueue_scripts hook.

    function queueMyStyles(){
    	wp_enqueue_style('subbranding',get_stylesheet_directory_uri()."/myStyle.css",'site-style');
    }
    add_action('wp_enqueue_scripts','queueMyStyles');
    
  5. Don't tie the click to the actual DOM element directly.

    <button id='button_1' class='button'>1</button>
    <button id='button_1' class='button'>1</button>
    <button id='button_1' class='button'>1</button>
    
    <script>
    $('.button').click(function(){
    	var whichClicked = $(this).attr('id');
    	alert('Button ' + whichClicked + ' was clicked!');
    });
    </script>
    

    You could also skip the class and use the element selector directly if either there are no other buttons on the page or you want all the buttons to react the same.

  6.  

    Last time I checked nl2br does not remove the newline characters! It only adds <br /> after them. 

     

    I have no issues with the following to remove newlines from a string

    $string = str_replace(["\r\n", "\r", "\n"], '', $string); 

    Wow - just re-read the php manual page and you're right. nl2br() doesn't actually remove the newline characters. I must be remembering incorrectly, or only thought it worked at the time. Hunh...

  7. Ch0cu3r, while I agree that nl2br() is for display, I've had issues in the past with str_replace() not actually replacing line breaks. I don't know if the input was from a Windows machine using just '\n' and I was looking for '\r\n' or if I was searching for '\n' and the input was from a Mac or *nix system that uses '\r\n', or if I was searching for '\n\r' (it was a while ago) but in that situation converting to <br /> and then replacing that with the empty string was the way around it. It did at least give me a consistent string to search for in the string as a whole...

     

    Also, asanti - cyberRobot's correct. The data shouldn't be massaged too much beyond validating and sanitizing before storing in the database. You can manipulate the raw data before you output to a variety of media.

  8. 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?

  9. 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!

  10. 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);
    		}
    	});
    });
    
  11. 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!

  12. 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.

  13. 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?

  14. 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.

  15. 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.

×
×
  • 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.