I'm very new to php. I found some CMS like code for east text editing here on SO and now I'm trying to implement it on our micro site.
My problem is, that I want login error report to show on exact position on the page - just under the login button.
Can someone tell me how can I put that error report text whereever I want? I don't want to override it with CSS positioning.
In basic, I want to put that p class="error":
<?php
if (empty($_POST) && isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'logout':
session_unset();
session_destroy();
break;
}
}
if (!isset($_SESSION['user'])) {
$user = '';
$pass = '';
if (isset($_POST['login'])) {
$user = strtolower(trim($_POST['user']));
$pass = $_POST['pass'];
$errors = array();
if ($user == '' || $user != '1') {
$errors['user'] = '';
}
if ($pass == '' || $pass != '1') {
$errors['pass'] = '';
}
if (empty($errors)) {
$_SESSION['user'] = $user;
} else {
echo '<p class="error">Insert correct ';
if (isset($errors['user']))
echo 'name';
if (count($errors) == 2)
echo ' a ';
if (isset($errors['pass']))
echo 'password';
echo '.</p>', "\n";
}
}
}
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
?>
somewhere else in the whole code of my page. Do I need to cut out something from that php code, or do I need to write new part of code for that?
Thank you for you help, Matej
Instead of just doing 'echo' all over the place, which means you get output at the place where the PHP code is embedded in the page, set some flags/message variables to output later.
e.g.
<?php
$errors = false;
$msgs = '';
if (....) {
$errors = true;
$msgs = "something dun gone wrong";
}
?>
... various bits of your html go here ...
<?php if ($errors) { echo $msgs; } ?>
... more html here ...
Related
I have an 'api' so to speak where I am trying to proxy an api on another server for an App.
The target url is formed like:
http://example.com/live/username/password/filename.mp4
how can I dynamically redirect to that?
here is the php I have so far which grabs the filename and user/password
<?php
if (isset($_GET['username']))
{
$username=$_GET['username'];
$password=$_GET['password'];
}
else if (isset($_POST['username']))
{
$username=$_POST['username'];
$password=$_POST['password'];
}
$action = isset($_GET['action']) ? $_GET['action'] : '';
$db = new SQLite3('./.dns.db');
$res = $db->query('SELECT * FROM dns');
$arr = array();
while ($row = $res->fetchArray(SQLITE3_ASSOC))
{
$arr[] = $row['url'];
foreach ($arr as $value)
{
$api_call = $value.'/player_api.php?username='.$username.'&password='.$password;
$api = json_decode(file_get_contents($api_call), TRUE);
$api2 = json_decode(json_encode($api["user_info"]) ,TRUE) ;
$auth = $api2["auth"];
if ($auth == 1)
{
$dns = $value;
}
}
}
if (isset($_GET['vod_id']) && $_GET['vod_id'] !== "")
{
$vodid = $_GET["vod_id"];
$vodinfo = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action=get_vod_info&vod_id='.$vodid);
echo $vodinfo;
}
else if (isset($_GET['series_id']) && $_GET['series_id'] !== "")
{
$seriesid = $_GET["series_id"];
$seriesinfo = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action=get_series_info&series_id='.$seriesid);
echo $seriesinfo;
}
else if ($action !== "")
{
$get_actions = file_get_contents($dns.'/player_api.php?username='.$username.'&password='.$password.'&action='.$action);
echo $get_actions;
}
else
{
$login = file_get_contents($dns.'/panel_api.php?username='.$username.'&password='.$password);
echo $login;
}
?>
The app will read from the JSON provided and grab the 'filename' and then attempt to go to /live/ on the api host, but this will lead too http://example2.net/live/username/password/filename.mp4
which doesn't exist.
I thought about maybe something in htaccess?
Im trying to provide the App with the http://example.com/live/username/password/filename.mp4
not the
http://example2.net/live/username/password/filename.mp4
(The example2.net is the $dns in the PHP)
Sorry I know this is a bad explanation - hopefully I've explained enough to be able to find an answer.
(1st post)
edit: I have been reading about turing folders in links to querystring where I can point to this
<?php
if (isset($_GET['username']))
{
$username=$_GET['username'];
$password=$_GET['password'];
$streamid=$_GET['streamid'];
}
else if (isset($_POST['username']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$streamid=$_POST['streamid'];
}
header('Location: http://example.com/live/'.$username.'/'.$password.'/'.$streamid);
?>
I just need now to figure out how to use htaccess to turn the requested folder url into a query string from
example2.net/live/username/password/file.mp4 to
example2.net/live.php?username=username&password=password&streamid=streamid.mp4
I ended up using this which worked for .htaccess
RewriteEngine on
RewriteRule ^live\/([^\/]+)\/([^\/]+)\/([^\/]+) /path/to/api/live.php?username=$1&password=$2&streamid=$3 [L]
I am trying to create a login page and I am having some troubles. I cannot get this code not to return false even though I know I have the right password in my .txt document (It's just hashed though).
Here's my PHP file that I can not stop getting not to return False:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
Also, if you can think of anything I should have in my code, please let me know. Thanks so much.
Edit: Updated what I have for my code right now. Still returning False.
Since unHash is a function, it is not getting executed (it is not called from what I can see), so $hashedPass is not getting set. In the future, try adding some debug statements (e.g. just print out $pass and $hashedPass before the return false;).
A shot in the dark: You have turned off error messages and only get a blank page instead of a redirect when entring a right login combination?
If that is the case, you might use the following code:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
// echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
The reason your code fails is the echo statement, which is executed before the header-redirect. It´s not allowed to have any output before an header-redirect. (more about this behaviour: How to fix "Headers already sent" error in PHP)
I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").
I'm looking for as simple approach to correcting errors such as non-matching passwords and people inserting blank data into a form in HTML.
I want to use PHP to throw me back an error when this happens, I was considering using if statements but realised it would not show more than one error if it happens.
Here is an example of what I was doing, keeping in mind $firstname's input is from POST:
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;
header('Location: register.php');
}
In register.php it picks up this, and warns the user that he has entered no first name. This is cool but won't display additional errors if there are any. I'm guessing switches and arrays are the way forward but I don't really understand how to add a entry to an array.
Anyone able to help?
session_start();
....
$_SESSION['flag']=false;
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;$_SESSION['flag']=true;
}
if ($lastnamee == "")
{
$_SESSION['nolastname'] = 1;$_SESSION['flag']=true;
}
...
header('Location: register.php');
in register.php
session_start();
...
if ($_SESSION['flag']==true){
if ($_SESSION['nofirstname']==1) {///message}
if ($_SESSION['nolastname']==1) {///message}
...
}
Use a nested if, e.g;
<?php
if($firstcond){
if($secondcond){
}else{
$_SESSION['error'] = 'Second Condition not met!';
header('Location: register.php');
//error
}
}else{
$_SESSION['error'] = 'First Condition not met!';
header('Location: register.php');
//error
}
?>
This means that in order for $secondcond to be validated, $firstcond must pass whatever checks you perform on it first :)
session_start();
ob_start()
if ($firstname == "")
{
$_SESSION['nofirstname'] = "Enter your name";
header('Location: register.php');
}
Redirect the page and display
echo isset($_SESSION['nofirstname'])?$_SESSION['nofirstname']:'';
Try this.
Try this:
session_start();
$errors = array();
if ($firstname == "")
{
$errors['nofirstname'] = 1;
}
if ($lastname == "")
{
$errors['nolastname'] = 1;
}
$run = 1;
foreach ($errors AS $key => $value)
{
$_SESSION[$key] = $value;
$run = 0;
}
if (!$run)
header('Location: register.php');
I have developed a small application. I created a login panel for it. I have only one user so, I hard coded both user name and password. Below is the code but it is not working.I don’t have any db for this bcoz, it will have only 1 user.
Any help ii be appreciated.
Thanks in advance.
<?php
if(($_POST['na'] = 'admin') == ($_POST['pwd'] = 'zucker'))
{
header("location:first.php");
}
else
{
header("location:index.php?msg=enter correct user name and password");
}
?>
ok, from what I can decipher from your code - you have = and == applied incorrectly. Where you have = you want == and where you have == you want &&
if (($_POST['na']=='admin') && ($_POST['pwd']=='zucker')) {
header('location:first.php')
};
I hope this isn't how your login model is going to work - whats to stop just anyone going directly to first.php?
To avoid some Notice errors and other bugs:
<?php
$na = isset($_POST['na']) ? $_POST['na'] : false;
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : false;
$submit = isset($_POST['submit']) ? true : false;
if ($submit) {
if ($na == 'admin' && $pwd == 'zucker') {
header("location:first.php");
exit(); // Make sure nothing else gets sent
} else {
header("location:index.php?msg=enter correct user name and password");
exit(); // Make sure nothing else gets sent
}
}
?>
Here's a slightly more advanced example:
<?php
$na = isset($_POST['na']) ? $_POST['na'] : false;
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : false;
$submit = isset($_POST['submit']) ? true : false;
// Accounts array (append as you wish)
$accounts = array(
'admin' => '4635c0015b2084afcc7cb39593545e06',
'foo' => '37b51d194a7513e45b56f6524f2d51f2'
);
// form complete?
if ($submit && $na && pwd) {
if (isset($accounts[$na]) && md5($accounts[$na]) == $pwd) {
header("location:first.php");
exit(); // Make sure nothing else gets sent
} else {
header("location:index.php?msg=enter correct user name and password");
exit(); // Make sure nothing else gets sent
}
}
?>