![](https://forums.phpfreaks.com/uploads/set_resources_1/84c1e40ea0e759e3f1505eb1788ddf3c_pattern.png)
HDFilmMaker2112
-
Posts
547 -
Joined
-
Last visited
Never
Posts posted by HDFilmMaker2112
-
-
I have to call the method into the other ones? I thought I could just pass variables around using $this variable.
That did make it work, but I don't understand as to why. I'm using $this->invalid without calling in the returnMyStream method, and it works without an issue. So why am I having to call in getName but not returnMyStream?
-
I've tried a few things; still not working, but I wanted to posted the updated code:
<?php class MyStream{ public function __construct($mystream_url){ $db = new DBConnection; $MyStreamDB = $db->connect('mysqli', 'persist', 'db_name'); $mystream_url=$MyStreamDB->mysqli_sanitize($mystream_url); $MyStreamResult = $MyStreamDB->query("SELECT `prof`.`user_id`, `prof`.`university`, `prof`.`cover_picture`, `prof`.`profile_picture`, `prof`.`first_name`, `prof`.`last_name`, `prof`.`middle_name`, `prof`.`maiden_name`, `prof`.`active`, `prof`.`location`, `prof`.`hometown`, `prof`.`work`, `prof`.`high_school`, `prof`.`relationship` FROM `user_profile` as `prof` JOIN `user_details` as `details` ON `details`.`user_id`=`prof`.`user_id` WHERE `details`.`url`='$mystream_url'"); $this->rows = $MyStreamResult->fetch_assoc(); $this->mystream_num_rows = $MyStreamResult->num_rows; } public function returnMyStream(){ if($this->mystream_num_rows==1){ foreach($this->rows as $key=>$val){ $return[$key] = $val; } return $return; } else{ $this->invalid="invalid"; return $this->invalid; } } public function getName(){ if(isset($this->rows['middle_name']) && $this->rows['middle_name']!=null){ $middle_name=" "; $middle_name.=$this->rows['middle_name']; $middle_name.=" "; } else{ $middle_name=' '; } $this->full_name=$this->rows['first_name']; $this->full_name.=$middle_name; $this->full_name.=$this->rows['last_name']; return $this->full_name; } public function getDisplayName(){ $this->maiden_name=$this->rows['maiden_name']; return $this->maiden_name; } public function getTitle(){ if($this->invalid!="invalid"){ $section=$this->full_name; if(isset($this->rows['maiden_name']) && $this->rows['maiden_name']!=null){ $section.=" "; $section.="("; $section.=$this->rows['maiden_name']; $section.=')'; } else{ $section.=''; } } else{ $section='Page Not Found'; } return $section; } } ?>
-
For some reason in my getTitle function below it won't pull in the full_name from the getName function. The getName function is working perfectly fine; so the issue is somewhere in the getTitle function, I believe. "Page Not Found" prints out perfectly fine, when $this->invalid!="invalid" is false, When It's true I just get - in the browser title bar. That hyphen is only displayed when $section is found to be set.
<?php public function getName(){ if(isset($this->rows['middle_name']) && $this->rows['middle_name']!=null){ $middle_name=" $this->rows['middle_name'] "; } else{ $middle_name=' '; } $this->full_name=$this->rows['first_name'].''.$middle_name.''.$this->rows['last_name']; return $this->full_name; } public function getDisplayName(){ $this->maiden_name=$this->rows['maiden_name']; return $this->maiden_name; } public function getTitle(){ if($this->invalid!="invalid"){ $section=$this->full_name; if(isset($this->rows['maiden_name']) && $this->rows['maiden_name']!=null){ $section.=' ('.$this->rows['maiden_name'].')'; } else{ $section.=''; } } else{ $section='Page Not Found'; } return $section; } ?>
You can see what's going on here:
http://www.kynxin.com/andrewmccarrick2
If you mouse over the images it'll have my name in the title attribute (you'll get the little bubble on mouseover). Those title attributes are feed via the getName() function.
If I remove the else statement in the getTitle function it seems $section is no longer set, and I no longer see the hyphen in the title bar... so for some reason $section is being rewritten over each time I try to concatenate it.
-
Using object orientation would actually provide speed as well. If you split your "validation" and "sanitisation" up into different areas of your application then re-use the code as is the way with OO, you will end up programming very quickly anyway.
Really? I've always heard OO runs slower than a regular function, and both run slower than regular code (except when running the same code more than once, but functions are supposedly faster than OO).
-
Anyway, I will say that article did go back and make me add backticks, quote numbers, and use intval on all numbers (I'm even using it on inner-script generated number).
Here's the primary things you need to consider when using mysqli_real_escape_string:
1. Write properly quoted SQL:
1.1. Single quotes around values (string literals and numbers)
1.2. Backtick quotes around identifiers (databases, tables, columns, aliases)
2. Properly escape the strings and numbers:
2.1. mysql_real_escape_string() for all values (string literals and numbers)
2.2. intval() for all number values and the numeric parameters of LIMIT
2.3. Escape wildcard/regexp metacharacters
(addcslashes('%_') for LIKE, and you better avoid REGEXP/RLIKE)
2.4. If identifiers (columns, tables or databases) or keywords
(such as ASC and DESC) are referenced in the script parameters,
make sure (and force) their values are chosen only as one of an
explicit set of options
2.5. No matter what validation steps you take when processing the user
input in your scripts, always do the escaping steps before
issuing the query. Validation is not a substitute for escaping!
-
An article I recently read, linked to me by CrayonViolent in IRC, clearly explains why a variable run through mysql_real_escape_string isn't enough to secure your database. More experienced PHP programmers are likely aware a nere escape_string isn't enough but for the newbies I definitely recommend reading it.
Having a read of any referenced articles in this piece of text is also worthwhile as I've found stuff I was slightly sketchy on clearly explained. Whilst it was written back in 2007 5 years ago, I still feel its necessary today.
http://www.webappsec.org/projects/articles/091007.txt
And honestly I'd still take speed over 100% security. But if you follow the above article, you should get both, speed improvement and 100% security.
-
@CrashOkami: Just to elaborate on what Pikachu2000 and boompa are discussing:
Prepared Statements are run this way (there may be syntax errors because I rarely use prepared statements, actually up to this point never in an actual site):
$Title = $_POST["Title"]; $Small_desc = $_POST["Small_desc"]; $Desc = $_POST["Desc"]; $Image = $_POST["Image"]; $Author = $_POST["Author"]; $stmt = mysqli_prepare($link, "INSERT INTO news (News_ID, Title, Small_desc, Description, Image, Author, Date) VALUES (?, ?, ?, ?, ?, ?, ?)"); mysqli_stmt_bind_param(NULL, $Title, $Small_desc, $Desc, $Image, $Author, NOW()); mysqli_stmt_execute($stmt);
Non-Prepared statements with SQL Injection Prevention are run this way:
$Title = mysqli_real_escape_string($link, $_POST["Title"]); $Small_desc = mysqli_real_escape_string($link, $_POST["Small_desc"]); $Desc = mysqli_real_escape_string($link, $_POST["Desc"]); $Image = mysqli_real_escape_string($link, $_POST["Image"]); $Author = mysqli_real_escape_string($link, $_POST["Author"]); $add_query="INSERT INTO news(News_ID, Title, Small_desc, Description, Image, Author, Date) values (NULL, '$Title', '$Small_desc', '$Desc', '$Image', '$Author', NOW())"; mysqli_query($link, $add_query)
Both of the above essentially do the same thing.
Now here's the primary differences:
Prepared statements store the query with the variable insert values in memory (the "?" in the query are essentially variables/placeholders that get filled in by the "bind_param" function), so you can place the query in a loop, drop in values (via the "bind_param" function ), and have it run through the same query repeatedly with different insert values. When inserting data via the same query per single script execution, this is the preferred and faster method. It would be perfect for inserting data from an array or foreach statement, where you need to iterate through the array and run the query multiple times with the same table and column names but different values (essentially inserting different rows based on the same query).
This method should, IMO, be used sparingly, because...
When using prepared statements with a single set of values to insert (as shown in the above example), where you're not looping through an array or foreach statement, then prepared statements can run 7% to 15% slower than a straight mysqli query with mysqli_real_escape_string. I would say 90% of the time you're not going to be inserting, selecting, updating, or deleting multiple different rows based on the same query at the same time.
Know the tools available to you and use the right one for the given situation. Prepared statements are not the be-all-end-all of query statements; which some people will have you believe. If they were, PHP wouldn't have the other options available.
-
I haven't looked at your code in depth, but is there any feasible way to get this:
<?php //make sure the user doesn't have an existing mute if(isset($_POST['message'])) { //if they clicked cancel instead of "reply" if(isset($_POST['cancel'])) $base->redirect('viewthread.php?forum='. $f.'&id='. $thread); //make sure the title and message meet the standards if(strlen($_POST['message']) > 2000 && $rank < 3) { echo '<div class="frame e">Your post can\'t be larger than 2000 characters.</div>'; } elseif((time()-$last_post[0]['lastpost']) < $flood_limit[0]['floodlimit'] && $rank < 4) { echo '<div class="frame e">You\'re attempting to post too soon.</div>'; } else { //auto-hiding? $data = $database->processQuery("SELECT `autohiding` FROM `threads` WHERE `id` = ?", array($thread), true); $status = ($data[0]['autohiding'] == 1) ? 1 : 0; //insert post $database->processQuery("INSERT INTO `posts` VALUES (null, ?, ?, ?, NOW(), ?, '', ?, ?)", array($username, nl2br($_POST['message']), $thread, $status, $_SERVER['REMOTE_ADDR'], time()), false); $creation_id = $database->getInsertId(); //update thread $database->processQuery("UPDATE `threads` SET `lastposter` = ?, `lastpost` = NOW() WHERE `id` = ?", array($username, $thread), false); //update their last post field $database->processQuery("UPDATE `users` SET `lastpost` = ?", array(time()), false); //send them to the thread they posted on $base->redirect('viewthread.php?forum='. $f .'&id='. $thread.'&goto='. $creation_id); } } else { $chars = ($rank > 2) ? $chars = null : $chars = 2000; if(isset($_GET['quote']) && isset($_GET['qt']) && $rank > 3) { $quote = ($_GET['qt'] == 1) ? $database->processQuery("SELECT `content`,`username` FROM `posts` WHERE `id` = ?", array($_GET['quote']), true) : $database->processQuery("SELECT `content`,`username` FROM `threads` WHERE `id` = ?", array($_GET['quote']), true); $text = $base->remBr('[quote='. $quote[0]['username'] .']'. $quote[0]['content'] .'[/quote]'); } ?>
Above the HTML code, set any echos to a variable instead of echoing them out right away, then place an echo into the current location of that code. Basically treating the variable as a vehicle to transport the results of all that PHP to the correct location after it's generated.
-
Meh, still same, points me to the ELSE statement. Should I try rebuilding my whole database with MySQLi? Would it be worth it? At the very least, now would be the best time to do it, since it's empty of records, save for 1 admin account, and the tests which I'm always deleting.
You shouldn't really have to rebuild anything. MySQLi is just the PHP to MySQL connection code. You still run MySQL you're just connecting to it with PHP's improved MySQL code structure.
Basically just change mysql to mysqli in a lot of the functions, plus a few changes to the data in them.
Just add i to the connect function, add an i to mysql_select_db and flip the db_name and link variables, and add an i to mysql_query.
$link = mysqli_connect("###", "###","###") or die("There was an error connecting to the database."); $select_db = mysqli_select_db($link, $db_name); $add_query="INSERT INTO news(News_ID, Title, Small_desc, Description, Image, Author, Date) values (NULL, '$Title', '$Small_desc', '$Desc', '$Image', '$Author', NOW())"; $add_results = mysqli_query($add_query, $link) or die("Record not inserted. Could not execute query. Please try again. <br> <br>"); echo "Record successfully inserted. Go back to the <a href=admin_index.php>admin index page.</a>"; }
Here's the MySQLi overview on PHP.net: http://www.php.net/manual/en/mysqli.overview.php
And here's a list of the mysqli functions: http://www.php.net/manual/en/mysqli.summary.php
(A majority of what you're looking for is under the "Methods" table on that page.)
As to why the if statement isn't working, not entirely sure, somebody should be able to spot something.
-
try changing the if statement to this:
if($Title!="" && $Small_desc!="" && $Desc!="" && $Image!="" && $Author!="") {
The "!" before something like isset or empty works, but I think it may cause issues before a variable.
-
Try this:
$Title = mysql_real_escape_string($_POST["Title"]); $Small_desc = mysql_real_escape_string($_POST["Small_desc"]); $Desc = mysql_real_escape_string($_POST["Desc"]); $Image = mysql_real_escape_string($_POST["Image"]); $Author = mysql_real_escape_string($_POST["Author"]);
You should however look into moving to MySQLi (note the I) and using mysqli_real_escape_string.
-
The column names don't have to match, but the data does.
I know this won't be exactly what you need, but it's an example:
Say I have two tables
categories:
id | category | description 1 | example | example description
products:
product_id | product | product_price | category_id 1 | test | 1.00 | 1 2 | test 2 | 2.50 | 1
Here I would link the table with an ON condition in the Query like this:
SELECT products.*, categories.category_name FROM categories JOIN products ON categories.id=products.category_id WHERE categories.category='example'
EDIT:
You posted while I was working on mine.
Is category in useful links the same value as category_name in categories?
If so you can do this:
SELECT useful_links.*, categories.category_name FROM useful_links JOIN categories ON useful_links.category=categories.category_name WHERE (add your WHERE condition here.)
-
Use the table name with a dot after it, then the column you want to pull. * to pull all columns.
You need a column in one table that has the same data in a column in the other table to link on.
So table 1 column 1 has an ID, you'd need the same ID number in the second table to link the two tables.
SELECT useful_links.*, categories.category_name FROM useful_links JOIN categories ON (need to know what column matches to write the ON portion) WHERE (add your WHERE condition here.)
Could you give an example of your table structure?
-
I have this code
<?php if ( $page == "home" ) { echo '<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/expand.js"></script>';} ?>
for $page, can I put several pages in the quotes where I currently list "home". If I can, how would I do this, because putting comma doesn't seem to work for me, although syntax error is not displayed.
Thanks in advance
You need the "or" separator. You can use the literal "or" or the symbol based version "||" (two straight lines aka pipe character.). I personally prefer the pipe character.
http://us.php.net/manual/en/language.operators.logical.php
As an example, both of the additions I made are valid. You can pick which ever you prefer, the literal "or" is generally used as an all caps to make it easier to see at a glance in the condition.
<?php if ( $page == "home" OR $page=="contact" || $page=="about" ) { echo
-
Mod_Rewrite Solved:
RewriteCond %{HTTP_HOST} !^www [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Solved the log-in/out issue as well.
Turns out the sessions themselves were fine, it was the SessionID cookie being written as non-www to the browser.
-
I think this whole issue might be non-www. vs. www. issue...
How would I make sure everything uses one or the other?
It seems as though the session is getting set on www. (if the users access via www.) and redirected to www.kynxin.com/newsstream, but the links in my site are for non-www.
So I need something to set something so the site always uses one or the other.
-
Well it's not quite working correctly. Right now if I log-in, it'll change the top menu bar, and if I directly access the rewritten URLs (using mod_rewrite) via browser address bar, such as /home it loads fine... but if I access it via a link with /home it logs me out. But right now I guess it's good enough to do development...
-
I throw in a unset($_SESSION['username']; in the login.php
<?php header('Content-type: text/html; charset=utf-8'); session_start(); $viewed_homepage=$_SESSION['homepage']; $login_username=$_POST['email']; $login_username=strtolower($login_username); $login_password=$_POST['password']; $login_stay_logged_in=$_POST['stayloggedin']; $login_form_submitted=$_POST['login_form_submit']; /*if form has been submitted and the front page has been viewed*/ if($viewed_homepage=="viewed" && $login_form_submitted=="submitted"){ require_once 'db_select.php'; require_once 'function.php'; /*Connect to DB*/ $LoginDB = $db->connect('mysqli', 'persist', 'db418598519'); /*Encode - Sanitize user input for query*/ $sanitized_email = $LoginDB->mysqli_sanitize($login_username); $encoded_password = $LoginDB->kam3($login_password); /*run query*/ $result = $LoginDB->query("SELECT * FROM user WHERE email_address='$sanitized_email' AND password='$encoded_password'"); $num_rows = $result->num_rows; $rows = $result->fetch_assoc(); /*Close Database Connection*/ $LoginDB->close(); /*If user matches a database entry log-in*/ if(($num_rows==1) && ($rows["email_address"]==$sanitized_email && $rows["password"]==$encoded_password)){ /*Set Session/Cookie data to stay logged in*/ $_SESSION['username']=$sanitized_email; $_SESSION['password']=$encoded_password; $_SESSION['user_id']=$rows['id']; /*If selected, Set Cookies*/ if($login_stay_logged_in=="yes"){ /*Connect to DB to insert cookie key*/ $CookieDB = $db->connect('mysqli', 'persist', 'db418598519'); /*Generate key, encode username, and get current time for cookies */ $hased_value = kam3(md5(generatepassword(6))); $hashed_username = md5s($rows["email_address"]); $time = time(); setcookie("knxn_hash", $hased_value, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); setcookie("knxn_username", $hased_username, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); setcookie("knxn_visited", $time, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); } /*Unset error alert for log-in form*/ unset($_SESSION['login_error']); /*redirect to dashboard*/ header("Location: /?p=newsstream"); } else{ /*redirect to index.php with error message*/ $_SESSION['login_error']="error"; unset($_SESSION['username']); header("Location: ./"); } } else{ /*redirect to index.php if submission didn't originate from log-in form on index.php*/ header("Location: ./"); } ?>
Seems to be working correctly that way.
-
// Delete the session vars by clearing the $_SESSION array $_SESSION = array();
Rather then unset for all those $_SESSION values give the above a shot.
No luck.
-
// Delete the hash, username and visited cookies by setting their expiration's to an hour ago (3600) setcookie('knxn_hash', ' ', time() - 3600); setcookie('knxn_username', ' ', time() - 3600); setcookie('knxn_visited', ' ',time() -3600)
Just curious if you're deleting the cookies if the user isn't selecting stay logged in, even still you should make them expire 30 days out or so. Is the form defaulting to selected for the stay logged in box? If you've tested it checked then your going to be able to log out and back in without any issues, you'd have to clear your browser data.
I'm not worried about the cookies right now. They're not being set because I couldn't get them to work, and I disabled the option on the log-in form for the time being.
I turned error reporting on in logout.php and I'm getting this:
Notice: Undefined index: username
-
Alright, I made a test.php... If I log-in, then manually type in test.php in the address bar, it loads and displays the $_SESSION['username']. Then I manually type in logout.php, and it displays the $_SESSION['username']... but if I try to access it directly though a link, like the sign-out link, it doesn't show it.
-
Actually $_SESSION['username'] doesn't appear to be set inside of logout.php so it's going around that if statement. Doesn't make sense why.... It's set only nearly every other page other than my logout.php page; so it's staying set.
-
Alright, just tried echoing everything out, and everything is doing what it should, still getting magically logged in when I have the redirects in place though.
echoing out all the log-in information in login.php displays the information when details are entered, and shows no details when no details are entered.
Echoing everything out in logout.php after everything is unset shows a blank page, as expected.
-
I for the life of me can get this to work:
When you first land on the homepage of my site, the links at the top are set to the user being logged out. When you log-in the links on the top the page change to the menu for a logged in user as they should. When You select sign-out everything looks like it goes okay, you get logged out and the user is returned to the homepage. However, if you simply click the log-in button again, without typing anything into the username or password fields, you're magically signed in again.
login.php
<?php header('Content-type: text/html; charset=utf-8'); session_start(); $viewed_homepage=$_SESSION['homepage']; $login_username=$_POST['email']; $login_username=strtolower($login_username); $login_password=$_POST['password']; $login_stay_logged_in=$_POST['stayloggedin']; $login_form_submitted=$_POST['login_form_submit']; /*if form has been submitted and the front page has been viewed*/ if($viewed_homepage=="viewed" && $login_form_submitted=="submitted"){ require_once 'db_select.php'; require_once 'function.php'; /*Connect to DB*/ $LoginDB = $db->connect('mysqli', 'persist', 'db418598519'); /*Encode - Sanitize user input for query*/ $sanitized_email = $LoginDB->mysqli_sanitize($login_username); $encoded_password = $LoginDB->kam3($login_password); /*run query*/ $result = $LoginDB->query("SELECT * FROM user WHERE email_address='$sanitized_email' AND password='$encoded_password'"); $num_rows = $result->num_rows; $rows = $result->fetch_assoc(); /*Close Database Connection*/ $LoginDB->close(); /*If user matches a database entry log-in*/ if(($num_rows==1) && ($rows["email_address"]==$sanitized_email && $rows["password"]==$encoded_password)){ /*Set Session/Cookie data to stay logged in*/ $_SESSION['username']=$sanitized_email; $_SESSION['password']=$encoded_password; $_SESSION['user_id']=$rows['id']; /*If selected, Set Cookies*/ if($login_stay_logged_in=="yes"){ /*Connect to DB to insert cookie key*/ $CookieDB = $db->connect('mysqli', 'persist', 'db418598519'); /*Generate key, encode username, and get current time for cookies */ $hased_value = kam3(md5(generatepassword(6))); $hashed_username = md5s($rows["email_address"]); $time = time(); setcookie("knxn_hash", $hased_value, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); setcookie("knxn_username", $hased_username, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); setcookie("knxn_visited", $time, time()+(86400*180), "/", "beta.area51entertainment.com",false,false); } /*Unset error alert for log-in form*/ unset($_SESSION['login_error']); /*redirect to dashboard*/ header("Location: /?p=newsstream"); } else{ /*redirect to index.php with error message*/ $_SESSION['login_error']="error"; header("Location: ./"); } } else{ /*redirect to index.php if submission didn't originate from log-in form on index.php*/ header("Location: ./"); } ?>
Logout.php
<?php header('Content-type: text/html; charset=utf-8'); session_start(); /*Unset and destroy users session data*/ if(isset($_SESSION['username'])){ unset($_SESSION['username']); unset($_SESSION['password']); unset($_SESSION['user_id']); unset($_SESSION['homepage']); session_destroy(); header("location: ./"); } else{ header("location: ./"); } ?>
Issue with using a variable in another method
in PHP Coding Help
Posted
Yeah I know how functions work, I've been coding in PHP for over 10 years and have been using functions for over 8; it's just every single example I've seen hasn't shown the need to call a method to pass variables from one to another.
The more and more I look into OOP, the more and more it seems like simple functions would work just as well. I'm getting the idea here, that all OOP is are functions wrapped in a class name; I really see nothing more to it than that. I frequently use functions that call other functions. I thought one of the benefits to OOP was the need not to do that; apparently not. With OOP you need to initiate a class via the "new" keyword and you get to use cool looking -> pointer characters to call functions... seems like there's nothing more than that compared to regular functions. Regular functions are just as good of a method to "re-use code", if not better it seems, than OOP.
And since I continually seem to be treated like I don't know anything about PHP on this forum, I won't be returning.
As per KillerPHP.com's OO beginner guide:
http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php
As per one of their examples:
They're not calling the set_name function/method into the get_name function/method.