Object Moved error html to php - php

I honestly don't know what's wrong. Every time I try to add an account to my xml database file, it doesn't get written in the file. I don't see anything wrong with my code.
When I click my submit button this page's content is displayed
Object Moved
This document may be found here
//This is me testing my code below
hey im in the if statement
hogwartsBoss
swag
hogwartsBoss#gmail.com
Harry
Potter
BabyMetal Head Bangya!!
Iron Madien Run to the Hills
japybunnyhijapygen#yahoo.com genesis Bejarano
HTML SIGN UP FILE
<!--This is the sign up section on the Home Website page -->
<form method="post" action="sign_up.php">
First Name:<input type= "text" name="first"/><br /><br />
Last Name:<input type= "text" name="last"/><br /><br />
Email:<input type= "text" name="email"/><br /><br />
Username:<input type= "text" name="username"/><br /><br />
Password:<input type= "password" name="password"/><br /><br />
<input type= "submit" name="submit" value="Sign up"/>
</form>
PHP SIGN UP FILE
$f = $l = $e= $user = $pass = null;
if(isset($_POST['username']) && !empty($_POST['username'])) {
echo "hey im in the if statement";
include 'xmlconnect.php';
$f=vaildName($_POST['first']);
$l=vaildName($_POST['last']);
$e=vaildEmail($_POST['email']);
$user= $_POST['username'];
$pass= $_POST['password'];
$credTag = $xml->addChild('credentials');
//user account info
$userTag = $credTag->addChild('username',$user);
$passTag = $credTag->addChild('password',$pass);
$emailTag = $credTag->addChild('email',$e);
$infoTag = $credTag->addChild('info');
$firstTag = $infoTag->addChild('first',$f);
$lastTag = $infoTag->addChild('last',$l);
file_put_contents('UserAccountDB.xml',$xml->asXML());
echo $xml->asXML();
// echo "updated database";
// printf($xml);
//redirects you to the homepage
session_start();
$_SESSION['userName'] = $user;
//$url = "http://cs3360.cs.utep.edu/gbejarano/WebStore/UserAccountDB.xml";
//$url = "http://cs3360.cs.utep.edu/gbejarano/WebStore/myLibrary.php";
//$url = 'http://localhost/Music_Webstore/myLibrary.php';
header('Location: '.$url);
}

There is a great misunderstanding here:
Object Moved
This document may be found here
is not an error message. It's your web-server's standard response body of a message in the Redirect 3xx group. Those do not denote errors, just standard redirects.
Those redirects are expected because you answer with a redirect:
header('Location: '.$url);
However using
echo $xml->asXML();
before the header command does not work at all. Please consult the PHP manual on how to do a proper redirect and related to other existing Q&A material here on site as well before you draw wild assumptions in a new question and label non-errors as errors and cause other confusion.
If certain words are not clear to you, ask about the words first.
If you have problem to decipher a message the computer gives to you, ask about the message first.
Do not post live code. Instead create a new example from scratch that contains as little code and data as necessary to reproduce your issue.

Sometimes the solution is simple:
It wasn't my code it was my school server security

Related

How would I go about not allowing a user to login if Google ReCaptcha doesn't pass?

