is there a way to get user input into variables with php using only one file (ie have the form to input the data and process it in one document instead of "POST"ing to a seperate document)
Printable View
is there a way to get user input into variables with php using only one file (ie have the form to input the data and process it in one document instead of "POST"ing to a seperate document)
Yes?
I don't know the full rhetoric off the top of my head but it's a simple case of dealing with the $_POST superglobal. If there's nothing in it, user hasn't posted, otherwise do the usual cutting up into little bits and enjoy.
Sure. Just POST to yourself. In the document, check either if the request method is POST ($_SERVER['REQUEST_METHOD'] == 'POST') or if the variables are available (isset($_POST['whatever']). Do your processing depending on this.
But let me tell you, that's not pretty. Separating is better.
another thing im trying to stab at is this fancy mysql database output im trying to do if anyone thinks they could help (im new at php and mysql). Im trying to make my own automatied FAQ system. theres 4 fields for each row but thats not important
the problem is it only processes the first "while($row = mysql_fetch_array( $result ))" part correctly, the 2nd one doesnt do anything. if i switch them around in order the new first one works but not the 2nd one.Code:$result = mysql_query("SELECT * FROM faq");
if (!$result)
{
$errorreport="3faq printing out faq";
echo($errormessage);
}
else
{
$highestID=0;
$contentSize=0;
$contentPrinted=0;
while($row = mysql_fetch_array( $result ))
{
if($row['ID'] > $highestID)
{
$highestID=$row['ID'];
};
$contentSize=$contentSize+1;
}
echo($highestID);
while($row = mysql_fetch_array( $result ))
{
echo "<p>Question: ";
echo $row['Question'];
echo "<br>Answer: ";
echo $row['Answer'];
echo "</p><br>";
}
i think the problem is it doesn't look down through each row starting from the begining on the 2nd while loop, is there some kind of command to "reset" the "cursor"?
yeh i guess your right its alot easier to just seperate itQuote:
Originally Posted by CornedBee
Until someone more experienced answers, execute the query again. Perhaps if you just made the first one grab the "ID" field it wouldn't look so damn spaghettio. ;)Quote:
Originally Posted by MisterSako
EDIT: mysql_data_seek
I've got a database script using PHP/MySQL that manages customer information. So far it's about 1,500 lines so I'll just give you a zip link if you think it'll help.
Here's a preview:
http://bookmarkhosting.com/tool/
It is being worked on though so it's a WIP. Can't be much help to offer support, maybe it'll help you somehow. If not, I tried,
yes that i think would help alot please zip it up for me :}
thanks
One thing we use on the forum project I'm involved in is seperating data collection with display. So you would gather the information and store it and display it later. When large amounts of data is possible we use a call back function to get one part of it at a time. However its still seperated into the gathering and displaying part.
agh what am i doing wrong???
http://mrsako.gotdns.com/backupwithlogin.php
right below the body tag i tried to do this
<?php
include("loginsystem/include/session.php");
?>
why does it just write it all to the screen? on my faq section (scroll super alot down and click FAQ) i have php embded within my page there (but not a include file) and it works fine so i know i have PHP and mysql installed correcctly. this is whats in the session.php file
i tried putting php after <? but it just made the entire site not show up except for the include stuff
btw shadow if i'd still muchly appreciate that zip file :}PHP Code:
edit- i took this code out because it was a waste of 200 lines
Wow, you're that experienced with PHP that you're working with classes straight away? You need groupies, seriously. ;)
I think you'll find it's not optional. Please don't try that "Oh but it works... better!" argument.Quote:
Originally Posted by MisterSako
It's time you learnt the greatness that is PHP debugging, a.k.a. put echo "Ran to here"; statements EVERYWHERE!
nah i got it from here
http://evolt.org/node/60384
if someone else made what i need i dont think i should spend the time making my own :-p
i tried putting <?php where the guy put just <? but it seemed to not like doing that
i just foud ever <? and made it a <?php
im getting there :D
edit: i got this all figured out now, it turns out the author is a little bit of an idiot
i might end up not using his code itll probally just be brining me in the wrong direction
<? is allowed in place of <?php if short_open_tag has been enabled in php.ini
If it has not then you can not use it.
alright im stuck once again. i started all over and ditched that other guys login system
i have finished making my own system in which you can login and register
( http://mrsako.gotdns.com/index.php )
its pretty nifty you can even try it if youd like.
how it works lets say your logging in you type in the information on login.php and you hit submit and it gets processed in a different .php file. and then it sends you back to the site after logging you in. or it sends you back to login.php if you had a wrong username or password. what i want to do is be able to have some text coming up saying "invalid username or password" is there a way i can do this with variables by having the processing php file assign $errormsg="bad uname or pass"; then have login.php echo(errormsg);
or do i have to do something like login.php?error=1
im not going to use cookies though thats just dumb, id rather do the login.php?error=1 method
You could always just send them to a login error page.
Otherwise, the only ways to transfer information between different php pages that I know of are POST, GET, cookies, and write it to a db/file.
You don't want cookies, writing it to a file/db is not needed, so looks like either post or get.
the only problem with using post or get is that all pages in your site will have to keep forwarding the variables, otherwise if they go back a page they will no longer be logged in. So you have to use at least session cookies to determine whether a person is still logged in or not.
yeh i use cookies to keep track if their logged in or out. but im trying to avoid cookies becasue not everyone has them enabled and you can just edit your cookie file to do stuff that maybe your not supposed to etc.
i decided to use the assiging variables at the end of the address way for the error reporting. my only slight concern is some browsers might trip up wth stuff like ! : and , being in the address
>>wth stuff like ! : and , being in the address
so don't put them in the address bar...why would you need to use those characters?
::edit::
Yes quite a few people disable or block cookies, but gmail and other sites for email make you use them. So if people need to log into your site then they need to use cookies, it's not uncommon.
also, cookies can be very safe for this type of thing. You just need to store the info in a hash of some kind, something unreadable. That way they can't just change a 0 to a 1 and get access, know what I mean?
php has that md5(); function. which im kind of thinking is a good idea, but if someone wanted to get in theres probally some kind of md5 reading programs out there
It may be better to use sessions, or something that simulates sessions. With sessions, the attacker has to get the session key, which would often be a MD5 or SHA1 hash, and so would be difficult (aside from 'social engineering' and carelessness). Another (but potentially slow) way would be to store the user id and some hashed key that changes on each page load, and then validate the user on each page load.Quote:
also, cookies can be very safe for this type of thing. You just need to store the info in a hash of some kind, something unreadable. That way they can't just change a 0 to a 1 and get access, know what I mean?
MD5 is a cryptographic hash algorithm, and while there are rainbow tables that allow people to 'reverse' the hashing for pre-computed values, no method other than brute force is known to get the original message given only the hash. Of course, I suggest using SHA1 with sha1() instead of MD5 anyway.Quote:
php has that md5(); function. which im kind of thinking is a good idea, but if someone wanted to get in theres probally some kind of md5 reading programs out there
Cain & Abel. ;)Quote:
php has that md5(); function. which im kind of thinking is a good idea, but if someone wanted to get in theres probally some kind of md5 reading programs out there
As, laserlight said, there is no real way of "undoing" a hash other than brute force hashing a dictionary file until you get a match. Though, doing so is actually surprisingly fast, these days.
*Note: SlyMaelstrom does not condone hacking.
yeh thats how i would do it. create a genourmous loop that puts in every character possibility in every order and check its md5 with the target md5Quote:
Originally Posted by SlyMaelstrom
Why would you put every character in every possible order? That's not what a dictionary file is, at all. Dictionary files consist of real word, combinations of real words, predictable usage of dates and initials (ie. gb1964). Most of which is compiled from other successful attempts of cracking. If all the passwords were just completely random combinations, what would be the point of hashing them in the first place?
some people do make random passwords. my passwords never form words, it would be more fool proof. but none of that is importantQuote:
Originally Posted by SlyMaelstrom
whats the command in php to check a string variable for a certain string of text within it.
ie i have a this variable $dir which is a location to the directory your browsing (im making a online web site control panel thing like alot of free web hosts have) and i want to say like
if in $dir theres the string "hosted/../" (spelled like that in that order) to change $dir to = "hosted"
i searched the php website i cant find the command for this. im using the latest version of php (im trying to make it so the user cant browse into directories hes not supposed to be in)
also is there a command to remove the last certain amount of characters from a string
ie
actualy does the double quotes make it an array of characters not a string?PHP Code:
$oldstring="tenletters";
$newstring=takeofflast($oldstring, 7);
if($newstring=="ten")
{
echo("it worked");
}
What you have to understand is when people bruteforce, they aren't looking for *your* password, they're looking for *any* password.
Here is your string function
http://us2.php.net/manual/en/function.strpos.php
...and your other question
PHP Code:
$foo = substr("Hello World!", 0, -7); // returns "Hello"
$foo = substr("Hello World!", 0, -8); // returns "Hell"
$foo = substr("Hello World!", 0, -1); // returns "Hello World"
ok another command question
i know stristr(); can find the first occurance of a character within a string. but how about the last occurance?
ie i have $dir=hosted/blah/blah2
i need it to seperate off blah2 by only looking at the string starting after the last /
nevermind, i should of done this before. typicg in stuff like
last occrance of string "php" in google usualy finds the command as the first result
im being dumb
2 things that you will need if you want to make a secure login system, beyond what you have, and also to be a decent PHP programmer:
Prepared statements, learn them, love them, thank your deity of choice for them, if you want to know why they are needed, look up SQL injection.
PHP Documentation, download that, and you will solve 90% of your problems, PHP has horid error reporting, but that documentation makes up for it because everything is laid out and every PHP command is in there.
Another thing for when you move to multiple files, consider making the seperate files classes, then you can just call them and use them at your discretion. Who ever said putting the form post to the same file makes for ugly stuff, it is really simple with well placed comments and using the format:
I picked up PHP programming because I was given the task of reworking the security and adding a bunch of features to the site. I had about 30 pages of PHP dumped on me and not one day in my life scripting with it. Luckly it is a lot like Perl (so simular it ........es me off sometimes when I try to use a function that is in one, and not the other) so it was a quick learning process.Code:if($_POST['HAX']){
// do stuff
exit (0); //So that you don't go farther into the file
}
Wikipedia and Google will be your friends if you can't find the type of command or usage of a command you are looking for in the documentation.
yes thats what i have been doing, i have a book on php, though it uses php 3 or 4 or something so its sligthyl old. but alot of it was useful and it went through the importance of checking ever command like that
Also, php.net is very useful.
Just go to php.net/function, to get the man page on it along with user comments, etc.
i have this part in my code. which DID work then out of nowhere it stopped working and i cant understand it. this is apart of my registration process to make sure the user input the right kind of information
whenever they input something wrong it goes into the first if statement (with all the ||) if nothing is wrong it skips over the if statement, like it should be.PHP Code:
if(($username_check > 0) || ($usersite_check > 0) || ($usersite_check2==0) || ($password_check==0) || ($email_check2==0))
{
if($username_check > 0){
header("Location: register.php?error=2"); //Sorry, that username already exists
}
if($password_check == 0){
header("Location: register.php?error=3"); //The Password and Confirmation Password you entered do not match
}
if($email_check > 0){
header("Location: register.php?error=4"); //sorry that email is taken
}
if($email_check2 == 0){
header("Location: register.php?error=5"); //The Email and Confirmation Email you entered do not match
}
if($usersite_check > 0){
header("Location: register.php?error=7"); //Sorry, that web url is taken
}
if($usersite_check2 == 0){
header("Location: register.php?error=8"); //your web url can only contain letters and numbers
}
header("Location: register.php?error=9991"); //if somehow they got through those if statements, send em back to register
die("error, report to webmaster ($site_email)");
}
see how on the bottom i have the "//if somehow they got through those if statements, send em back to register" part. well when it goes inside this if statement, which means it had to qualify as one of the if statements which are seperated with ||. but it NEVER will go into the ifstatements below it, and always goes to the backup header command i put.
i can't figure out why it does this, it also skips over them if i place them outside the "mother" if statement
I haven't done much php, but looking at the structure of the conditional it's pretty obvious that
a) the header for error # 9991 will always be sent if any error occurs
b) up to six additional headers will be sent depending on how many fields are invalid
it seems to me that you'd only wany to send one header if an error occurs. in that case, why not string together all of the errors and send them as a single header?
And as a side note, sending relative URLs in the Location header field is a violation of the HTTP spec, even though practically all user agents accept it. (Lynx prints a warning.)
Quote:
Originally Posted by Sebastiani
that was actually my plan, and thats when i figured out that my registratinon check process was broken.
actualy as i am typing this now i realised that i don't even need that whole section
lynx?Quote:
Originally Posted by CornedBee
I'd assume he means http://lynx.browser.org/Quote:
Originally Posted by MisterSako
oh i've never heard of it before.
im thinking the fact it's a text only browser would probally very very few to none visitors are going to see my site with lynx
Perhaps. But the fact that it's a text browser makes it a great tool to check your site for basic accessibility. It gives you the answer to the question, "Does my site work if someone doesn't have all the niceties of a modern browser?" Think about mobile phones and other simple devices.
I also just mentioned it because it's picky enough to actually mention your HTTP violation.
I often use Lynx during setting up my Linux computers, by the way, when I need to check something about hardware or download some file. That's before I get a GUI running, so I can't use anything better.
hmm that is a good point. i guess the goal of computer sceince isnt ALWAYS to be lazy :-p
on another note invovlnig my registration process. it jsut occured to me that if you get a error all the fields will be blank if you inputed some wrong data, which could be annoying to the user if they had to write alot of stuff. they could hit the back button and have their infortmation back, but that seems amatuerish and plus it may not always work because of peoples bowsers and stuff.
so im thinking, if i send their input values back through from the process.php file to the register.php file using GET so that the value of the fields will be as they last entered them .
( value="<?php $username ?>" )
could this pose any kind of secruity threat? i dont normally like to just print out variables like this without using some kind of checker statement to verify that the user didnt type their own stuff in the address bar. but this is the only thing i can think of doing besides combining the registering and processing functions into one document.
Which, slightly modified, is not a bad idea. Basically, you should always separate processing and displaying in the code anyway. If you have both well encapsulated, it's easy to make the two effectively the same, so you can directly reuse the values.Quote:
besides combining the registering and processing functions into one document.
That said, there is no security issue with just GET-forwarding the variables - the only problem would be the long querystring, which might be longer than what the server wants to handle. (I think Apache rejects URLs longer than ~1000 characters, perhaps even less.)
Well, don't forward the requested password, as it would appear in clear text in the URL, and users might not like that.
Boy, I wish I had found this thread sooner because then I wouldn't have to make such a huge post. Here it goes:
Yes, infact it's quite common for smaller scripts. Take for instance this bare bone code:Quote:
Originally Posted by MisterSako
All this requires is that in your forms you include a hidden variable called action so you can easily find out what you should be doing in your code. If you didnt specify an action variable you'd have huge if statements check for which variables should be defined. By using a simple action variable you group your variable checks into single sections. Nice neat code.PHP Code:
switch($_REQUEST['action']) {
case "login":
login();
break;
case "search":
search();
break;
default:
main_page();
break;
}
function login() {
// check if $_REQUEST['user'] and $_REQUEST['pass'] is set
// .. if not display login form and return;
// if set, check if this is a valid login (escape input if this is a mysql ceck.
// $usrname = mysql_real_escape($_REQUEST['user']);
// $passwrd = mysql_reql_escape($_REQUEST['pass']);
// $sql = "select * from login_table WHERE user = '$usrname' AND pass = '$passwrd'";
// .. if result is null display bad login message, display login form again and return;
// if login is good, set session variables, and forward back to the main page.
}
function search() {
// check if search input is specified, if not display search form
// if search is specified display search results return;
}
function main_page() {
// display your main page
// return;
}
The problem with your second loop not working is that you've already looped through all the record sets. Mysql queries return a record set just like an associative array.Quote:
Originally Posted by MisterSako
The code:
Says logically while mysql returns me a record set I want to do this loop. I dont want to exit until fetch_array is null. Hence you come out of the first loop already at the end of your array. Luckily, mysql has a handy dandy function that allows you to reset the record set index. It's mysql_data_seek. However, you should rewrite the code so you don't need to do this as its very unefficient and theres probably a tremendously better way to do it. It looks roughly like you want to know how many QnA's you selected. So you can use mysql_num_rows() To find out.PHP Code:
while($row = mysql_fetch_array( $result ))
In the php.ini file there's some php tag options. One is asp tags, the other is short tags (<? ?>).Quote:
Originally Posted by MisterSako
Quote:
Originally Posted by php.net
The customary method is to stay at the login page on error. Ie if the login is being processed on a seperate file, you could also have the same login form in that page so you can echo out an error and display the login again. You could also use session variables even though the user hasn't logged in yet. Just set $_SESSION['login_error_msg'] = "you failed at loggin in"; Then on the main page check to see if the variable is set, if so display the message.Quote:
Originally Posted by MisterSako
Session's are the standard form of variable storage. To keep things secure, the onlything that should be stored in a cookie, is a session id. If they edit the value, then all they do is lose their session.Quote:
Originally Posted by MisterSako
Use strpos to find the location of a string within a string. If the string does not contain the search, it returns false. In php to determine the difference between false and 0 (because a sub string could start @ 0) use !== or ===. The three character signs mean check variable type as well as value.Quote:
Originally Posted by MisterSako
Not a command persay, but very easy to accomplish.Quote:
Originally Posted by MisterSako
use -8, because character indexes are 0 based, but strlen is 1 based.PHP Code:
$newstring = substr($oldstring, strlen($oldstring)-(8), 7);
This is a fun one, as it involves a neat logic trick.Quote:
Originally Posted by MisterSako
PHP Code:
$search_str = strrev($str);
$needle_str = strrev($needle);
$last_pos = strpos($needle_str, $search_str) - (strlen($search_str) - strlen($needle_str));
// (13)
Hello World! World! // 18 long
// (5)
!dlroW !dlroW olleH // 18 long
// 18 - 5 = 13 // huzah
Welcome to the Repeating Department of Redundancy Department (RDR Department).Quote:
Originally Posted by MisterSako
Chop off the first if statement and just use the nested statements. Also, if you are using cookies, you should be aware that header() tends not to work as session_start() sends out header statements that will make the header() function error out. Use a javascript, or html meta redirect instead unless you know your session isn't going ot use cookies and send out headers before hand.
Just conformation here:Quote:
Originally Posted by CornedBee
http://www.zend.com/zend/spotlight/mimocsumissions.php
Quote:
Originally Posted by Zend
i can't seem to figure out how to send POSTs between pages without it being a form. can someone give me an example of a variable being sent to a page using the POST method (with out it behing a form)
i would appreciate it
To my experience, it's not possible. Did you use the following, by the way? I don't see any disadvantage of using it.Quote:
Originally Posted by MisterSako
Code:<form ...>
<input type="hidden" name="someName" value="someVal" />
...
</form>
Quote:
Originally Posted by MisterSako
Theres no NEED to send post variables across pages. Instead, you save the post variables in your session data, and check that data in the next page.
i don't get this,
i POST to my process file so i can get the variables with $username = $_POST['username']; type of thing but i don't get why i cant just use that same thing again once it directs the user back to the registration page to have the textfields show what they last had.
do i have to "rePOST" the variables use time i go from document to document?
ive tried sending the user back to the register page using
META HTTP-EQUIV=Refresh CONTENT="2; URL="
as well as header: location
Another option is to pass it in query string.
Cookies is another, if it's appropriate at all.Code:$redirect_to = 'http://mysite.com/register.php?username=' + urlencode($username);
Pretty much yes. Consider using sessions.Quote:
do i have to "rePOST" the variables use time i go from document to document?
i think im going to try and use cookies for this
Quote:
Originally Posted by MisterSako
It seems clear you are either really unclear on what sessions are all together, or you just don't get it.
Your POST variables are ways for your users to REQUEST something of you. In order to do that, they are sending extra data to your page. Believe it or not, there is an Overhead here that while not remarkble will add up in worse case scenarios. Once a user has sent data to you once, theres absolutely no reason to continue to cary it around via request methods. Instead, you save the data in SESSIONS. Sessions stay across multiple pages and even multiple visits.
To use sessions, it's really this simple:
Afterwards, on any other page in your site:PHP Code:
<?php
session_start();
// if the user has sent us a variable via GET or POST, save it
if(isset($_REQUEST['a_variable_name']))
$_SESSION['a_variable_name'] = $_REQUEST['a_variable_name'];
?>
PHP Code:
<?php
session_start();
// for some reason i want to display the form again
// with the data they originaly sent me
echo "<input type='text' name='a_variable_name' value='{$_SESSION['a_variable_name']}'/>";
?>
It's really very simple.
i understand the purpose of sessions ive just gone crazy pulling my hair out to try and get it to work.
on a side note does php have a limit no how long a if statement can be. i got into a weird situation where its like
and the else part only has partially the stuff it should have, wihtint that 500 lines theres ?> and <?php and ?> and <?php alot of times so maybe they could be messing it up.PHP Code:
if (this){
//10 lines of code
} else {
like 500 lines of code
}
Quote:
Originally Posted by MisterSako
No.
For the intranet I maintain at work, I have multiple files with 1000+ each. Php is more then capable.
i must have some kind of oddly placed } or something
You should split your code a bit to make it more organized.
i try to, but there is also a pointy if i have too many different php files ill eventualy be overwhelmed with a plethora of php files that are all used for one thing
is there a alphanumeric test code that actually works?
i want it to tell me if there are any characters in a stringbesides a-z A-z or 0-9
i tried
if (ereg('[^A-Za-z0-9]', $string))
and i tried
if (ctype_alnum($string))
both will not work, theyre always wanting to say everything i input is alphanumeric even if its like ♠ܥ
Quote:
Originally Posted by MisterSako
http://www.tote-taste.de/X-Project/regex/
http://www.phpguru.org/downloads/PCR...at%20Sheet.pdf
use http://www.quanetic.com/regex.php to test. I use it all the time. It does have a bug where you have to use double '\'s to work on special chars. so \d would be \\d
A '^' outside means match the beginning of the string.
what you want is /[a-zA-Z0-9]/
also, i'd use preg_match:
PHP Code:
if(preg_match("/[a-zA-Z0-9]/", $str))
echo "bad input!";
Actually, you might as well use ctype_alnum(), which is like C's isalnum() from <stdio.h>
Should be faster (and somewhat simpler) than using regex, but then is literally limited to testing that each character of the whole string is indeed in the range of A-Za-z0-9
Unfortunately, Jeremy G, your use of preg_match() is wrong. Your pattern matches any alphanumeric character, spewing out a "bad input!" message if one is found. Correct is:Quote:
also, i'd use preg_match:
EDIT:PHP Code:
if (preg_match('/[^A-Za-z0-9]/', $string)) {
echo "bad input!";
}
I see that you have tried ctype_alnum() and it didnt work. Most probably you have to do a:
before you use ctype_alnum()PHP Code:
setlocale(LC_CTYPE, 'C');
It was a typo. I make mistakes.Quote:
Originally Posted by laserlight
Every once in a while. The //'s are what i was going for.
Quote:
Originally Posted by laserlight
just out of curisoty so i know whats going on in my code, what does that line do?
on more thing is, i want to host my mysql database on a seperate server, which i have one kind of, except it won't connect
don't i just type the IP address of the server wiht mysql on it? ie now i type in localhost because the web and mysql servers are on the same machine
It switches the locale to the 'C' locale, which is fairly language-neutral. (Or rather, language-ignorant - it has absolutely no proper treatment of anything outside English.)