submit pressed then loaded function - php

login.php
<?php
class airsystem{
public function login(){
echo "check login";
}
}
$airsystem = new airsystem;
?>
index.php
<?php
require_once ("login.php");
if(isset($_POST['submit'])){
$airsystem->login();
}
?>
<input type="submit" name="submit">
my intention is to make the login system and the function only runs when i clicked submit, it mean "check login" only show if i click submit button. but the echo always there even i am not pressing the submit.
so mean it auto load the function , how i going to achieve that ??

If I recall correctly isset on a $_POST will cause you problems as it can be set but empty. Try using this which will ensure submit is set and populated:
<?php
if( !empty($_POST['submit']) ){
require_once ("login.php");
$airsystem->login();
}
?>
Additionally it is worth only including the login script if it is required (the user has pressed the button). (As suggested by #rineez)

Related

How do I use PHP to detect a button click and open an new page?

I was wondering if someone can help me. I am trying to write some PHP code so that when I click on a button in one page, upload.php, the button click is detected and I am redirected to another page, processing.php. I am following along another tutorial and I have triple checked, I don't see what I have done wrong, but the button click is not being detected as it is in the video.
This is the code for my upload.php file:
<?php include_once('includes/header.php');?>
<?php include_once('includes/classes/VideoDetailsFormProvider.php');?>
<div class="column">
<!-- //calling PHP function to create upload form -->
<?php
//create variable and assign value
$formProvier = new VideoDetailsFormProvider($con);
//call function
echo $formProvier->createUploadForm();
?>
</div>
<?php include_once('includes/footer.php');?>
This is the relevant code from my additional class VideoDetailsFormProvider.php:
class VideoDetailsFormProvider{
private $con;
//create constructor and pass $con variable to it
public function __construct($con){
$this->con = $con;
}
//creating a function to create the upload form
public function createUploadForm(){
$fileInput = $this->createFileInput();
$titleInput = $this->createTitleInput();
$descriptionInput = $this->createDescriptionInput();
$privacyInput = $this->createPrivacyInput();
$categoryInput = $this->createCategoryInput();
$uploadButton = $this->createUploadButton();
return "
<form action='processing.php' method='POST'>
$fileInput
$titleInput
$descriptionInput
$privacyInput
$categoryInput
$uploadButton
</form>
";
}
private function createUploadButton(){
$html = "<button name='uploadButton' class='btn btn-primary'>Upload Video</button>";
return $html;
}
And this is what I have in my processing.php file:
<?php include_once('includes/header.php');
//check for submission of the form or button is pressed
if(!isset($_POST['uploadButton'])){
echo "No form data has been set";
}else{
}
?>
When I click the button object, nothing happens. In the video I am transferred to processing.php and the echo message is not displayed. Or at least I should be, but that doesn't happen. I did try to check here to see if I could find some answers, a few things I tried didn't work out. Does anyone have any ideas about something I might be missing? Thanks in advance
The problem is with your upload button, when you use an html form it has to be submitted to the php processing page, try:-
private function createUploadButton(){
$html = "<button type='submit' name='uploadButton' class='btn btn-primary'>Upload Video</button>";
return $html;
}

How to check for PHP session from login page

I have two pages made in PHP, index (using it as login page) and main page (this one should be protected).
Index page has a login form that asks only for password (there are no users intended to be).
I want to make this:
1. When you enter password on index page, and if it's correct, the site will redirect you to the main page. If password is not correct then it will alert you about that.
2. Main page should not be visible if you have not entered password on the index page. If you have entered it then you will be able to see the main page.
I figured out that the easiest way would be to make it with PHP session check, but it's not working on my code, so can you please help me?
So this is my PHP code for the index page. Here the site needs to check is (universal, for all) password correct, and if so it needs to redirect to main, or if not to display some alert box.
<?php
session_start();
$password = '1234';
if($_POST['password'] == $password){
//Create session
$_SESSION['session'] = 1;
// If correct redirect to main
header('Location: http://www.example.com/main');
exit;
}
else {
// If not correct stay on index (do nothing)
}
?>
Code my main page looks like this. This is where the site should check if user has session and then decide should he be able to see the site or not (if not it should redirect to index for login).
<?php
session_start();
if (!isset($_SESSION["session"]))
{
header("location: http://example.com/index");
}
?>
I Googled everything and came out with no working solution. Is there better way to achive this or can you help me fix it?
So TLDR, how to password protect main page with login (no users, same password for everyone)?
Currently this code doesn't work. When I enter password on index it redirects to main. But main page doesn't have session check working. It simply shows all without redirecting to index for login if user is without session.
Ok.. sorry for my first advice. It is obviously not a solution. But if i understand you correctly. This is my working approach:
index.php
<?php
session_start();
$password = '1234';
// Check if the user is not already logged in
if (isset($_SESSION['login'])) {
header('Location: main.php');
}
// Check if the form is submitted
if (isset($_POST['submit'])) {
if ($_POST['password'] == $password) {
$_SESSION['login'] = true;
header('Location: main.php');
}
}
?>
with form
<form action="" method="post">
<input class="upisnopolje" type="password" name="password" placeholder="Unesite kod" required>
<input class="upisnopolje" id="upisnopoljefix" type="submit" name="submit" value="Ok">
</form>
main.php
<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION["login"])) {
header("location: index.php");
}
if ( isset( $_POST['submit'] ) ) {
unset($_SESSION["login"]);
header("location: index.php");
}
?>
with form to logout
<form action="" method="post">
<input type="submit" name="submit" value="Log out">
</form>
Note that submit button needs to have name="submit" for $_POST['submit'] check.
Hope it helps.

