PHP page not being displayed error 500 - php

I'm trying to make a website by using PHP and when I run it, it comes back The sharedweb.uniwebsite.ac.uk page isn't working sharedweb.uniwebsite.ac.uk is currently unable to handle this request. 500 And when I click on the Details tab, I get Press the reload button to resubmit the data needed to load the page. Which I have done. The previous pages do work and I'm trying to work on the login page and when I go Register button, that's when I get the error
EDIT
The code that's causing the error is
<?php
// include function files for this application
require_once('bookmark_fns.php');
//create short variable names
$email=$_POST['email'];
$username=$_POST['username'];
$passwd=$_POST['passwd'];
$passwd2=$_POST['passwd2'];
// start session which may be needed later
// start it now because it must go before headers
session_start();
try {
// check forms filled in
if (!filled_out($_POST)) {
throw new Exception('You have not filled the form out correctly. Please go back and try again.');
}
// email address not valid
if (!valid_email($email)) {
throw new Exception('That is not a valid email address. Please go back and try again.');
}
// passwords not the same
if ($passwd != $passwd2) {
throw new Exception('The passwords you entered do not match. Please go back and try again.');
}
// check password length is ok
// ok if username truncates, but passwords will get
// munged if they are too long.
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{6,12}$/)', $passwd)) {
throw new Exception('Your password must be between 6 and 12 characters inclusive. Please go back and try again.');
}
// attempt to register
// this function can also throw an exception
register($username, $email, $passwd);
// register session variable
$_SESSION['valid_user'] = $username;
// provide link to members page
do_html_header('Registration successful');
echo "Welcome " $_POST["username"];
echo 'Your registration was successful. Go to the members page to start setting up your bookmarks!';
do_html_url('member.php', 'Go to members page');
// end page
do_html_footer();
}
catch (Exception $e) {
do_html_header('Warning:');
echo $e->getMessage();
do_html_footer();
exit;
}
?>
EDIT #2
It's still not working

There is an PHP error somewhere. To show the error add the following lines at the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
(remove them after fixing the error, to not expose any secrets later)
Possibility 2 would be to check your error.log, which will tell you why its not working too.

Related

How to stop execution of PHP script when a certain condition is met in IF statement?

