Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
$inputarray=array("username", "password");
foreach($inputarray as $inputkey);
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}
$username isn't being defined, only $password. Anyone know what's wrong?
It's just a typo:
foreach($inputarray as $inputkey);
You included a semicolon at the end of that line, so the foreach statement runs, then ends, and then the if clause executes on the last value that the foreach statement left in $inputkey.
Try:
foreach($inputarray as $inputkey)
{
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}
}
Error is probably due to the ; at the end the foreach line. This will cause the foreach line to run leaving to completion, but not run any other statements as there is no enclosure that follows it. Once completed the value of $inputkey will be "password" which is why you are only getting data from "password"
Try:
$inputarray=array("username", "password");
foreach($inputarray as $inputkey) {
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey])) {
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$$inputname=$inputresult;
} else {
die("You have to fill both fields.");
}
} //endforeach
Variable variables are a code smell that you're making things hard on yourself. Instead of doing that, at this stage, and for the specific purposes of a login page, I would make life as simple, readable, and uncomplicated as you can.
Just do this:
$username = #$_POST['username']; // Just about the only place where using # is ok.
$password = #$_POST['password'];
if(!trim($username) || !trim($password)){
die("You have to fill both fields.");
}
A login form is not a place to innovate or make your code complicated. For a little added abstraction, you could put that information into a simple login validation function so that you can modify the criteria down the line (e.g. username must be longer than 1 character, or whatever).
But from looking at your code, you're making a CLASSIC MISTAKE:
DO NOT ROLL YOUR OWN LOGIN SYSTEM THE FIRST TIME AROUND.
Reuse an expert's login code and learn from that. Write other things in custom php, but borrow someone else's time tested login code for database parameterization, error checking, and abstraction. Writing your own login system is playing with fire.
It looks like you're assigning the string name $inputkey to the value. Also you were creating dynamic variables that you might never have found in your code.
$inputarray=array("username", "password");
foreach($inputarray as $inputkey=>$inputvalue);
if(isset($_POST[$inputkey]) && !empty($_POST[$inputkey]))
{
$inputname=$inputkey;
$inputresult=$_POST[$inputkey];
$inputname=$inputresult;
}
else
{
die("You have to fill both fields.");
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello everyone again here,
I want to create a PHP script for my software which generates and returns the specific code using one $_GET request with a string and using another verificates this code, then forbid running same string.
Something what should work like this:
1st user's software runs "http://example.com/codes.php?create=" and string like "abc".
and script returns code based on "abc", e.g. "4aO45k", "12sdF4" etc.
2nd user's software runs "http://example.com/codes.php?verify=" and this code.
If this code exists, return true and remove it FOREVER, meaning this code will never be generated again. If this code doesn't exist, return false.
If 1st user's software will run "http://example.com/codes.php?create=abc" another code will be generated.
In simple words:
if $_GET is create, then
generate random alphanumeric string, save it and return
if $_GET is verify, then
check if this string exists, if so, then
return true, remove from saved
otherwise
return false
Possible without databases, SQL, mySQL, FireBird...?
How do I make it using .ini files as storage?
Thanks.
It's possible with files. You can do something like the simple solution below:
A couple of notes:
I don't know what you intend by based on exactly, so this just uses the input as a prefix
This stores every code in a file indefinitely; if used a lot this file will grow very large and checking for the existence of codes, and ensuring new codes are unique can grow very slow
The same code can be verified multiple times, but will never be recreated. Marking them as used after verification is of course possible as well
As a general rule don't go creating global functions and shoving everything in one file like this. It's really just proof of concept of what was asked
<?php
$file = fopen('codes', 'a');
if (!empty($_GET['create'])) {
$seed = $_GET['create'];
do {
$code = uniqid($seed);
} while (codeExists($code));
fwrite($file, $code . "\n");
echo $code;
}
else if (!empty($_GET['verify'])) {
echo codeExists($_GET['verify']) ? 'found' : 'not found';
}
function codeExists($verification) {
$file = fopen('codes', 'r');
$found = false;
while ($code = trim(fgets($file))) {
if ($code == $verification) {
$found = true;
break;
}
}
return $found;
}
$example = 0;
if ($password == "123") {
$example = 1;
}else{
die("Incorrect Password");
}
if ($example === 1) {
echo "Conditions Met.";
}else{
echo "Conditions Not Met";
die();
}
//Super important code that should not run if $example does not equal 1
Is it possible for code like this to execute if the condition has not been met, I am including guessing the password, or some kind of brute force method.
I am just asking if an if statement can somehow break, is there any way for an if statement to mess up and somehow let the user execute the theoretical code below without knowing the password.
Just to clarify, I am not talking about guessing the password, or any over vulnerability like that, I am purely talking about whether it's possible for an if statement to execute if the statement conditions are not met, for example if the server was under extreme load, could it make a mistake as such?
No, the if part of it will not run, provided you include the else part the flow is automatically transferred to else if the if condition is not met.
To answer your main question no the likelihood of an if being broken is slim to none. That would make 100% of the code in production right now unreliable. How many sites do you visit that have a username and password and they do the same thing (kind of).
You really need to revisit this code should be consistent, formatted and limited in flows
You have 2 die versions (which is not the best option)
The code formatting is all over the place and you have logic checks that really just make the flow harder to follow for no advantage.
$example = 0;
//For the sake of simplicity I will assume you know this is not how to handle passwords in real life.
//If not please comment and I will give a better example.
if ($password == "123") {
$example = 1;
}else{
//Die version 1
die("Incorrect Password"); //If you are here then nothing below in this script will run.
}
//Literally just a continuation of the code you have uptop?
if ($example === 1) {
echo "Conditions Met.";
}else{
//Die version 2
echo "Conditions Not Met";
die();
}
//This is the code that should be in the if.
//Super important code that should not run if $example does not equal 1
Refactoring this can be as simple as:
//For the sake of simplicity I will assume you know this is not how to handle passwords in real life.
//If not please comment and I will give a better example.
if ($password == "123") {
//Super important code that should not run if bad password!
}else{
//Killing a script is bad form
//Redirect them to a login page or something.
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need help on how to make an API for PHP. I was trying to make one web server communicate with another webserver through PHP.
I also want it to update MySQL code. I was using $_GET but it was less secure. Here is my code, can you please take a look at it?
<?php
/*
example: website-url-here.com/?command=insert-command-here&password=testing
*/
$command = $_GET["command"];
$password = $_GET["password"];
if ($password == "testing") {
//Was not a good idea, less secure.
//echo eval($command);
//More secure
if ($command == "create-user")
{
//create user command here
}
else if ($command == "delete-user")
{
//delete user command here
}
else
{
die("Command is incorrect");
}
}
echo "Success";
?>
This question is way too open ended to answer in a StackOverflow answer. Try reading up a little on REST, and a lot on PDO, especially in the context of sanitizing user input.
Think about what would happen if somebody called your api with [url]?command=rm -rf .&password=testing
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So I'm using $_GET to capture the URL to use it later but when I use $_GET it wont redirect!
So here's my sample code:
URL : http://localhost/project/active.php/?s=ieugfshd&h=qwuyrbcq&i=1
php code:
<?php
include 'init.php';
$s = trim($_GET['s']);
$h = trim($_GET['h']);
$i = trim($_GET['i']);
$q = key_check($s,$h,$i);
if($q == 1)
{
header("location:password_active.php");
exit;
}
if($q == 0)
{
header("location:login_failed.php");
exit;
}
?>
EDIT:
key_check( ) function
function key_check($k1,$k2,$id)
{
$query = mysql_query("select key1 from users where user_id = '$id'");
$key1 =mysql_result($query,0);
$query = mysql_query("select key2 from users where user_id = '$id'");
$key2 =mysql_result($query,0);
$y=strcmp($k1,$key1);
$z=strcmp($k2,$key2);
if($y || $z == 0)
{
return 1;
}
else
{
return 0;
}
}
Now when I try this, I got "1" but I'm getting
This web page has a redirect loop
But my password_active.php doesn't have any redirects. It's just an html page.
The URL you're using to access to your script is:
http://localhost/project/active.php/?s=ieugfshd&h=qwuyrbcq&i=1
This loads active.php, which does its role and then tries to send the following header :
header("location:password_active.php");
The browser recieves this header, and tries to resolve that relative URL by adding password_active.php after the last slash before the query string (that ?s=xxx string).
So your browser loads:
http://localhost/project/active.php/password_active.php?s=ieugfshd&h=qwuyrbcq&i=1
This loads active.php again, which does its role again and then send again the same header, and that loads this page:
http://localhost/project/active.php/password_active.php?s=ieugfshd&h=qwuyrbcq&i=1
Again. And again. And again. After several tries, your browser understands that something is going wrong and stops.
You should use an absolute URL in your HTTP header:
header("Location: /project/password_active.php");
Also, please note how HTTP headers should be written, according to the standard.
Random notes :
According to the file names, $s and $h are both passwords. You should hash them, and not passing them via the URL.
if($y || $z == 0) is unlikely to work as you think, since it will be evaluated as if y or not z in pseudo code, while you may have wanted if not y and not z for password checking.
Also, good point for calling exit() after a Location header. You should never forget that, as it is very important and may cause some trouble in your scripts if you forget them.
Try removing / after file.php. Like index.php?i=sa
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have the following function to upload a file to a database table field.
protected function _upload_file() {
...
}
Once uploaded, uploading a new file overwrites the original uploaded file.
What I want is to establish a new upload without overwriting the file. The way I see it, I would have to create a new function like;
function if_upload_file() {
...
}
If that function is successful, then repeat function.
Any idea how I could accomplish that?
Let the function return true if the file was uploaded successfully and as long as it stays true, you loop again and again. Like that
$con = true;
while($con) {
if($con) {
$con = your_function()
}
}
//your function
function your_function() {
//do your stuff here
if($file_upload_successful) {
return true;
} else {
return false;
}
}
At least i think this might work ... not even sure. Well, no risk no fun.
An alternative to Y U NO WORK's answer is to use the function recursively.
E.g. if you had an array of files to upload..
function foo($array_of_files) {
if(is_array($array_of_files) && count($array_of_files) > 0) {
$file = array_shift($array_of_files);
// ... Handle upload code.
if(count($array_of_files) > 0) {
foo($array_of_files);
}
}
}
However, this does build stack layers, and could be quite troublesome for debugging.
Using a while loop would be a sensible strategy so long as you handle the loop conditions correctly.