PHP "header" function

I have a small form with 2 inputs and a submit button. When the button is pressed, the variables are saved, and then the user is redirected to a new page.
<?php
session_start();
if (isset($_POST['coord1']) and isset($_POST['coord2'])) {
$coord1 = $_POST['coord1'];
$coord2 = $_POST['coord2'];
$_SESSION['coord1'] = $coord1;
$_SESSION['coord2'] = $coord2;
header("Location: http://localhost/isi/app/index.php ");
exit();
}
?>
The problem is that I always get an Error 404 even if the path is correct. If I copy the path and access it through browser, the page is displayed... Why is the path not working inside this function?

How to protect my php code from auto executing when loading the page

I want to protect my action page so that whenever user or hacker directly hits www.something.com/process.php That should not have any effect .Please help me securing the process.php page when user directly hits from browser address bar .
I have following code in index.html
<form method="post" action="process.php">
Name:<input type="text" name="txtname"><br/>
Age :<input type="text" name="age"><br/>
<input type="submit" value="submit">
</form>
I have following in process.php
<?php
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
?>
Add the following line to the top of process.php
if (empty($_POST)) {
header('HTTP/1.0 403 Forbidden');
die('Restricted');
}
What about making sure that the user opened index.html first before navigating to process.php?
You have two options:
From the process.php make sure that the $_SERVER['HTTP_REFERER'] value matches your index.html page
if($_SERVER['HTTP_REFERER'] == "http://localhost/index.html"){
//do your work here
}
Another solution, you can for example create a random variable in a hidden input in the index.html, store it in the session, then in the process.php page you can check if the variable that you stored in the session matches the variable sent by the form.
this is some basic ways to secure your applications from an attack called CSRF you can read more about it here:
https://en.wikipedia.org/wiki/Cross-site_request_forgery
http://www.gnucitizen.org/blog/csrf-demystified/
preventing csrf in php
You should try something like that
<form method="post" action="process.php">
Name:<input type="text" name="txtname"><br/>
Age :<input type="text" name="age"><br/>
<input type="submit" value="submit" **name="ButtonName"**>
</form>
Add a name of your button. Then change your process.php file to something like this :
<?php
if (!isset($_POST['ButtonName'])) // If the submit button hadn't been hit
{
// Kick the user off the page
echo "<script typer=\"text/javascript\">window.location='index.html';</script>"
}
else
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
?>
Now if you try to enter into process.php without submitting the form, you will automaticaly be "kicked"
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
What happens is this is not a POST request? Or if it is a POST request, but those two fields are not present? This code is broken. Now, your configuration may ignore that error and treat $_POST['age'] as a blank when it is not set, but that’s not something you should be relying on.
class Request {
public static function value($arr, $field, $default=null) {
return isset($arr[$field]) ? $arr[$field] : $default;
}
public static function get($field, $default=null) {
return self::value($_GET, $field, $default);
}
public static function post($field, $default=null) {
return self::value($_POST, $field, $default);
}
}
That should exist as a useful class you can call when you want it. And then, in this file, you can have
$name = mysql_real_escape_string(Request::post('txtname'));
$age = mysql_real_escape_string(Request::post('age'));
if ($name && $age) {
// Do database stuff here.
}
For a quicker solution, you could just stick
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
exit;
}
at the top of the file.
Incidentally, the mysql_* family of functions have been removed from the latest versions of PHP. You should migrate to the mysqli_* family or to PDO if you want your code to continue to work when you upgrade your PHP installation.
one way would be checking if the form is submitted and binding all the actions inside it as following
<?php
if(isset($_POST['txtname']))
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
else
{
// form not submitted
}
?>
extra security can be added by binding whole inside another condition if the user has logged in or not as following
<?php
if(checkUserLogin())
{
if(isset($_POST['txtname']))
{
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
else
{
// form not submitted
}
}
else
{
// user has not logged in yet. redirect to login-page using header("location:....");
}
?>
where checkUserLogin() can be a function to check user logged in details for example
function checkUserLogin()
{
$return= false;
if($_SESSION['userloggedin']==1)
{
$return=true;
}
return $return;
}
check on the data you sent first like the and make your code ad the followings
<?php
//connection code to connect and use database...
$name=mysql_real_escape_string($_POST['txtname']);
$age=mysql_real_escape_string($_POST['age']);
if((isset($name) && $name != '') || (isset($age) && $age != '')){
$sql="insert into table values('$name','$age')";
$result=mysql_query($sql);
}
?>

How to keep me logged in on a php form

I created a login page to a php form that I also created. Whenever I fill the form with the required fields, I get redirected to a 'Thank you for your submission' page, that has the link 'Go Back to Form'.
The problem is, when I press the 'Go Back to Form' link, it assumes that I am not logged in anymore, and so I get directed to a white page instead.
Login Page Code:
<?php session_start(); ?>
<?php
if (isset($_POST['submitlogin'])) {
$username1= $_POST['username'];
$pass1= $_POST['password'];
if($username1==$nomepass && $pass1==$passpass) {
$_SESSION['CurrentUser']= $username1;
echo '**HTML FORM**';
}
else
{
//...
}
}
?>
Form 'Thank you' Page:
HTML code Inside PHP echo
...
echo ' <p> Back to login page </p>' ;
On the login form and subsequent pages using sessions, put an if statement to check if the session that tells that a person has logged in is set. Then, it will redirect you to a home page or whatever page you want if you are logged in.
That way, if you are not logged in, you can login otherwise, it will redirect you
<?php
session_start();
if(isset($_SESSION['CurrentUser'])){
// redirect to some page
}
else{
// do something else
}
You could also make that line to read as:
if(isset($_SESSION['CurrentUser']) && !empty($_SESSION['CurrentUser']))
Normally we can use the session and call it on every page where I wan to allow the register user, for example..
This is you php code
if (isset($_POST['submitlogin'])) {
$username1= $_POST['username'];
$pass1= $_POST['password'];
if($username1==$nomepass && $pass1==$passpass) {
$_SESSION['CurrentUser']= $username1;
header('location:index.php');
}
Now you can code in the index page like this...
<?php
if(!isset($_SESSION['currentUser']))
{
header('location:signin.php');
}
?>
if the session is set tyhen the above code will keep you login otherwise you will redirect to signin page..

Categories