To begin with, I'm having difficulties tying the Google ReCaptcha into my login form. Just for some background information, this is all running on a live webserver with an SSL Certificate, I've got the correct site and secret keys and all that jazz.
Here's my login form:
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<br />
<p>Please log in to your account below:</p>
<form action="index.php" method="post" target="_self">
<b>User Name:</b><br>
<input type="text" size="20" name="userid"><br />
<br />
<b>Password:</b><br>
<input type="password" size="20" name="password"><br />
<br />
<div class="g-recaptcha" data-sitekey="_MY PUBLIC SITE KEY_"></div>
<br />
<input type="submit" name="submit" value="Login">
<input type="hidden" value="validate" name="content">
</form>
And my script to validate:
<?php
if (isset($_POST['submit'])) {
$userid = $_POST["userid"];
$password = $_POST["password"];
$secretkey = "_MY SECRET KEY_";
$responsekey = $_POST["g-recaptcha-response"];
$useripaddress = $_SERVER["REMOTE_ADDR"];
$url = "https://www.google.com/recaptcha/api/siteverify?secret={$secretkey}&response={$responsekey}&remoteip={$useripaddress}";
$response = file_get_contents($url);
echo $response;
}
require_once("scripts/thecrab.php");
$userid = htmlspecialchars($_POST['userid']);
$password = htmlspecialchars($_POST['password']);
$query = "SELECT userid from users where userid = ? and password = PASSWORD(?)";
$stmt = $pdo->prepare($query);
$stmt->execute([$userid, $password]);
if (!$stmt->rowCount() & $response->success == 0) {
echo "<h2>Sorry, your user account was not validated.</h2><br>\n";
echo "Try again<br>\n";
echo "Return to Home\n";
} else {
$_SESSION['valid_recipe_user'] = $userid;
echo "<h2>Log In Successful</h2><br>\n";
echo "<img src=\"images/image-11.png\">\n";
}
?>
So here's the few issues that I am having. If you notice, at the top of my page that validates the information, I've got
echo $response;
That's in there strictly for testing purposes, so that I can see if the ReCaptcha comes back as true or false, but even when filling out the ReCaptcha, it always comes back as false, no matter what the security setting is set to on my Google site. I added pre tags around the validation so that it could spit back the results in an easier form to read and I'm greeted with this even when I fill out the Captcha:
{
"success": false,
"error-codes": [
"missing-input-response"
]
}
Now, since I'm stuck with an eternal "false", I decided to give the if statement a shot and implement in, if the success is false (ie. 0) then don't login, else login. Pretty simple, and you can see that at the bottom of my validation page in the if statement:
if (!$stmt->rowCount() & $response->success == 0)
So far so good, I FTP it up to the server, refresh and give it a go. But this time I get an error, and it states that the variable $response is undefined. Well I defined the variable at the top of the validation page where I said:
if (isset($_POST['submit'])) // Checks to see if the form was submitted
And it was submitted as I hit the Login button that has name="submit", so it see's that submit is set with the value of login, so it executes what follows the if (you know how PHP works), and at the bottom is where it defines $response. As far as I know, with PHP, it doesn't matter which block the variable is defined in, as long as it gets executed then it can be used anywhere.
So all in all, the issues I'm having is:
ReCaptcha always evaluates to False
Error thrown stating $response is undefined despite it being defined
Ties in with #2, since variable is undefined, it can't execute the if statement.
I've tried almost everything in my skillset.
Check again the parameters you're passing to https://www.google.com/recaptcha/api/siteverify.
The response parameter must be responSe and not respone.
This causes the error returned by the server - "missing-input-response" means you're not passing the "g-recaptcha-response" parameter
Now that the response is working:
file_get_contents will return a string, containing a JSON response. If you want to access the success value in the JSON the way you're accessing here
if (!$stmt->rowCount() & $response->success == 0) {
then you have to first use json_decode to create an object out of the string.
the if logic in that same row is using a bitwise AND operator as you're using a single ampersand & instead of &&
the logic itself - currently if no user account exists AND the recaptcha failed then there will be error, otherwise it is valid. The problem is that if there is no user but recaptcha is OK then the user is valid and if the user is ok and recaptcha failed then the user is still valid. So I'm guessing you meant to use OR instead of AND:
if (!$stmt->rowCount() || $response->success == 0) {

Redirect on a UNIX server when posting a form

So I finally decided to get an online server so I can share my website that I worked really hard on to the world. But there has been some growing pains. I have never been education on internet server management, so I thought that if it worked on my WAMP server then it would work on any server. So I chose ipage thinking that it would work, and it turned out to be a UNIX server.
There has been this trend on my website where use an AJAX/Jquery event to bring forth a form from another view and whenever I submit a it, and it will go to the original form page. It will execute the query and go through alright, but you have to hit the back button and that is just bad for the user experience. But on my local WAMP server, it works out perfectly.
Let me give you sort of a visual of the code:
The form:
<div id='addCard'>
<form action='<?php echo $_SERVER['PHP_SELF']?>' method='post'>
<label> Question </label><br><input type='text' name='question' size='30'>
<?php
if (isset($_POST['submitted'])) {
$valid = true;
if (empty($_POST['question'])) {
echo "<mark> You must have a question! </mark>";
$valid = false;
}
}
?>
<br>
<label> Answer </label><br><input type='text' name='answer' size='30'>
<br>
<label> Extra Information </label><br><input type='text' name='information' size='30' height='100'rows='80' cols='90'>
<br>
<?php
if (isset($_POST['submitted'])) {
if (empty($_POST['answer'])) {
echo "<mark> You must have an answer! </mark>";
$valid = false;
}
}
if (isset($_POST['submitted'])) {
if ($valid) {
require_once '../Models/classes.php';
$new_card = new Cards($_SESSION['user_id'], $_POST['question'], $_POST['answer'],
$_POST['information']);
$new_card->card_insert($_SESSION['user_id'], $_POST['question'], $_POST['answer'],
$_POST['information']);
}
}
?>
<input type="submit" name="submitted" value="Add Card">
<input type="reset" value="Reset Fields">
</form>
</div>
jQuery function used to call forth the form:
$('#addCard').click(function() {
$('.bar').empty();
$('.bar').load('add_card.php #addCard');
});
The actual function to put the card into the database:
public function card_insert($user_id, $question, $answer, $information){
$card_insert = sprintf("INSERT INTO Cards(user_id, question, answer, information) VALUES('%d', '%s', '%s', '%s');",
mysql_real_escape_string($user_id), mysql_real_escape_string($question),
mysql_real_escape_string($answer), mysql_real_escape_string($information));
$result = mysql_query($card_insert) or die(mysql_error());
if ($result) {
header("Location: my_cards.php");
}
}
What do you think needs to be changed? Is it a header function I need to add in? I'm using an absolute link and it still goes to that view.
If you wish to try it out for yourself, then try it at: http://www.wonderpenguin.com/Study_Penguin/index.php
If you want to see the folder structure, then check out my github page:
https://github.com/Lalien/Study_Penguin
Probably you have different output buffer sizes on the machines. Anyway, header can only be set as long as no output has been send to the client.
The function card_insert tries to set a location header but there's a lot of HTML code which has been implicitly printed to the client already. Try to change the order and have HTML code always after header(...)
PHP is OS independent and scripting language so it will not be problem where you have writen code either wamp or mac or hosted on Linux
Cross check php_self function ?
See example below

How to do a q&a validation in php with cookies

I would like create a script that is somewhat like a login. Before going to a certain page, they must answer a question correctly. If they get it right, then they proceed to the page. For example "What's your mom's name?" If the mom's name is Laurie, then they must enter this into a textbox and get it right to proceed.
Update
I used the script that oliver moran gave me to accomplish this. I added more questions so there is currently one question per page. After the final question has been answered, I have the page targeted to a place where they login, because I couldn't figure out how to do this simply based on the answer of the question. And I am fine with having the user login as a separate function. I have gotten the form to get them to login, and not let users that aren't logged in get to these pages. And the script works as long as they have kept the browser window open.
I have used the link that Oliver Moran gave on using sessions, and you can see in my code that I use sessions. But this does not solve the problem of keeping them logged in.
I would now like to know how to set a cookie once the user has logged in so they can leave the browser window and come back and still be logged in. I have searched this site for an answer, and couldn't find one that made sense. Here is my login code
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
if ($username&&$password) {
$connect = mysql_connect("127.0.0.1","root","") or die('Couldn\'t Connect to Database');
mysql_select_db ("login") or die('Couldn\'t find database');
$query = mysql_query("SELECT * FROM members WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0) {
while($rows = mysql_fetch_assoc($query)){
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
}
if ($username==$dbusername&&$password==$dbpassword) {
echo "Login Successful. <a href='home.php'>Click here for the members area</a>";
$_SESSION['username'] = $dbusername;
}
else{
echo "Incorrect Password";
}
}
else{
die("Incorrect Username and Password");
}
}
else{
die("Please enter something in the boxes");
}
?>
Typically, a server-side language is used for this kind of thing. This is because, if you do password checking in JavaScript, anybody can see the correct password (since all the code is available by looking at the page's source code).
In order to do it securely, you'll need to submit the answer to a server and use a server-side language to check the answer. The server-side script then decides what response to give back to the user.
PHP is a very popular language for server side scripting. Here's the basics:
First we need a log in page (login.html) that has a HTML form in it, like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Login</title>
</head>
<body>
<form action="script.php" method="post">
<label>Enter your mom's name: <input type="text" name="mom" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
The important part here is the form. When the form is submitted, the data is sent to a PHP script called script.php.
That script looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Check login</title>
</head>
<body>
<?php
$mom = $_REQUEST['mom'];
$correct_answer = "Barbie";
if (!isset($mom) || $mom != $correct_answer) {
// nothing was submited or the name was incorrect
echo '<p>That\'s the wrong answer. Try again.</p>';
} else {
echo '<p>Welcome! That\'s the right answer.</p>';
}
?>
</body>
</html>
This is a fairly simple script. It checks what was submitted for 'mom'. If nothing was submitted or it was the wrong answer then a 'try again' message is shown. Otherwise, a 'welcome' message is shown.
The PHP logic (and so the correct answer) will not be visible in a web browser. Only the 'try again' or 'welcome' message will be sent down from the server.
This is the basics of working with HTML forms on the server side. I suggest you read up on using PHP. It's an easy and fun language (if inelegant, in my opinion). You can learn the basics here:
http://www.w3schools.com/php/default.asp
To test your code, you will need a web server. You can download and install a fully-fledged web server with PHP and MySQL (a database) from here:
http://www.wampserver.com/en/
With that, you can develop at test server-side code on your own machine. To test the above example, copy the code above into two files, called login.html and script.php, and put them into the www directory of WAMP.
Good luck!
This is what I managed to come up with. At the top of the page, insert this code before the <!DOCTYPE html>
<?php
//Check for existance of cookie from right answer
if(isset($_COOKIE['parents'])){
header("Location:q1.html");//Move on to next question
}
//Checks answer
if(array_key_exists("dad", $_POST) && array_key_exists('mom', $_POST)){
$dad = $_POST["dad"];
$mom = $_POST["mom"];
$dcorrect = array("Dad", "dad");
$mcorrect = array("Mom", "mom");
if(in_array($dad, $dcorrect) && in_array($mom, $mcorrect)){
setcookie('parents', '1' ,time()+60*60*24);
header("Location: index.html");
}else{
$wrong="<div class='error'>Wrong answer</div>";
}
}
?>
With this HTML
<form action="index.html" method="post">
<label>Enter your father's name:</label>
<input required autocomplete="off" type="text" name="dad" placeholder="Bill">
<label>Enter your mother's name:</label>
<input required autocomplete="off" type="text" name="mom" placeholder="Billette">
<input type="submit" value="Press me when you think you are right" />
<?php echo $wrong; ?>
</form>

PHP error with HTML formring

I am learning PHP from a book called PHP and MySQL web development. I am a newbie to PHP , I am pretty well versed with C and HTML, I find syntax of PHP to be pretty same of C.
Look at the code:
<html>
<form action = "processorder.php" method = "post">
<p>tires:<input type=”text” name=”tireqty” size=”3” maxlength=”3” /></p>
<input type=”submit” value=”Submit Order” /></td>
</form>
</html>
This is the HTML code now I will type in the php code and save it as processorder.php
<?php
$tireqty = $_POST[‘tireqty’];
echo "<p>Your order is as follows: </p>";
$tireqty." tires<br />";
?>
After doing this , i go to the html page where I have to enter the value for tires and click submit after doing this it redirects to me mu processorder php page where my raw php code gets displayed and not the proper output which is:
Your order is as follows:
2 tires
But i get a different o/p which is as shown below:
$tireqty = $_POST[‘tireqty’];
echo "<p>Your order is as follows: </p>";
$tireqty." tires<br />";
what is going on here what is wrong??? and i also get an error message is processorder script saying that:
parse error: undefined index 'tireqty' in line something and undefined var tireqty
Hey guys i dont know whats wrong but cant post comments that button is not working or my browser is not enabling me to write comments, I am answering to all the calls here:
Yeah I am using XAMPP what is wrong in that, what should i do?
I copied your codes and yes there are no errors in it but when i go to html page and click submit the browser opens a dialog box saying that "I have chosen to open process.php" and what should it do with it so i select open with gedit because that is the only default option available there, and it redirects to my php script page :(:(:(
WHat is this it is so tough, Is PHP really that difficult or am i working on a poor platform and learning from a bad book?
Is there any good book on php
<?php
$tireqty = $_POST[‘tireqty’];
echo "<p>Your order is as follows: </p>";
$tireqty." tires<br />";
?>
You closed your echo tags in the first 2nd row already, therefor you need to add another echo tag to the 3rde line.
<?php
$tireqty = $_POST[‘tireqty’];
echo "<p>Your order is as follows: </p>";
echo $tireqty." tires<br />";
?>
Always make sure that your variables have been set before you use them:
<?php
if(isset($_POST['tireqty'])){
$tireqty = $_POST['tireqty'];
echo "<p>Your order is as follows: <br />";
echo $tireqty." tires.</p>";
}
?>
Also, your HTML had a random closing table column tag in it:
<html>
<form action = "processorder.php" method = "post">
<p>tires:<input type="text" name="tireqty" size="3" maxlength="3" /></p>
<input type="submit" value="Submit Order" />
</form>
</html>
Sounds like your PHP environment is not working as it should. Do you have a web server with PHP running or XAMP (http://www.apachefriends.org/en/xampp.html)?
Always use
if ( isset($_POST['var']) ) { ... }
Same with $_GET, $_SESSION etc. You variable tireqty isn't initialized until form is submitted, that's why throws errors

Why doesn't this email-address-submitting code work with Opera and Internet Explorer?

I've just discovered the email-address-saving form on my website does not work on Opera and Internet Explorer (7 at any rate), and possibly other browsers. Works fine with Firefox. Unfortunately I'm not a developer and no longer have any contact with the guy who wrote the code for the form so I've no idea how to fix it. I assume the problem has something to do with the code below:
<?php
$str = '';
if (isset($_POST['submit']))
{
if(!eregi("^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['email'])) {
$str = "<span style='color: red'>Not a valid email address</span>";
} else {
$file = 'emails.txt';
$text = "$_POST[email]\n";
if (is_writable($file)) {
if (!$fh = fopen($file, 'a')) {
exit;
}
if (fwrite($fh, $text) === FALSE) {
exit;
}
fclose($fh);
}
header('Location: thankyou.html');
}
}
?>
and then the body bit:
<form action="index.php" method="post">
<input type="text" name="email" style="width: 250px;" />
<input type="image" src="img/button-submit.png" name="submit" value="Submit" style="position: relative; top: 5px; left: 10px" />
</form>
<?php echo $str ?>
Anybody feeling pity for a helpless non-dev and have an idea what's not working here?
This is being caused by the fact that the submit input is of type 'image'. On submit, IE7 only returns the x and y coords of the click.
This should do the trick:
Replace:
if (isset($_POST['submit']))
With:
if (isset($_POST['submit']) || isset($_POST['submit_x']))
It is a browser based issue
in your form, you have used <input type="image" />
IE doesn't pass name/value pairs for image type input, instead it only sends the key_x/value_x and key_y/value_y pairs
you probaly want to use <input type="submit" /> as replacement/addition, since this is completely supported on all types of browsers (think also about text browsers please, i still use them.)
Unfortunately, the error, if any at all, is going to be between the Browser and the server, not PHP. If you could provide some details like the HTML form that isn't working in IE7, then we may be able to help out more.
Your form element is self-closed. Remove the trailing / in the opening tag and it should work. (Er, it might work. Either way, there shouldn't be a trailing slash.)
Assuming that the php in your code is in the same file as the form ... you might try adding the name of your php file to the form's action.
<form action="" method="post">
... becomes ...
<form action="name_of_php_file" method="post">
Include a hidden field in your form that will only be valid and present if you submit the form. Something like:
<input type="hidden" name="checkemail" value="1" />
Then, in your PHP, change the if-condition to check for this particular variable:
<?php
$str = '';
if (isset($_POST["checkemail"]))
{
//-- rest of your code
}
?>
This will allow you to keep the image as the submit button and work across browsers which differ in how they send the value, if at all, of the name of image type buttons.
I know this doesn't fix your problem, but I don't like the line:
$text = "$_POST[email]\n";
Is that not bad practice? I haven't used PHP for years, but I think you should change it to
$text = $_POST['email'] . "\n";
or something like that. Using $_POST[email] without the quotes around the array key causes PHP to first look for a constant named 'email'. Only after not finding it will it convert email to a string and then pull the value out of the associative array. Just wasted CPU power.

Categories