I am a beginner to PHP and i want to make a static method that if its argument is empty it'll show the message. If not, it'll set the given message to a static variable for later use. But when i call the method to set the message, and then call it in another page to show the message. Nothing appear.
Here's my portion of code for this "session.php" :
class Session {
public static $message;
public static function notify($message = ""){
if(!empty($message)){
self::$message = $message;
} else {
return self::$message;
}
}
}
$session = new Session();
"add_user.php" :
<?php
require_once '../helper/session.php';
?>
<?php
if (isset($_POST["submit"])) {
$user->username = $_POST["username"];
$user->password = $_POST["password"];
$user->first_name = $_POST["first_name"];
$user->last_name = $_POST["last_name"];
if($result = $user->add_user()){
Session::notify("New user added");
redirect_to("../view/login.php");
} else { Session::notify("Cannot add new user"); }
}
?>
"login.php" :
<?php
require_once "../control/add_user.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../stylesheet/login.css" />
<title>Welcome to Harmony</title>
</head>
<body>
<header>
<h2>Harmony</h2>
</header>
<section>
<div id="formStyle">
<h3>Login or Signup:</h3>
<form action="login.php" method="post">
<p><label for="username">Username: </label>
<input type="text" name="username" value="" placeholder="Username"/></p>
<p><label for="password">Password: </label>
<input type="text" name="password" value="" placeholder="Password"/></p>
<input type="submit" name="submit" value="Submit" />
<input type="button" name="sign_up" value="Sign up" onClick="parent.location='add_user.php'">
</form>
<?php echo Session::notify(); ?>
</div>
</section>
</body>
</html>
You aren't really writing to the session, now are you?
You should create two more methods for getting and setting the variables in the actual session. After the redirect, your message dissapears, because it is only saved on script execution.
function set_notification($message) {
$_SESSION['notification'] = $message; }
function get_notification() {
if(!empty($_SESSION['notification'])) {
return $_SESSION['notification']; }
Something like that :)
Of course, for sessions to work, you should do a session_start() call in the beginning of the script. read more about them here
HTTP by nature is shared-nothing, so anything you do in one request is not available to any other request. You will need to use a shared datastore to persist these messages.
A database, memcache, even a text file on the server (assuming you are operating on a single server and are not load balancing multiple) are all choices.
You can use cookies on the client side to persist a small amount of data. But keep in mind its not a secure solution (without using encryption) and you are limited in the amount of data you can store in cookies.
HTTP - and PHP - is stateless. You need to use session variables to track data across sessions
http://www.php.net/manual/en/book.session.php
Related
I want to put a honeypot on my website to stop spambots from filing out my form.
I found this answer which seems useful. It advises to include an invisible checkbox on your page:
<input
type="checkbox"
name="contact_me_by_fax_only"
value="1"
style="display:none !important"
tabindex="-1"
autocomplete="off"
>
But then, PHP is suggested to test whether the checkbox has been checked:
$honeypot = FALSE;
if (!empty($_REQUEST['contact_me_by_fax_only']) && (bool)
$_REQUEST['contact_me_by_fax_only'] == TRUE) {
$honeypot = TRUE;
log_spambot($_REQUEST);
# treat as spambot
} else {
# process as normal
}
I've not used much PHP before. My questions:
Can I just put this PHP in my html code with surrounding <?php ?> tags?
If so, does it matter where I put the PHP? Does it have to be after the form (for example)?
In the part of the PHP that says #process as normal, do I need to put anything in here?
Or am I supposed to put the PHP in my post.php file which I created to post my form?
If it helps, the form part of my html code:
<form action="post.php" method="post">
</br>
<label for="email"></label>
<input type="email" placeholder="Enter your email address..."
name="email" required>
<button type="submit" class="signupbtn">Sign Up</button>
<input type="checkbox" name="contact_me_by_fax_only"
value="1" style="display:none !important" tabindex="-1" autocomplete="off">
</form>
I'm trying to follow the answer on this. I'm still not sure where everything should go. I don't understand when I am telling the code to do when it's a human response; I want it to submit the form, but I don't know how it fits together with the php.
<html>
<head>
<title>Page Title</title>
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="shortcut icon" href="fav.ico" >
<meta name="description" content="">
</head>
<body>
<div class="home_pic">
<img border="0" style="border-color: black" src="pic1.png"
height="700px">
</div>
<div class="home_text">
Some words for the website
</div>
<?php
if (isset($_REQUEST['contact_me_by_fax_only']) && (bool)
$_REQUEST['contact_me_by_fax_only'] == TRUE) {
$honeypot = TRUE;
log_spambot($_REQUEST);
// treat as spambot -- I don't need it to *do* anything if spambot
?>
<?php
exit(); // all done if a spambot
} else {
// process as normal -- here we will use a function, note that in PHP
// scope rules will hide most global variables from the function!
process_human_response();
}
function process_human_response()
{
<!--DOES THE FORM GO IN HERE NOW?-->
<form action="post.php" method="post">
</br>SIGN UP:
<label for="email"></label>
<input type="email" placeholder="Enter your email address..."
name="email" required>
<button type="submit" class="signupbtn">Sign Up</button>
<input type="checkbox" name="contact_me_by_fax_only"
value="1" style="display:none !important" tabindex="-1" autocomplete="off">
</form>
?>
</body>
</html>
Sorry, I'm very confused.
In the accepted answer to Better Honeypot Implementation (Form Anti-Spam)
That is the PHP for the processing page that your form submits to.
Copying code from Nicholas Summers' post, I'll add some sample HTML to clarify it.
<?php
$honeypot = FALSE;
if (!empty($_REQUEST['contact_me_by_fax_only']) && (bool)
$_REQUEST['contact_me_by_fax_only'] == TRUE) {
$honeypot = TRUE;
log_spambot($_REQUEST);
// treat as spambot -- here we will place the HTML "inline"
?>
<html>
<body>
<p>Tasty spam, thanks!</p>
</body>
</html>
<?php
exit(); // all done if a spambot
} else {
// process as normal -- here we will use a function, note that in PHP
// scope rules will hide most global variables from the function!
process_human_response();
}
function process_human_response()
{
//... get data from $_REQUEST
//... process data
?>
<html>
<body>
<p>Thank you good human!</p>
</body>
</html>
This shows placing your code and HTML "inline" at the global level for the first case (spam) and in a function for humans just to show another way.
As pointed out, the code is often shorter and easier to maintain if you don't duplicate any of the shared HTML, like this:
Shared beginning of page:
<html>
<head> <!-- and shared CSS, JS files here --> </head>
<body>
Some PHP logic to decide if it is a spambot
<?php
if (isset($_REQUEST['contact_me_by_fax_only']) && (bool)
$_REQUEST['contact_me_by_fax_only'] == TRUE) {
$honeypot = TRUE;
log_spambot($_REQUEST);
// treat as spambot -- here we will place the HTML "inline"
?>
Include the response HTML for a spambot, done "inline". Because this is in the "if" case of the PHP code this HTML will only be sent to the browser when the if test is true (= spambot)
<p>Tasty spam, thanks!</p>
Continue the PHP code for the if case, then switch to the else case.
<?php
exit(); // all done if a spambot
} else {
// process as normal -- here we will use a function, note that in PHP
// scope rules will hide most global variables from the function!
process_human_response();
}
?>
Shared HTML for end of page
</body>
</html>
The function called about to process a human response
function process_human_response()
{
//... get data from $_REQUEST
//... process data
?>
This HTML is inside of the function, so it is only sent if this function is called
<p>Thank you good human!</p>
finish the function
<?php
}
?>
I started PHP recently and I was wondering :
I have a php file which only contains a function called sqlConnect(); which checks that the user isn't yet logged into the MySQL DB, and if so, redirects the user to an html page which is a form for the user to enter the username and password for the DB. After the user has submitted the form, I want to get back to the point where I left (in the function).
One thing you should know too is that the $_SESSION is started in another file which calls this function.
Here's what I tried, yet it didn't work :
connect.php :
<?php
function sqlConnect() {
$_SESSION['CurrentPage'] = "/php/sql/connect.php";
if(!array_key_exists('mysql_username', $_SESSION) && !array_key_exists('mysql_passwd', $_SESSION)) {
echo "<script>window.location='/forms/sql_login.php';</script>";
}
$servername = "localhost";
$username = $_SESSION['mysql_username'];
$passwd = $_SESSION['mysql_passwd'];
$db_name = "ToolDB";
// create connection
$sql_connection = new mysqli($servername, $username, $passwd, $db_name);
// check that it was established
if($sql_connection->connect_error) {
$msg = $sql_connection->connect_error;
echo "<script>alert('Impossible de se connecter à la base de données MySQL : $msg.');</script>";
return NULL;
}
else {
$_SESSION['mysql_username'] = $username;
$_SESSION['mysql_passwd'] = $passwd;
return $sql_connection;
}
}
?>
sql_connection.php :
<?php session_start(); $url = $_SESSION['CurrentPage']; ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Sound Department - Program Making Tool (form)</title>
<link rel="stylesheet" type="text/css" href="/style/style.css" />
</head>
<body>
<header>
<nav>
<h2 style="margin-left: 10px; font-family: sans-serif;">Sound Department - Program Making Tool (MySQL Login Page)</h2>
</nav>
</header>
<div class="bodyElement">
<form action="<?php echo $url ?>" method="post">
<p>Nom d'utilisateur : <input type="text" name="mysql_username" /></p>
<p>Mot de passe : <input type="password" name="mysql_passwd"/></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</div>
</body>
</html>
Does anybody know how to achieve that ?
PS : I know I shouldn't store the password in plain text, but the site is running on my local network for now and I thought I was just gonna modify my code to store the password in a more convenient way later.
ob_end_clean();
header("Location: example.com");
exit();
Put this at the end where you want the user to be redirected.
Header() doesn't let you redirect after an output is given, but
ob_end_clean()
allows you to redirect after an output.
You can use the header() function to redirect clients to another page.
<?php
header('Location: <your page>');
exit;
?>
I'm not quite sure why is this happening. After a bit of research and a few shots ate solving it I'm finally giving up and asking for help. My problem is that I start a session on a page (controle.php) and create an array at $_SESSION["agenda"], but I only what to create it at the first time. After that I want to add elements to it with array_push($_SESSION["agenda"], $Contato), where $Contato is an object and I create a new instance of that object for every iteration. However, the data on $_SESSION["agenda"] is not persisting, every time the code runs it creates a new array. I've tried adding session_start() to the very top of the page, checked that my browser allows sites to save cookies. As for PHP configuration I'll post a picture because I'm ignorant in this area.
Here is phpinfo();
controle.php code:
<?php
session_start();
require_once '../Model/Contato.php';
$op = $_GET["op"];
if (isset($op) && $op != "") {
switch ($op) {
case 'add':
include '../View/novo.php';
break;
case 'cad':
if(isset($_POST["enviar"])){
$nome = $_POST["nome"];
$email = $_POST["email"];
$Contato = new Contato($nome, $email);
if(!isset($_SESSION["agenda"])){
$_SESSION["agenda"] = array();
}
array_push($_SESSION["agenda"], $Contato);
include '../View/sucesso.php';
}
else{
include '../View/erro.php';
}
unset($nome);
unset($email);
break;
case 'lst':
include '../View/lista.php';
break;
}
}
else{
include '../View/index.php';
}
?>
novo.php code:
<!DOCTYPE html>
<html>
<head>
<title>Novo Contato</title>
</head>
<body>
<h1>Criar novo contato</h1>
<form action="../Controller/controle.php?op=cad" method="post">
<label>Nome:</label>
<input type="text" name="nome" required="required">
<label>Email:</label>
<input type="email" name="email" required="required">
<input type="submit" name="enviar" value="Enviar">
</form>
</body>
</html>
I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O
I'm working with a .html and a .php. In the default.html the user must enter some info and when the button is clicked the html does a post to the default2.php.
In default2.php the data is checked and if it's correct it redirects the user to another page. The problem I'm having is when the data entered is wrong.
I'm having two issues here:
When the data is wrong I'm redirecting the user to the default.html, because if I don't do that, it will stay in default2.php and default2.php has nothing important for the user to see. I don't know if this is the best way to do this.
When the data entered is wrong, I want an echo message to the user in default.html. But I don't know how to trigger this from default2.php.
How can I solve these two issues?
Thanks...
default.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
default2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
Just add some parameter to
header("Location: default.html?test=failed");
And in html use Javascript to display something sensible when variable test is set to failed. You can find a tutorial how to get value of url parameter with javascript here.
Hope that helps.
Other than that you can use PHP in your default.html and perhaps even AJAX request to do validation without leaving the page and highlighting validation errors.
Personally, I don't like to expose states like "error" and "invalid" to the user using a query string. In this situation, I would merge the two files in one single PHP file, with the PHP code at the top and the HTML code at the bottom.
The if statement in the PHP code would be:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
And down in the HTML where you want to display the message:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
Ofcourse, in the form element, you would have to remove action="default2.php".
If you prefer separating the logic and the markup, you could change default.html to for example template.php and include it at the end of your controller php file.
I just don't like the idea of an extra page without any content that only acts as a redirector.
If you made default.html a PHP file, you could pass a variable via the URL, this would then allow you check if this variable has been passed using $_GET[]and show the user a message.
So for example, if you forwarded the user to
default.php?error=1
On the default page, you could have a segment of code such as
if (isset($_GET['error'])) {
echo "Show user a message here";
}