I'm trying to make an api for my iOS application by sending POST http requests to my api.php. I'm testing it right now, but my echo is not showing up? The only moment my echo works is when I delete everything and just write echo 'Test';.
Here is my code:
<?php
$user = '';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=iOS', $user, $pass);
if(isset($_POST['status']) && $_POST['status'] == "login")){
// Login stuff
}else if(isset($_POST['status']) && $_POST['status'] == "registreren")){
//Register stuff
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
if($dbh->execute($sql)){
echo 'Did it';
}else{
echo 'Nop';
}
}
}else{
echo 'Something is wrong';
}
$dbh = null; // PDO sluiten
?>
I'm not so good at php, but in my case there should always return 'Something is wrong' when accessing the api.php by URL because I don't send any POST requests with it.
There are several syntax errors which might prevent your code from executing correctly. In every if-statement, there is an additional bracket.
Eg: if(isset($_POST['status']) && $_POST['status'] == "registreren")) should be replaced by if(isset($_POST['status']) && $_POST['status'] == "registreren") (note that the last bracket is missing).
Remove the additional brackets at the end of every if-statement in your code and it might be fine.
Related
When I run this page, everything shows up correctly, but then when I try to test my various error messages, my button keeps redirecting me back to my login page as if everything was inputted correctly. It fails to register the if blocks I've included. Below is the php (the html runs fine, not included).
*Side note, a few lines are commented out because I initially had PDO and am changing them over to mysql, but those shouldn't affect everything else running. I have them commented out too so if things did work, I wasn't adding unnecessary info to my database.
Of course, PHP is not skipping anything. It is diligently running your conditions, but in your code the only condition that affects the insert is the last one.
To make it work as desired you have to change all your ifs to elseif save for the first one
The problem: Your error may be set, but your INSERT will execute only if $password == $password2 which will be true if they're both empty.
You need to indicate alternative paths by doing else if
<?php
error_reporting (E_ALL);
$error = "";
if (isset($_POST['createAccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$city = $_POST['city'];
$province = $_POST['province'];
$postalCode = $_POST['postalCode'];
if (!$username){
$error = "<br><div><em>No username entered.</em></div>";
}
elseif (!$password || !$password2){
$error = "<br><div><em>Missing password.</em></div>";
}
elseif (!$firstName || !$lastName){
$error = "<br><div><em>Please enter first and last name.</em></div>";
}
elseif (!$address || !$city || !$province || !$postalCode){
$error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
}
elseif ($password != $password2){
$error = "<br><div><em>Passwords do not match.</em></div>";
}
else{
$conn = mysql_connect(<blocked out for privacy reasons>);
$db = mysql_select_db("grocery", $conn);
$account = mysql_query("SELECT *
FROM accounts
WHERE username = '$username'",
$conn);
$rowExist = mysql_num_rows($account);
if ($rowExist == 1){
$error = "<br><div><em>Username already exists.</em></div>";
}
else {
//$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
// VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
//$conn->exec($newAccount);
header("location: GroceryLogin.php");
}
mysql_close($conn);
}
}
// I'm guessing here you do an echo $error;
I have the following script where the user enters some data from the android phone in order to register.
<?php
include("connect.php");
include("functions.php");
if(logged_in())
{
header("location:profile.php");
exit();
}
$error = "";
$j = new stdClass();
$string = "";
if (isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['email']) && isset($_POST['password'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
//We need to encrypt our password.
$password = md5($password);
$insertQuery = "INSERT INTO users(firstName,lastName,email,password) VALUES('$firstName','$lastName','$email','$password')";
$result = mysqli_query($con,$insertQuery);
if(!$result){
$j->status = "Fail";
$j->message = "No users in database";
$string = json_encode($j);
echo "No inserted data";
//echo $string;
}else{
$j->status = "success";
$j->message = "Successfully registered";
echo "Data inserted";
$string = json_encode($j);
}
echo $string;
}
?>
Unfortunately nothing happens. I can't even generate JSON from the url itself. For example I enter the url's link
http://localhost/android_reg/
and get nothing back. Shouldn't I get
{
"status":"fail",
"status":"No users in database"
}
when there is not data in the database? Surely there is something wrong with my php code.
No. You shouldn't get anything thing back. The main part of your code checks various $_POST variables to see if they're set. Requesting the page in your web browser is a HTTP GET request, so you'll never see any output because the POST variables will never be set.
Make sure your script generates json-output in any case.
Since the fail-branch is usually shorter I prefer to handle it first. In your case: if there is any POST parameter missing -> bail out.
Your script is also prone to sql injections. Prepared statements can avoid that.
<?php
require 'connect.php';
require 'functions.php';
if(logged_in())
{
header("location:profile.php");
exit();
}
// isset() can take multiple arguments and only returns true if all variables are set
if ( !isset($_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'missing POST parameter(s)');
}
else {
$stmt = $con->prepare('
INSERT INTO
users
(firstName,lastName,email,password)
VALUES
(?,?,?,?)
');
if ( !$stmt ) {
$result = array('status'=>'fail', 'message'=>'prepare failed');
}
else if ( !$stmt->bind_param('ssss', $_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'bind failed');
}
else if ( !$stmt->execute() ) {
$result = array('status'=>'fail', 'message'=>'execute/insert failed');
}
else {
$result = array('status'=>'success', 'message'=>'Successfully registered');
}
}
// single, unconditional exit/output point (ok, except for the if(logged_in())/exit() thing)
echo json_encode($result);
Do I correctly do it? using header("Location: ....") to redirect to another page?
Could you suggest to improve may code because I'm new to this things..
<?php
require 'db.php';
$msg='';
if(!empty($_POST['username']) && isset($_POST['username']) && !empty($_POST['password']) && isset($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$sql = mysqli_query($connection, "SELECT username FROM admin WHERE username = '".$username."' AND password ='".$password."'");
$count = mysqli_num_rows($sql);
if($count == 1)
{
header("Location: AdminDeleteAccount.php");
exit;
}
else
{
$msg='Username and Password didnt match';
}
mysqli_close($connection);
}
else
{
echo 'howdie';
}
?>
yes you are doing it correctly, store the password in database using some kind of encrytption like MD5, sh1 etc. Also make sure that nothing is echoed out before the header function or else the header function will not work and you will see an error message.
I have written PHP code with many nested if conditions. I just want to display an alert for an exceptional condition along with the if conditions.
Here is my source code:
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$query ="SELECT * FROM user where username='.$username.' AND pass='.$password.'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password))
{
session_destroy();
session_start();
echo "message";
} else {
do_alert("Exceptional alert");
}
} else {
do_alert("Exceptional alert");
}
These two else conditions are not working. I don't know really where my mistake is.
I think it may have to do with your do_alert down in your code. Follow me through the code.
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) { // if not empty
$query =""; // this is an empty query
$row = mysql_fetch_array($query); // returns nada
$counted = mysql_num_rows($query); // gives nada back
if (($counted === 1) && ($row['username'] === $username) && ($row['password'] === $password)) { // completely useless at this point cause no row is returned
session_destroy();
session_start();
echo "message";
} else { // this will not be executed
do_alert("Exceptional alert");
}
} else { // this will be executed
do_alert("Exceptional alert"); // where is this function defined?
}
okay i commented on your code where it goes wrong. As you see it happens already on the first if, so it should return the last else. Since I dont know where your do_alert code is defined, my guess is that this is your error.
Try replacing it first with an echo like this: echo "I am a super duper evil monkey"; and see if that works.
edit
since you added your query now, i 'd like to point out as well that you should sanitize your input. This to make it more safe. However the term safe here is kind of irralevant, cause you re using an outdated mysql set. (mysqli / pdo are the ways to go now)
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
why? simple. Look at this!
$_POST['username'] = 'awesome';
$_POST['password'] = "' OR ''='";
it would turn up something then like this.
SELECT * FROM users WHERE user='awesome' AND password='' OR ''=''
And this would mean, everybody could log in, cause blank is always blank. Just as a headsup.
More information here: http://php.net/manual/en/function.mysql-real-escape-string.php
edit 2
// very first thing you do if you work with sessions, is actually starting it. you dont do this in your if else statement, cause you could not benefit of the session variable on a later stage on this page.
session_start();
// these variables come from a form with a form name, so we are going to do a check if indeed this came from that form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (!empty($username) &&
!empty($password)) {
$query ="SELECT name, password FROM user WHERE name='".$username."' AND password = '".$password."'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password)) {
echo "message";
} else {
echo "no entrees found";
}
} else {
echo "failed to input some variable";
}
I cleaned some up in my own words, you may have to fiddle with the query, and further i fixed it a bit since you didnt use the session appropiately.
Now where it echo's the message, you should set a session variable, that you can destroy later when you log out. A session variable you can call in the session itself, on every page that has sessionstart() in it. Here you can check if it excists, if so then you are logged in. I hope this helps you out.
I'm currently making a webpage and I have run in to some problems with echo being inside a div container.
My website is currently setup like this:
index.php has the header and a navigation pane on the left side. and there is a bodycontent div that will load in different pages depending on what is clicked.
I previously had the following code in my index.php right before my bodycontent div:
<?php
//set the variables
$username = isset($_POST['username']) ? $_POST['username'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$step = isset($_POST['step']) ? $_POST['step'] : '1';
//validation
if($step=='2'){
if($username == '' || strlen($username)==0){
echo 'username can not be blank<br/>';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){
$errors[] = 'invalid email address<br/>';
}
if($password == '' || strlen($password)<=4){
$errors[] = 'password can not be blank or less than 4 characters<br/>';
}
$username=mysql_real_escape_string(trim($username));
$email=mysql_real_escape_string(trim($email));
$password=md5(mysql_real_escape_string(trim($password)));
//mysql queries
if(empty($errors)){
//do something
$query = "
INSERT INTO user
(email, username, password, user_level)
VALUES
('$email', '$username', '$password', '1')";
$result = mysql_query($query) or die ('error: '. mysql_error());
echo 'new user registered!';
$step='2';
}
else{
//error output
foreach($errors as $errors)
echo $errors;
$step='1';
}
}
if($step=='1'){
?>
I decided to move this piece of code in my registration.php page so the index.php looks cleaner for me.
However, ever since I moved the code from index.php to registration.php the echos are not displaying. If you need more code I will gladly post some more.. I don't want to overwhelm right now.
I noticed in your final foreach loop:
foreach($errors as $errors) is missing an opening bracket;
foreach($errors as $error) {
// instructions
}