Jump to content

Karaethon

Members
  • Posts

    160
  • Joined

  • Last visited

Posts posted by Karaethon

  1. 1 hour ago, requinix said:

    The downside to files, like actual files on the server, is that they need to be cleaned up after a while. If generating the text isn't particularly problematic then I would do it from scratch every time it's needed - be that the first display or an additional download.

    Yeah, that's why I want to generate the file only if the user clicks save.

    1 hour ago, Barand said:

    You could use output buffering when generating the page. Save the buffered content to a uniquely named file then output to the screen. Provide a download link to the file.

    Hmm, IDK if I can do this, the final output isn't ever on the server, the user javascript posts to the different php files the server and assembles the final output on user side. 

     

    I found this idk if it will do what I need, but I'll play with it.

  2. I have, on my site, a server output page (after the user has completed certain steps the server generates data to display for the user). For security purposes the server cannot retrieve this data after the page is left, it is gone for good (unless the transaction ID from paypal is supplied), so I want to make a button that dumps the data to a text file the user can then save or print. While the page is active I could retrieve the data from the server again, so... can javascript do this on client side (if so please give me an example of how) or should I just requery the server and get it to create the text file and then send it to the user?

  3. I am testing an idea and I want to run through thousands of iterations of the testing script. It is not a complex script but is complex proccessing (using password_hash) and it timesout out on the 64th iteration, is there an ini_set command or simething I can put in the start of the testing file to change the timeout only for the proccessing of this script?

  4. I need to reset my autoincrement value, I had a minor goof in my insert code and it ws inserting data wrong, i have fixed it but im now over 1000 rows in and all error posts are deleted, its not a big deal on a bigint but i want to start over at the beginning for my own OCD issues. how/can this be done?

  5. On 7/2/2019 at 8:58 AM, requinix said:

    Don't do that. Make a page specifically for the AJAX request that "calls" the snippet.

    And just stick with .php. It's more portable, both for running and for editing. If you want your snippets (I term I hate, by the way) to be separate then put them in a dedicated directory or something.

    Yeah, thats what I ended up doing. and why hate 'snippets'? thats what they are, pieces of html that by themselves are just a piece of the whole page. like footer, header, menu, etc. what would you call them? pieces? chunks? (truffle shufle)

  6. 4 hours ago, benanamen said:

    The one thing that hasn't been mentioned is WHY would YOU want to do this in the first place?

    Its kinda silly. I have code snippets, pieces of code that i use often in several places, so i save them as .snip, when I include them they run php code but i needed to call one via ajax and it wasnt running php code because it wasnt .php 

    i finally realized that giving it a ohp extension was the logical, least effort, option.

  7. ok, been playing with pdo... i get a good connection (i believe, because no errors are being thrown) but my attempt to query is not working...

    <?php
    	include '../includes/dbconn.inc';
    	$player = $link->prepare("SELECT * FROM players WHERE PlayerID=?")->execute(['1']);
    	echo $player;
    	echo $player->fetch();
    ?>

    is failing,  at first echo $player is: 1

    at fetch error is thrown: 'Call to a member function fetch() on boolean

    whats going on?

  8. 26 minutes ago, mac_gyver said:

    if you mean named place-holders, no, the order doesn't matter. they are matched via their names.

    No, I meant if the table has col1, col2, col3... do I have to make the PDO query in the same order? i understand that it will bind my values regardless of where they are in the array, I just want to know do I have to put the INSERT order to match the table order.

    i.e: INSERT INTO table (col1, col2, col3) VALUES ( :arg1, :arg2, :arg3) where the data was [arg1=>'test1', arg2=>'test2', arg3=>'test3']

    OR could I use

    INSERT INTO table (col3, col1, col2) VALUES ( :arg3, :arg1, :arg2) where the data was [arg1=>'test1', arg2=>'test2', arg3=>'test3']

  9. 45 minutes ago, mac_gyver said:

    the code you are currently producing is where we were back when using the mysql_ extension. it took a lot of code to securely handle each different type of data being put into the sql query statement and a lot of code to provide error handling for all the statements that can fail. by using prepared queries, the simple and consistent PDO extension, and exceptions to handle errors, most of the implementation detail code disappears. you only have to validate that data meets the needs of the application, which in most cases is just to make sure it is not an empty value or that is has an expected format, form the sql query statement, with place-holders for any external/unknown data values and array of input data values, then either call the prepare/execute methods or the query() method (which you can combine by extending the PDO class with a general purpose query method that accepts an optional 2nd array parameter of input values) to run the query.

    letting php handle the exception/error will give you all the file name, line number, and sql error information, that will either get displayed or logged based on the php error settings, without requiring any conditional logic in your code or ever touching the code after it is written. this just takes one line of code to set the error mode to exceptions when you make the connection. (lol i just noticed that you are using the connection error statements in your insert query error handling.)

    Hmm, ok... well I started playing with php/mysql back in 2003, then had a minor 15 year vacation... so i know im behind the times... where can i go to read/learn this new PDO stuff? I'm currently using my old 'PHP, MySQL, Javascript, & HTML5 all-in-one for dummies' as a basic reference, I got it on that "vacation" to try to stay in the loop but i know its old now itself. (copyrighted 2013).

  10. 2 minutes ago, mac_gyver said:

    nope. you should validate input only, not alter it. for any sanitation you can come up with, there are libraries of things hackers use that can get past it.

    the only fool-proof way of preventing anything in data from being treated as sql syntax is to use a true prepared query (PDO has emulated prepared queries that should be avoided.) prepared queries also eliminate all the single-quotes around values and all the concatenation, extra quotes for concentration, and any {} that people have used to get values into the sql query statement.

     

    don't waste your time writing and then changing code just because the context changes. write code once and leave it alone.

     

    hmm, ok i need to learn about these prepared queries i think...

    and i guess i thought sanitize = validate, but i guess there is a difference

    i know i SHOULD write once, but I tend to be a bit thick-headed so i put in exra verbose error code so i know whats wrong at code time... 

    Ieally need to break my bad habits and develop beter ones, thanks for the input.

  11. 4 minutes ago, Barand said:

    You can't really call it "final" until it's been tested.

    With careful construction of your test data, avoiding string values, empty $criteria arrays and queries that return no records (still valid), it should be fine and let you sleep at night with the feeling you've done a good job.

    well yeah i guess final isnt the right word, the original code was used in a testing file not the final file, I test pieces separately first to make sure they are doing what I expect then move them to my working file which becomes the final after completion and testing.

  12. 29 minutes ago, mac_gyver said:

    since you should be using a prepared query with external/unknown data values, your current code is not general purpose and will need to be redone to make it secure. you will want to switch to the much simpler php PDO extension, since it requires fewer statements to accomplish any task and the result from prepared and non-prepared queries can be treated in the same way. also, you should be using exceptions to handle connection, query, prepare, and execute errors and in most cases let php catch and handle the exception, where it will use its error related settings to control what happens with the actual error information (database errors will get displayed or logged the same as php errors.) by unconditionally outputting the raw error information on a live/public server, you will only be helping hackers who intentionally trigger errors, since connection errors contain the db username, and all the errors contain server path information.

    next, to dynamically produce sql statements, use arrays to hold the column/value terms and implode() the results. this will eliminate all the extra commas and substr() statements.

    lastly, you apparently didn't look very closely at the echoed sql query statement. you are putting back-ticks ` around the values. do you know what using back-ticks in an sql context means?

     

     

    Thanks for the info, I'm not sure if it matters but this class will only be called by other classes whose job is to sanitize user input so i dont think i have to worry there and the error handling is at the moment only for testing server when placed on live server that will all be gone.

    And nope I'm not sure about back-ticks i just kinda copied the phpmyadmin output and tried to match it.

     

    OHHH I SEE IT! the phpmyadmin isnt using back-ticks! theyre single quotes! i had to zoom in to catch that.

  13. 15 minutes ago, requinix said:

    ...but look at what happens when answered threads don't get removed: the discussion continues. We don't close threads just because OP got their answer - we're not StackOverflow. You never know what else might arise after the problem is supposedly "solved".

    Yeah, i see thst, i just felt a little stupid for not seeing it and wasting forum space and everyone elses time.

    16 minutes ago, benanamen said:

    The last part could use some cleanup.

    
    if (mysqli_num_rows($result)) {
        return $result;
    }
    return false;

     

     

    Do you have a suggestion? I know I could just return $result...

  14. Final code is:

    public function getData($criteria){
    		$query = "SELECT * FROM {$this->table} WHERE ";
    		$crit = "";
    		foreach($criteria as $column => $value){
    			if(($column === 'bind')){
    				$crit .= "{$value} ";
    			}else{
    				$crit .= "{$column} = {$value} ";
    			}
    		}
    		$result = mysqli_query($this->link, $query.$crit);
    		if(mysqli_num_rows($result) !== 0){
    			return $result;
    		}else{
    			return false;
    		}
    	}

     

  15. I am trying to centralize my database communicatin into a class (im getting tired of typing and retyping the code to send queries) Its not done but I cant get INSERT to work. 

    Heres my Class:

    <?php
    ######################################################
    # Class Name: DBConnect
    # Description: Base Class to handle DB inquiries
    # Created: 06/27/19
    # Updated: 06/27/19
    # Author: James 'Karæthon' Cantando
    # Contact: TheKaraethon@gmail.com
    ######################################################
    class DBConnect{
    ######################################################
    # PROPERTIES
    ######################################################
    # PRIVATE
    	private const HOST = 'localhost';
    	private const USER = 'root';
    	private const PASS = '';
    	private const DB = 'crackthecode';
    	private $link;
    	private $table;
    # PUBLIC
    
    ######################################################
    # METHODS
    ######################################################
    # CONSTRUCTOR
    	function __construct($target){
    		$this -> table = $target;
    		$this -> link = mysqli_connect(self::HOST,self::USER,self::PASS,self::DB);
    		if(!$this->link){
    		die("An error occured while attempting to connect to the table \"{$this -> table}\" on the ".self::DB." database.<br />Error#: ".mysqli_connect_errno()."<br />Description: ".mysqli_connect_error());
    		}
    	}
    # PRIVATE
    	private function checkValue($val){
    		switch(strtoupper($val)){
    			case 'NULL':
    				return 'NULL, ';
    				break;
    			case 'CURRENT_TIMESTAMP':
    				return 'CURRENT_TIMESTAMP, ';
    				break;
    			default:
    				return "`".$val."`, ";
    		}
    	}
    
    # PUBLIC
    	public function getData($criteria){
    		$query = "SELECT * FROM {$this->table} WHERE ";
    		$crit = "";
    		foreach($criteria as $column => $value){
    			if(($column === 'bind')){
    				$crit .= "{$value} ";
    			}else{
    				$crit .= "{$column} = {$value} ";
    			}
    		}
    		$result = mysqli_query($this->link, $query.$crit);
    		if(mysqli_num_rows($result) !== 0){
    			return $result;
    		}else{
    			return false;
    		}
    	}
    
    	public function newData($data){
    		$query = "INSERT INTO `{$this->table}` ";
    		$cols = "(";
    		$vals = "(";
    		foreach($data as $col => $val){
    			$cols .= "`".$col."`, ";
    			$vals .= $this->checkValue($val);
    		}
    		$query = $query.substr($cols,0,-2).") VALUES ".substr($vals,0,-2).")";
    		echo $query;
    		echo "<br />INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0')";
    		$insert = mysqli_query($this->link, $query);
    		//$insert = mysqli_query($this->link, "INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0')");
    		if(!$insert){
    			echo "An error occured while attempting to INSERT into the table \"{$this -> table}\" on the ".self::DB." database.<br />Error#: ".mysqli_connect_errno()."<br />Description: ".mysqli_connect_error();
    		}
    		return $insert;
    	}
    
    
    
    ######################################################
    # End Class
    ######################################################
    }
    ?>

    The testing page has this:

    <?php
    	include '../includes/dbconn.class';
    	$test = new DBConnect("players");
    	$inserted = $test->newData([
    		'playerID'=> 'NULL',
    		'CreatedDate'=> 'CURRENT_TIMESTAMP',
    		'Username'=>'test',
    		'Passcode'=>'123456789',
    		'Email'=>'test@test.test',
    		'FName'=>'test',
    		'Lname'=>'tested',
    		'Addr1'=>'1234 msin st',
    		'Addr2'=>'NULL',
    		'City'=>'Anytown',
    		'State'=>'Denial',
    		'Country'=>'United States',
    		'PostalCode'=>'12345-6789',
    		'Phone'=>'19995551212',
    		'PhoneType'=>'Other',
    		'TaxpayerID'=>'123-45-6789',
    		'DOB'=>'2019-6-17',
    		'TokenBalance'=>'1000000000'
    		]);
    	if($inserted){echo 'Insert succeeded.';}else{echo 'Insert failed.';}
    ?>

    In the class file you will see two queries, one code generated the other from a successful phpmyadmin query. The phpmyadmin one works everytime, but the generated doent. and I cant see any difference between them when echoed except the values being inserted. please what am I doing wrong?

    Output from echoed queries:

    Generated Query: INSERT INTO `players` (`playerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, `test`, `123456789`, `test@test.test`, `test`, `tested`, `1234 msin st`, NULL, `Anytown`, `Denial`, `United States`, `12345-6789`, `19995551212`, `Other`, `123-45-6789`, `2019-6-17`, `1000000000`)

    PHPMyAdmin Query: INSERT INTO `players` (`PlayerID`, `CreatedDate`, `Username`, `Passcode`, `Email`, `FName`, `Lname`, `Addr1`, `Addr2`, `City`, `State`, `Country`, `PostalCode`, `Phone`, `PhoneType`, `TaxpayerID`, `DOB`, `TokenBalance`) VALUES (NULL, CURRENT_TIMESTAMP, 'test', 'ggb', 'hyh', 'yjj', 'hjj', 'ghu', 'ghj', 'tuo', 'dgi', 'fgu', 'iyh', 'ghk', 'Other', 'tujk', '2019-6-17', '0')

    notes mysql version: 10.0.33-MariaDB (? is that correct?)

     

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