I am trying to create a very simple session between 3 php pages as: index.php ,validate.php and target.php
index.php
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="validate.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and validate.php as:
<?php
session_start();
$err="Not Allowed";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: heaven.php");}
else
{echo $err; }
?>
and finally target.php as
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
Now my questions are:
How come user still can get access to target page while I have already set a session between pages(according to my understanding of sessions the target page must NOT be accessible unless the correct seesion value has been submitted but I can get access to page by clicking on page link in wamp index list! with echoing the $err; ! )
I tried to validate the $_SESSION value by using the isset() but it did'nt go through! can you please let me know how I can modify the validate.php using the isset() instead of if(($_POST['name']) == $_SESSION['uid']) comarison?
Can you please let me know how I can merge two (index.php and validate.php) in one page? I mean how I can validate the session inside the index.php and reduce the files two index and target? In this case I need to handle the wrong logins inside the index page.
Finally, can you please let me know how I can assign the value to $_SESSION from user input? I mean instead of having a hard coded part like $_SESSION['uid'] = 'test'; let the session value start with user input! I know this looks meaningless here but I would like to get idea on creating captcha in same index page
Thanks for your time in advance
This should work properly and just with 2 files. You could even compress it to 1 file, if you really want so (it's much harder to understand), ask for it and I can make it.
index.php:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="heaven.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
And the other file, heaven.php
<?php
session_start();
if (!empty($_SESSION['uid'])&&$_POST['name']==$_SESSION['uid'])
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
<?php
}
else
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Access denied</title>
</head>
<body>
Sorry, you have no permission to access this page.
</body>
</html>
<?php
}
?>
'Validation' is just to display the desired message if the strings match or to display a 'you cannot see this page' if they don't match.
The !empty() needs to be set. Else, imagine what would happen if someone visited the 'heaven.php' page without going first to index.php. You'd compare 2 empty strings! So it would be validated. The alternative is to put $_SESSION['uid'] = 'test'; at the beginning of heaven.php also.
I didn't really answer your questions in order (and in the 2nd one I cheated as I put 2nd and 3rd file together instead of 1st and 2nd), but my code should cover all your problems. For the last part, it's simply $_SESSION['uid']=$_POST['name']; , but it'd be a no sense to do it while validating user. The validation must come from somewhere, generally from a mysql database.
Please start to accept answers to your questions if valid (below the up/down button).
1) What do you mean by assigning correct session value? "heaven.php" is a file which is accessible by anyone if you don't check for access rights in that file.
2) Not sure what you mean. If you need to check if two variables exist and match, you need something like if ( (isset($_POST['name']) && isset($_SESSION['uid'])) && (($_POST['name']) == $_SESSION['uid']) )
3) If there's no need to reduce files to minumun, it's a good idea to keep validating, form processing etc. function in their respective files. If you want to valide session and form values within "index.php" you can do so by first checking if the values exist and then do to them whatever you like. (Like in the 2 above.)
4) You can assign user inputted values for variables by using forms. It's what you are doing with your form currently. In you process file/function you do something like:
if(isset($_POST['submit']){
$_SESSION['uid'] == $_POST['name'];
}
The example above is very simplified.
Finally. You aren't really validating anything, you just check if two values match. Validating means that you make sure value meets the standard(s) specified, for example user submitted value is an integer when it should be an integer (when inserted into database or used some other manner). I think you should see some tutorials about form processing and user input validation before creating anything that's intended in production environment.
Related
I would like to include a PHP page to protect every single page and after you login, it would show your username on the top right corner,
also it limits the only data that login user had provided such as his CV and personal info but without seeing other users info.
the structure will be the same as the previous post
index.php (include header.php, content.php and footer.php)
The title on the header.php will be changed menu after user login
Thank you.
Regards
Andy
Well if you want a script to ensure that it would be something like this:
first: Assuming you're not using design patterns and it is a php basic project with an archetype like " scripts(folder) css(folder) js(folder) index.php header.php and footer.php". lets create "security.php".
<?php
session_start(); //starting session to acces to it
if(empty($_SESSION["username"])){// if there's no data username in session
header("location: ./login.php"); //go and take them out of here!
}
?>
Now you have "security.php" ready you just have to include it to your protected pages and create a "login.php" page.
Ex: For including security.
<?php
//#mySecurePage
include "security.php";
//My Page Content Code or event header code if you want validation after loading anything (Best)
?>
Second: Create a Login page like.
<?php
if(!empty($_POST["username"]) && !empty($_POST["password"])){// if all data from login was sent
if($_POST["username"] == "me" && $_POST["password"] == 1234){//your validations here
session_start();//start session to acces it
$_SESSION["username"] == $_POST["username"];//allocate username
header("location: ./securedPageHere.php");//forward to a securedPage
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Login Page</title>
</head>
<body>
<form class="" action="" method="post"><!-- action is empty to send data to same page (login)-->
<input type="text" name="username" value="" placeholder="username">
<input type="password" name="password" value="" placeholder="password">
<input type="button" name="login" value="Login">
</form>
</body>
</html>
Now we're almost done, just need to load username at your menu bar
Third: Load username at menu bar. Just add the value accesing session (remember if you have loaded "security.php" you've already started session
<div><?php print($_SESSION["username"]); ?></div>
Now to use the Logut Button you have to destroy session, so add a listener to it and then just execute a script like:
<?php
unset($_SESSION); //clear session array
session_destroy(); //Destroy session
?>
Hope it helps you.
EDIT: to limit data accessed just use the username (best id) data from the login verified data saved at session array :).
I have just started to learn HTML and PHP, but have run into a road block while following beginner tutorials. I am attempting to have the user input numbers into a form on the HTML page, then press submit to redirect to a PHP page that displays the values. The PHP page shows up and successfully displays prepared text but displays nothing for the values.
HTML code:
<html>
<body>
<head>
<title>Practice Page</title>
</head>
<h1>Numbers</h1>
<p>Put numbers in the boxes</p>
<form action="welcome.php" method="post">
NumOne: <input type="text" name="oynumone"><br>
NumTwo: <input type="text" name="oynumtwo"><br>
<input type="submit" value="Submit" id="SubmitRegister" name="submit" />
</form>
</body>
<html>
PHP code:
<html>
<body>
Number one is <?php echo $_POST["oynumone"]; ?><br>
Number two is <?php echo $_POST["oynumtwo"]; ?>
</body>
</html>
Both of the files are simply in the same folder in my documents. I understand that I need a server to host PHP content; I have downloaded MAMP for this, but I don't yet understand how to use it.
Any help would be most appreciated.
Store both file name with .php extension AND/OR update Welcome.php like below -
Welcome.php
<?php
if isset($_POST['submit'])
{
$oynumone = $_POST['oynumone'];
$oynumtwo = $_POST['oynumtwo'];
echo "Number one is ".$oynumone;
echo "Number two is ".$oynumtwo;
}
?>
Also check this
I want to use the php session to pass the username to the second page
but it shows error.
Notice: Undefined index: nam in D:\software 2\wamp\wamp\www\session\s2.php on line 5
my first page(s1.php) is like this
<html>
<head>
<?php
session_start();
?>
</head>
<body>
<p>hello</p>
<form method="get" action=" http://localhost/session/s2.php">
<input type="text" name="nam"><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
my second page (s2.php) is bellow
<html>
<head>
<?php
session_start();
echo $_SESSION['nam'];
?>
</head>
here is the second page
<body>
</body>
</html>
thanks
Variables are not inserted into the session automatically. You need to insert them somehow. If you want to get the variables from the get paramaters posted by the form $_GET is what you are looking for.
eg:
$_SESSION['name'] = $_GET['name'];
Have a look through dealing with forms
You need to put session start at the top
<?php
session_start();
?>
<html>
<head>
You're most likely not seeing the error that is generated.
Also, after the data is submitted, you won't have it in the SESSION yet, it will be in $_GET['name']
I would recommend that you set the error_level to E_ALL while working on your local machine
In PHP, variables from a form are passed via GET or POST. In your case, you used
<form method="get" action=" http://localhost/session/s2.php">
So the type is GET (method="get"). To read GET variables, use _GET, not _SESSION. If you want POST variables, use _POST.
In your case, use _GET['nam'] instead of _SESSION['nam']
you should either :
add this line before echo $_SESSION['nam'];
$_GET['nam']=$_SESSION['nam'];
or
echo $_GET['nam'];
Good Luck
Recently installed wkhtmltopdf. Was trying to capture the entire page in its current state, however, the below method seems to navigate to the initial state of that page without all the input fields that the user has entered.
PHP
shell_exec('wkhtmltopdf http://localhost/www/bolt/invoice.php invoice.pdf');
I was wondering if someone knew of an implementation of wkhtmltopdf that captures the current state of the page including any text entered in the text fields??
I appreciate any suggestions.
Many thanks in advance!
wkhtmltopdf hits the page independently of your current browsing session. If you hit it like that, you're going to get what anyone would see when they first go to your page. Probably what you want to do is save the current page using an output buffer, and then run wkhtmltopdf on the saved page. Here's some sample code:
sub.php
<?php
$documentTemplate = file_get_contents ("template.html");
foreach ($_POST as $key => $postVar)
{
$documentTemplate =
preg_replace ("/name=\"$key\"/", "value=\"$postVar\"", $documentTemplate);
}
file_put_contents ("out.html", $documentTemplate);
shell_exec ("wkhtmltopdf out.html test.pdf");
?>
template.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>This is a page</h1>
<form action="sub.php" method="post" accept-charset="utf-8">
My Test Field:
<input type="text" name="test_field" value="">
<input type="submit" value = "submit">
</form>
</body>
</html>
Probably in the long run you should have some kind of base template that both pages would use, and one have some markers like value='%valueOfThisVariable%' in your input fields that you can replace with blanks when you present the fields to the user, and fill with the user data when you create the page that you want to write to pdf. Right now it's just going through and replacing all the name='this_name' with value='this_name->value'.
For some web development practice, I decided to make a dropbox-like site where users would login with a username and password and, assuming the combination is correct, would have access to a file uploader interface as well as a way to retrieve their files. I have something that works, but I have run into one problem. As soon as the user submits their username and password, the page is reloaded (this is fine) with the new php code, however, the URL changes slightly to where it reveals both the username and the password. Can someone tell me how to prevent this from happening?
Here is the index.php file:
<?php
function checkCredentials()
{
if($_GET && $_GET["username"]=="kwaugh" && $_GET["password"]=="password")
{
?>
<html>
<head>
<title>File Storage</title>
<style>
body{font-size:.85em ;font-family:Arial;}
</style>
</head>
<body>
<center>
<br>Please select the file that you would like to upload:<br><br>
<form method="post" enctype="multipart/form-data">
<input type="file" name="filename"/>
<input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
<?php
if ($_FILES)
{
$name = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $name);
if(file_exists($name))
{
?>
<html>
<body>
<div style="color:red; font-size:2em; font-family:Arial">
<center>The file has been successfully uploaded <br />Click here to go to your uploaded files</center>
</div>
</body>
</html>
<?php
}
else
{
?>
<html>
<body>
<div style="color:red; font-size:2em; font-family:Arial">
<center>Well crap, something went wrong. The file could not be uploaded :'( </center>
</div>
</body>
</html>
<?php
}
}
die();
}
elseif($_GET && $_GET["username"]!=="kwaugh" || $_GET && $_GET["password"]!=="password")
{
?>
<script>
alert("You have entered an incorrect username/password combination");
</script>
<?php
}
}
checkCredentials();
?>
<html>
<head>
<title>File Storage</title>
</head>
<body> <br /><br />
<center>
<img src="elephant.jpg">
<form name="credentials">
Please enter your username and password to upload files: <br />
Username: <input type="text" name="username"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Submit" >
</form>
<br />Or click here to access stored files.
</center>
</body>
</html>
Use POST for your credentials form. By default, the method is GET which will append the parameters in the URL. Obviously, this means checking variables in the $_POST array instead of the $_GET array.
If I can give another suggestion, I would split the application in multiple files. You shouldn't have the login and the upload interface in the same script, otherwise you will have major problems scaling up your application.
As you add pages, it will be almost impossible to know which part of the script should run and using which parameters and outputting what html
You will need to pass a "state" to the page so that you internally know what the user is trying to do - spreading the logic over multiple php files would make it easier to do.
The file will grow a lot, making it harder for you to understand what's actually getting executed, making it harder for you to debug
If you ever start working with other developers, it would be more "developer friendly" to break the features in separate php files to minimize conflicts when editing the files
A lot of web applications will be split in multiple pages (often implemented in a controller) where you would have the following:
Welcome Page (landing page, allow to log in, allow sign in, display information about your product)
Authentication Page (validate log in then redirect to the Profile page, show the sign in form, validate it, create new users, etc...)
Profile Page (for a logged in user, display his information)
To this you should probably add a File Management page that shows all files owned by a user, allows him to add / delete pages, etc...
Use:
<form name="credentials" method="post">
and
if($_POST && $_POST["username"]=="kwaugh" && $_POST["password"]=="password")
Use POST in your form and $_POST in your PHP code.
<form name="credentials" method="post" action="whatever-page.php">
and
if ($_POST["username"]=="kwaugh" && $_POST["password"]=="password")
change the login <form> to have a method of POST
<form method="POST" name="credentials">
Also, consider breaking up your web site into multiple .php files - you can't have everything in one file as it becomes unmanagable for all but the most simple sites.