I am developing an application using PHP. And I have an HTML form with three input fields: username, password and confirm password.
I want to prevent empty inputs. I have this PHP code for that:
if (empty($firstname)) {
$message = "Please enter first name";
}
if (empty($password)) {
$message = "Please enter password";
}
if (empty($confirm_password)) {
$message = "Please confirm password";
}
Now what it does is that it check for all 3 inputs at once and displays 3 messages. But I want it to check if first name is empty first. And if empty displays the message and exit (terminates the rest of the code, not only within the IF statement but the whole PHPcode. And if not empty then that is when it supposed to jump to the next field which is password in this case.
Please help me to achieve that.
Although the most simplest of solutions, like stated above, would indeed be to just call exit() or die() (which is actually an alias of exit()), it is also the worst solution. By simply killing your script you might prevent from a zombie apocalypse flooding the earth and other realms, but there's virtually not a single good use of exit outside of cli scripts. As a rule of the thumb; if somewhere in your code you've written either exit() or die(), you've done something wrong. Most primarily; the fact that something isn't quite as expected doesn't mean you can't handle it. You don't stay in your bed the whole day because you forgot to buy breakfast, don't you? You go to the supermarket and get some. If something 'unexpected' happens, in this particular case, you report back to your user so he can fix the problem (eg. by filling in the fields he forgot about)
In your case; properly separate your code into relevant parts, and you can handle exceptions (in every sense) like you should handle them. A little script as an example;
function handleForm() {
$formInput = sanitizePostData( $_POST );
if ( ! formValidated( $formInput ) ) {
return false;
}
doWhateverYouWantWithYourPostData();
}
function sanitizePostData( $postData ) {
// do something magical and return clean data
return $sanitizedData;
}
Ideally, you let your handleForm() function throw an Exception, or throw a custom FormException (by extending the Exception class). But if you don't want to, call this handleForm() function something like this;
if ( ! handleForm() ) {
// Present a meaningful message to the user
} else {
// Go and grab a pina colada!
}
You might also want to use try catch syntax, which avoid pyramidal codes of conditionnal statements :
<?php
try {
if (empty($firstname)){
throw new Exception("Please enter first name");
}
if (empty($password)){
throw new Exception("Please enter password");
}
if (empty($confirm_password)){
throw new Exception("Please confirm password");
}
// Everything is fine, logic continues here...
}
catch( Exception $e ) {
$message = $e->getMessage();
die( $message );
}
?>
At the first throw statement, the program automatically jump to the next catch statement. In this case, you throw a Exception, and as we catch them, the first error will be displayed (instead of accumulating all the errors).
As every folks put die for displaying the message I put it too, but you can return a nice HTML error if you would like.
When you read the code again, exceptions let the developper better understand that these conditionnal failures are really exceptions and that the code should stops. It is less easy to undertsand it when we only set up if else statements. That one of the advantages of exceptions.
But exceptions are far more powerful, they make it easy to know which lines thrown the exception, in which file, you can also provide an error code to make it more reliable, ...
Why don't you try else if
if (empty($firstname)){
$message="Please enter first name";
}
else if (empty($password)){
$message="Please enter password";
}
else if (empty($confirm_password)){
$message="Please confirm password";
}
in such code if first condition met then it will skip rest of conditions to check.
You can use die() or exit() - to terminate all, but why do you want to go this way?
As i understand you are doing registration-
You should do it this way -
$message = '';
if (empty($firstname)){
$message.="Please enter first name";
}
if (empty($password)){
$message.="Please enter password";
}
if (empty($confirm_password)){
$message.="Please confirm password";
}
if($message=='')
{
// your code here
}
else
{
echo $message;
}
You also can try something like this
$error = 0;
if (empty($firstname)) {
$error = 1;
$message = "Please enter first name";
}
if (empty($password)) {
$error = 1;
$message = "Please enter password";
}
if (empty($confirm_password)) {
$error = 1;
$message = "Please confirm password";
}
if($error === 0){
// Do whatever you wanna
$message = "Successful message";
}
you need to add
die()
After returning each message.
Pasting the whole code could help me give you a much better answer.
I suggest following...
function doSomething($message) {
echo $message;
exit();
}
if (empty($firstname)){
$message="Please enter first name";
doSomething($message);
}
if (empty($password)){
$message="Please enter password";
doSomething($message);
}
if (empty($confirm_password)){
$message="Please confirm password";
doSomething($message);
}

PHP could not execute query register_new

I have the wamp server running on my laptop and I've got phpmyadmin working, and I'm trying to create a website that allows people to register to. But when I go to the register_new.php file, I get the following error:
Warning: mysqli::mysqli(): (HY000/1045): Access denied for user 'user'#'localhost' (using password: YES) in C:\wamp\www\db_fns.php on line 4
Call Stack
# Time Memory Function Location
1 0.0150 138784 {main}( ) ...\register_new.php:0
2 0.0191 172744 register( ) ...\register_new.php:40
3 0.0191 172760 db_connect( ) ...\user_auth_fns.php:10
4 0.0191 173720 mysqli ( ) ...\db_fns.php:4
Warning: mysqli_query(): Couldn't fetch mysqli in C:\wamp\www\user_auth_fns.php on line 13
Call Stack
# Time Memory Function Location
1 0.0150 138784 {main}( ) ...\register_new.php:0
2 0.0191 172744 register( ) ...\register_new.php:40
3 0.0860 173952 mysqli_query ( ) ...\user_auth_fns.php:13
And I get Could not execute query as a warning
And within my register_new.php file, I have:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
// include function files for this application
require_once('require_fns.php');
//create short variable names
$email=$_POST['email'];
$username=$_POST['username'];
$passwd=$_POST['passwd'];
$passwd2=$_POST['passwd2'];
// start session which may be needed later
// start it now because it must go before headers
session_start();
try {
// check forms filled in
if (!filled_out($_POST)) {
throw new Exception('You have not filled the form out correctly. Please go back and try again.');
}
// email address not valid
if (!valid_email($email)) {
throw new Exception('That is not a valid email address. Please go back and try again.');
}
// passwords not the same
if ($passwd != $passwd2) {
throw new Exception('The passwords you entered do not match. Please go back and try again.');
}
// check password length is ok
// ok if username truncates, but passwords will get
// munged if they are too long.
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{6,12}$/', $passwd)) {
throw new Exception('Your password must be between 6 and 12 characters inclusive. Please go back and try again.');
}
// attempt to register
// this function can also throw an exception
register($username, $email, $passwd);
// register session variable
$_SESSION['valid_user'] = $username;
// provide link to members page
do_html_header('Registration successful');
echo "Welcome " . $_POST["username"];
echo 'Your registration was successful.';
do_html_url('member.php', 'Go to members page');
// end page
do_html_footer();
}
catch (Exception $e) {
do_html_header('Warning:');
echo $e->getMessage();
do_html_footer();
exit;
}
?>
EDIT
The register function is as follows
function register($username, $email, $password) {
// register new person with db
// return true or error message
// connect to db
$conn = db_connect();
// check if username is unique
$result = mysqli_query($conn, "select * from user where username='".$username."'");
if (!$result) {
throw new Exception('Could not execute query');
}
if (mysqli_num_rows($result)>0) {
throw new Exception('That username is taken - go back and choose another one.');
}
// if ok, put in db
$result = mysqli_query($conn, "insert into user values
('".$username."', sha1('".$password."'), '".$email."')");
if (!$result) {
throw new Exception('Could not register you in database - please try again later.');
}
return true;
}
Also, the code I have to connect to the database is
<?php
function db_connect() {
$result = new mysqli('localhost','user','password');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
I have a schema called website and a database on that schema called user which has the following
create table user (
username varchar(16) primary key,
passwd char(40) not null,
email varchar(100) not null
);
EDIT2
It's still not working
The problem lies within your server login credentials. You're providing the wrong username and password and thus unable to connect to your database.
The default username and login is usually:
Username : 'root'
Password : '' // Empty string.
Change the login credentials in your db_connect() function.
<?php
function db_connect() {
$result = new mysqli('localhost','root','');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>

Sign up in php not working and redirecting to same page with blank screen

I am developing Login system in php.I have one file for sign up named as signup1.php when I put details in sign up form and click on sign up button
it show same file signup1.php with blank screen.
I want to redirect myprofile.php when signup the user.
I put this code.
$user->redirect('myprofile.php');
code from the comment:
<?php
require_once 'dbconfig.php';
if($user->is_loggedin()!="") {
$user->redirect('myprofile.php');
}
if(isset($_POST['btn-signup'])) {
else{
try {
$stmt = $DB_con->prepare("SELECT name,email FROM customer WHERE email=:umail");
$stmt->execute(array(':umail'=>$umail));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['email']==$umail) {
$error[] = "sorry email id already taken !";
} else {
if($user->register($fname,$lname,$uname,$umail,$uphone,$upass)) {
$user->redirect('myprofile.php');
}
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
Redirect function:
class User {
public function redirect($url) {
header("Location: $url");
}
}
From the little information you provide I can see one problem. This:
if(isset($_POST['btn-signup'])) {
else{
}
}
Is not going to work, it will throw this error:
PHP Parse error: syntax error, unexpected 'else' (T_ELSE)
An if clause works like this:
if( $condition ) {
// do something if $condition is TRUE
}
else{
// do something else if $condition is FALSE
}
If I understood your code correctly you should just remove the else { line along with its corresponding closing bracket.
Common note: If you encounter the white screen of death in PHP, without any error message, error reporting is usually disabled (wich is normal in production environments). You can activate it with these lines:
ini_set('display_errors',true);
error_reporting(E_ALL);
Alternatively you can look at the error log of your web server (if your hoster provides one, not all do).

PHP Catch exceptions run order

I have some try-catch exception and if statements in the code below that I am trying to write.
try {
$user = new User($userId);
if ($user->getEmailToken() == $emailToken) {
try {
$user->setEmailToken('');
$user->setEmailVerified(1);
$user->store()
fMessaging::create('success', 'verify', 'Your email has been verified. Thank you.');
fURL::redirect('/account/confirm.php');
} catch (fExpectedException $e) {
fMessaging::create('errorMessage', 'verify', $e->getMessage());
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
} else {
fMessaging::create('errorMessage', 'verify', 'User token does not match.');
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
} catch (fExpectedException $e) {
fMessaging::create('errorMessage', 'verify', $e->getMessage());
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
My problem is that when it runs, it is somehow setting the email token value to '' before running the if ($user->getEmailToken() == $emailToken) statement, so it always goes to false.
Actually, somehow not only is it setting that, it is also setting the email verified value to 1 and saving my user in the database. Am I doing something wrong with the way I have the try-catch exceptions laid out?

Bitcoin sendfrom not returning any errors

I am trying to validate bitcoin engine respond once executing with correct amount within the account balance and correct wallet I am getting transaction ID, but if I enter amount too much and fake wallet I am not receiving any error in return just a blank page with html, head and body elements. Is there is any debug mode or what I can do to receive any response?
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
I am using jsonRPCClient to connect with bitcoin engine.
however when I do that in console using RPC commands
I am getting this : Account has insufficient funds (code -6)
code for redirection
if ($message !== '') {
ob_start();
header("Location: mywallet.php?error=done");
die();
} else {
ob_start();
header("Location: mywallet.php?error=true");
die();
}
Update Yes correct I will more ob_start(); above, thing is that once trying (try,catch) event I am getting blank page upon SUCCESS (so not transaction ID like with normal way I am doing I am getting back transaction ID) upon FAIL I am getting Unable to connect to Bitcoin Server. What I just need sounds very simple, how do I verified that transaction is SUCCESSFUL or FAIL, SUCCESSFUL -> I got ID in return, FAIL -> I have got Error in return. SO I can divert users to right places on the page after form is submitted. Actualy I am doing is withdraw funds form, where user inserts amount and his wallet to get funds back from bitcoin account to his private account. Hope this will helps to understand.
UPDATE 2 I have changed construction for that and seems to is working very well, basically is looking for "Unable" word as transaction ID doesn't have that word and other exception I am getting is "Unable to connect to server..." Thank you for guiding me. Any feedback ?
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$e->getMessage();
}
// exit;
if (!strpos($e,'Unable') !== false){
header("Location: mywallet.php?error=done");
die();
} else {
header("Location: mywallet.php?error=true");
die();
}
What bitcoin php library are you using? Looks like maybe this one?
If that's the case, it doesn't return an error message, it throws BitCoinClientException
So you need something like
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
echo $e->getMessage();
}
Updating
The ob_start seems superfluous because you don't output anything before the header location. Unless you have output something before you've reached this point in which case you can't send a header. So you'd need to move the ob_start up towards the top of the script before any output.
Also you aren't sending message to the wallet.php script. Or are you done with it at that point?
RE: update 2
One thing I might add is the possibility of some other exception message occuring we haven't thought of yet that doesn't contain the "Unable." I'd do something more like:
$errorOccured = false;
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$errrorMessage = $e->getMessage();
$errorOccured = true;
}
if (!$errorOccured) {
...
}
else {
header("Location: mywallet.php?error=true&errormsg=" . $errorMessage);
...
}
This would require modifying mywallet.php to accept $errorMessage as an additional GET parameter so you can send it back to the user. Might be nice to additionally use another parameter for sending $message on success which would contain the transaction ID.

Categories