How to Properly Start a Session in PHP? - php

I was recently following a tutorial on how to make a custom CMS for my website. I am currently making the back end, so the users can create and edit pages. The tutorial is kind of old so various functions have been deprecated. I was able to fix most of them, except for the "session_register();" function. I saw on many sites, including this one that told me to use "$_SESSION['admin']=$username;" for example. This is not working for me, since I apply this to many pages, each page is asking me to re-enter the information.
Here are files I am using:
admin_check.php:
<?php
$error_msg="";
if ($_POST['username']){
$username=$_POST['username'];
$password=$_POST['password'];
// Simple hard coded values for the correct username and password
$admin="Admin";
$adminpass="Password";
//connect to mysql here if you store admin username and password in your database
//This would be the prefered method of storing the values instead of hard coding them here into the script
if(($username !=$admin)||($password != $adminpass)){
$error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
} else{
$_SESSION['admin']=$username;
require_once "index.php";
exit();
}
}
?>
<?php
if ($_SESSION['admin']!="Admin"){
echo '<div class="container" style="background-color: #FFF ;"><h3><i class="glyphicon glyphicon-alert text-danger"></i> Solo los administradores
tienen permiso para ver este directorio. No se admite gente con Lag! </h3><br/>
<!DOCTYPE html
<html>
<head>
<title>Login Administrador</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href="../css/bootstrap.min.css" rel="stylesheet" />
<link href="../css/styles.css" type="text/css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap- glyphicons.css" rel="stylesheet">
</head>
<body style="padding-top: 5px; background-color: #EEE ;">
<div style="max-width: 450px; max-height: 550px; background-color: #CCC; padding-top: 30px; box-shadow: 0 0 15px #DDD; border-radius: 10px" class="container">
<div class="jumbotron" style="background-color: #fff; max-height: 470px; padding: 10px; border-radius: 2; box-shadow: 0 0 12px #777;">
<legend class="text-success">LOGIN ADMINISTRATOR</legend>
<hr />
<p style="font-size: 12pt;">Please enter your username and password to login into the admin site.</p>
<form action="admin_check.php" method="post" target="_self" class="form-group">
<label class="label label-default">username</label>
<input type="text" class="form-control" placeholder="username" name="username" id="username">
<br/>
<label class="label label-default">password</label>
<input type="password" class="form-control" placeholder="password" name="password" id="password">
<br/>
<button class="btn-success" value="submit" type="submit" name="button" id="button" >Submit</button>
</form><br/>
'.$error_msg.'
</div>
</div>
</body>
</html>
<br/><br/>
<center> <a href="../" >Click aquí para regresar a un lugar seguro.</a> </div></center>';
exit();
}
?>
^ As you can see, this is where the admins input the username and password, which I'd like to have stored somehow, like in a cookie, so they can navigate freely without having to input the username and password over and over again.
index.php:
<?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<body id="home">
<div class="container" style="background-color: white;">
<h2 style="color: #FF691F"><i class="fa fa-home fa-2x"></i> Home</h2>
</div>
</body>
<?php include "admin_footer.php"; ?>
create_blog.php:
<?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<script type="text/javascript">
function validate_form(){
valid=true;
if(document.form.pagetitle.value===""){
alert("Please Enter a Page Title!");
valid=false;
}else if{
alert("Please Enter Keywords about this Page!");
valid=false;
}
return valid;
}
</script>
<script type="text/javascript">
function validate_form1(){
valid=true;
if(document.form.pid.value===""){
alert("Please Enter a Page ID!");
valid=false;
}
return valid;
}
</script>
<body id="blog">
<div class="container" style="background-color: white; box-shadow: 0 -5px 9px 3px #b2b2b2;">
<br/>
<h2 style="color: #777 ;"><i class="fa fa-book fa-lg"></i> Upload Blog Entry</h2>
<p class="text-danger text-center">Title, Body, and Keywords are required to create new post! None should be left blank!</p>
<h6 class="text-muted pull-right"><< Back Home</h6>
<br/>
<form id="form1" name="form1" method="post" action="edit_blog.php" onsubmit="return validate_form1();" class="form-inline">
<div class="form-group">
<button class="btn-default" type="submit" name="button2" id="button2" value="Edit Post">Edit Post</button>
</div>
<input name="pid" type="text" id="pid" size="8" maxlength="11" class="form-control"/>
<span id="helpBlock1" class="help-block">Enter the ID of the post you want to edit. eg: "blog/article.php?pid=<'this is the id'>"</span>
</form>
<br/>
<form id="form2" name="form2" method="post" action="delete_blog.php" onsubmit="return validate_form2();" class="form-inline">
<div class="form-group">
<button class="btn-default" type="submit" id="button3" name="button3" value="Delete Post">Delete Post</button>
</div>
<div class="form-group"><input type="text" class="form-control" id="pid" name="pid"/></div>
<span id="helpBlock2" class="help-block">Enter the ID of the post you want to delete. eg: "blog/article.php?pid=<'this is the id'>"</span>
</form>
<br/>
<form id="form" name="form" method="post" action="congrat_blog.php" onsubmit="return validate_form();">
<div class="form-group">
<label>Title</label>
<input type="text" name="pagetitle" id="pagetitle" class="form-control" placeholder="Title..." value="<?php echo $pagetitle; ?>"/>
<br/>
<br/>
<label>Body</label>
<textarea name="pagebody" id="pagebody" style="height: 480px; width: 100%" ><?php echo $pagebody; ?></textarea>
<br/>
<label>Keywords</label>
<input type="text" name="keywords" id="keywords" class="form-control" placeholder="blog, mmob, etc..." value="<?php echo $keywords; ?>" />
<br/>
<button type="submit" class="btn-success" name="button" id="button" value="Create this page now">Submit</button>
</div>
</form>
</div>
</body>
<?php include "admin_footer.php"; ?>
^Like this I have multiple pages, all with the php function "session_start();" at the beginning of the document, and I included_once the "admin_check.php" with the "$_SESSION['admin']=$username" function on all of them.
Note: admin_header.php, and admin_footer.php are just HTML header navbar and footer, so I don't have to correct those for individual pages.
I am fairly new to php. Am I on the correct path of doing this?
Basically all I am trying to is a login feature so that the admins can access a back end which will let them upload information into a database, so it populates the site.
Here is the link of the tutorial series I've been following to create this basic CMS:
How to Build PHP and MySQL CMS Website Software
Thanks for your time!

So that tutorial didn't mention having to start the session in every page, but it does.
Therefore session_start(); but be part of all files using sessions.
Error reporting would have helped you here: http://php.net/manual/en/function.error-reporting.php
Another thing that tutorial may not have covered is "passwords".
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
If you plan on using a database later on, use PDO with prepared statements or mysqli_* with prepared statements
This is just an insight.

Looking at your code, you've forgotten session_start() at the start of your PHP file, it would be a good idea to put this at the top of your PHP file, so that sessions will work. This usually sets (or uses an already passed) cookies which then identifies the user so $_SESSION variables will work.
http://php.net/manual/en/function.session-start.php

Problem : You forgot to start session before setting session in your code.
Solution :
Replace your first portion of code with this one fixed :
<?php
session_start();
$error_msg="";
if ($_POST['username']){
$username=$_POST['username'];
$password=$_POST['password'];
// Simple hard coded values for the correct username and password
$admin="Admin";
$adminpass="Password";
//connect to mysql here if you store admin username and password in your database
//This would be the prefered method of storing the values instead of hard coding them here into the script
if(($username !=$admin)||($password != $adminpass)){
$error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
} else{
$_SESSION['admin']=$username;
require_once "index.php";
exit();
}
}
?>
Note : Remember to run the session_start() statement on your pages before you try to access the $_SESSION array or trying to set one, and also before any output is sent to the browser.
Reference URL :
http://php.net/manual/en/session.examples.basic.php

Related

Login Page: Span text error does not appear in table upon PHP prompt & Unable to progress when correct username and password given

This post was quite hard to title as I believe the issue I am having is spurred by multiple things.
I am trying to create a login system using HTML and PHP with the requirement of not using a database for username and password validation / storage. I found a good piece of code online that I liked the look of - it fulfills the requirements and works perfectly, so I tried to apply the elements it used in my own coding. However, my version does not offer any indication of working at all.
The original piece of code I found can be seen at this link here: https://www.w3schools.in/php/examples/php-login-without-using-database
The image above is of the program I am trying to take elements from - predominantly the "invalid login details" prompt that appears at the top of the page when login is pressed and an incorrect username and password is given. The code for this can be seen here:
<?php session_start(); /* Starts the session */
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('admin' => '123456','username1' => 'password1','username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
?>
The code is rather self-explanatory but I am very new to using PHP.
The remainder of the file is HTML based, creating the input boxes and button inside of a table, the code of which can be seen here:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Script Without Using Database</title>
<link href="./css/style.css" rel="stylesheet">
</head>
<body>
<div id="Frame0">
<h1>PHP Login Script Without Using Database Demo.</h1>
<p>More tutorials www.w3schools.in</p>
</div>
<br>
<form action="" method="post" name="Login_Form">
<table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
<tr>
<td colspan="2" align="left" valign="top"><h3>Login</h3></td>
</tr>
<tr>
<td align="right" valign="top">Username</td>
<td><input name="Username" type="text" class="Input"></td>
</tr>
<tr>
<td align="right">Password</td>
<td><input name="Password" type="password" class="Input"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" value="Login" class="Button3"></td>
</tr>
</table>
</form>
</body>
</html>
Once the user enters one of the 3 pre-defined usernames and passwords, they should be taken to a website called "index.php" which simply gives an affirmation that you have passed verification as you can only access it with the correct credentials - the code of which is here:
<?php session_start(); /* Starts the session */
if(!isset($_SESSION['UserData']['Username'])){
header("location:login.php");
exit;
}
?>
Congratulation! You have logged into password protected page. Click here to Logout.
My code is slightly different; I am using a stylised form to display my interface, and I am very much set on keeping it. However, I think this may be the issue as to why I cannot verify usernames and passwords.
My version of the code can be seen below.
<?php
session_start();
/* Check Login form submitted */
if (isset($_POST['Submit'])) {
/* Define username and associated password array */
$logins = array('admin' => '123456', 'username1' => 'password1', 'username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password) {
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username'] = $logins[$Username];
header("location:index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg = "<span style='color:red'>Invalid Login Details</span>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>U33 DATABASING</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-black.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Navbar -->
<div class="w3-top">
<div class="w3-bar w3-theme-d2 w3-left-align">
<a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right w3-hover-red w3-theme-d2"
href="javascript:void(0);" onclick="openNav()"><i class="fa fa-bars"></i></a>
<a href="http://localhost/webserver/navigationpage/navpage.html"
class="w3-bar-item w3-button w3-black w3-hover-red"><i class="fa fa-home w3-margin-right"></i>U33</a>
<div class="w3-dropdown-hover w3-hide-small w3-hover-red">
<button class="w3-button w3-hover-red" title="Notifications">Important Links <i
class="fa fa-caret-down w3-hover-red"></i></button>
<div class="w3-dropdown-content w3-card-4 w3-bar-block w3-black">
<a href="http://localhost/webserver/cvwebpage/cv.html"
class="w3-bar-item w3-button w3-hover-red">CV</a>
<a href="http://localhost/webserver/phplogin/login.php"
class="w3-bar-item w3-button w3-hover-red">Literary Database</a>
Submit an Article
</div>
</div>
</div>
<!-- Navbar on small screens -->
<div id="navDemo" class="w3-bar-block w3-theme-d2 w3-hide w3-hide-large w3-hide-medium">
CV
<a href="http://localhost/webserver/phplogin/login.php" class="w3-bar-item w3-button w3-hover-red">Literary
Database</a>
Submit an Article
</div>
</div>
<div class="login">
<h1>Literary Database Login</h1>
<table width="300" height="20" border="2px solid black" align="center" cellpadding="4" cellspacing=1 class="table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
</table>
<form action="" method="post" name="Login_Form">
<label for="Username">
<i class="fas fa-user"></i>
</label>
<input type="text" name="Username" placeholder="Username" id="Username" required>
<label for="Password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="Password" placeholder="Password" id="Password" required>
<input class="w3-hover-red" type="submit" value="Login">
</form>
</div>
</body>
</html>
I'm not certain what's wrong here at all; I have assigned the same variable names to my input boxes as would be if they were inside of the table in the other program, but that hasn't seemed to do anything. Additionally, regardless of what is inputted into the two text boxes, the "invalid login details" text does not appear in the that I created - which is a table within the form.
An image of my product can be seen here:
As you can see, there is a grey outlined box above the username field - this is empty and should remain so until the user enters an incorrect username/password. Once this occurs, the red text should appear inside of the box - which I thought I had done when calling upon the $msg function in the else statement of the PHP at the top of the file, but that doesn't seem to work.
Also, when entering the correct information into the username and password field, I am not taken to the index.php file. Just for assurance, here is an image of the index.php page when the username and password are correct:
Maybe this is an issue of variable scope? I'm not really sure and would love any help I can get to figure this out.
Thank you for your time and I look forward to seeing the responses I get.
You are missing the name attribute on the submit button.
<input class="w3-hover-red" type="submit" value="Login">
should be
<input class="w3-hover-red" type="submit" value="Login" name="Submit">
Without it the very first isset fails and it just spits out the html as if you hadn't done anything.

GET request without the question mark

I am a customer service assistant and I wanted to make a simple form to check the price of products on the webpage, without having to load the whole homepage.
The website is www.homebase.co.uk, and the search URL is http://www.homebase.co.uk/en/homebaseuk/searchterm/.
I want to make a form where it will add the text entered in the form after /searchterm/ without the question mark.
EG if I type in 775199 and press submit/search it will navigate to http://www.homebase.co.uk/en/homebaseuk/searchterm/775199.
Thanks so much for your help all :)
I really appreciate it!
Assuming you are using PHP. I think what you want to do is this:
<?php
//THIS IS THE SAME PAGE WHERE YOUR SEARCH FORM EXISTS
$searchPage = "http://www.homebase.co.uk/en/homebaseuk/searchterm/";
$formAction = "./"; //FORM IS SUBMITTED BACK TO ITSELF...
if(isset($_POST['search_term']){
//BUILD THE REDIRECTION LINK BASED ON THE DEFAULT SEARCH PAGE: $searchPage . $_POST['search_term'])
//AND THEN REDIRECT TO THE REDIRECTION LINK
header("location: " . $searchPage . htmlspecialchars(trim($_POST['search_term'])) );
exit;
}
Your HTML Form might look something like this:
<form method="POST" action="<?php echo $formAction; ?>" >
<input type="text" name="search_term" id="search_term" value="" class="search_term" />
<input type="submit" name"submit" id="submit" class="submit" value="Search" />
</form>
Okay, so I solved the problem:
<style type="text/css">
.biga {
font-family: Arial, Helvetica, sans-serif;
font-size: 36px;
color: #F90;
background-color: #FFF;
border: medium solid #000;
}
}
.centerpoint {
text-align: center;
}
</style>
<title>Product Search</title>
<p>
<div class="centerpoint"> <span class="centerpoint">
<input name="prog_site" type="text" class="biga" id="prog_site" value="" />
<a href="http://"
onclick="this.href=(
'http://www.homebase.co.uk/en/homebaseuk/searchterm/' + document.getElementById('prog_site').value)"
target="_blank">
<input name="so_link" type="button" class="biga" value="Search Product">
</a>
</p>
</span></div>
This is the code I used. Thanks for all of your help!

Weird PHP within html

I've written some html code, and once i tried to place some PHP inside it, anything below this sign ?> wouldn't appear!!! I have some pictures and text that wouldn't appear unless I place it above. I'm writing with Bootstrap 2.3 and phpMyAdmin 4.10. all languages. Thank you for your time in advance.
here is my code so far:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassowrd" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassowrd" placeholder="Your password">
<input class = "btn btn-default" type="submit" value="Sign in">
</form>
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
header("location:index.php");
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
?>
</div>
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
</body>
</html>
A few things have already been outlined (as answers) that do make sense, however I spotted a few typos in your inputs that will prevent your form from working, plus a few other points.
Here are a few of my recommendations:
First, this (in 2 instances) has a typo in it name="usrPassowrd" which should read as name="usrPassword" to go with your existing $password = $_POST['usrPassword'];
As I stated in my original comments:
Comment #1: die("cannot go empty"); header("location:index.php"); exit; Your header won't do anything, because it DIE()'d and that will cease to go any further.
Comment #2: What I suspect is going on is, because you've got your entire code inside one big clump, and that if certain conditions aren't met... it still wants to keep going. Now, I suggest that you put a conditional statement wrapped around your PHP....
such as if(isset($_POST['submit'])){ // PHP } then add this to your submit button name="submit" --- I also suggest you split up your form and your PHP/SQL altogether and make it submit to another page instead, with the same conditional statement I've already outlined.
If you absolutely want to execute everything in one page, try the following:
Note: I borrowed the img src from user3009875's answer also.
(Rewrite)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassword" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassword" placeholder="Your password">
<input class = "btn btn-default" name="submit" type="submit" value="Sign in">
</form>
<?php
// this below, will prevent a premature execution of code
if(isset($_POST['submit'])){
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
// header("location:index.php"); // commented out
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
} // end brace for if(isset($_POST['submit']))
?>
</div>
<!-- commented out original img src -->
<!--
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
-->
<!-- new img src by user3009875 in an answer given -->
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
</body>
</html>
You can't use header() there to perform a redirection because you've already outputted some HTML and PHP has flushed HTTP headers.
The reason that <img> disappeared is probably that you called die(). This function terminates the whole page at once.
If you see cannot go empty, you should check the form to make sure you posted username field. If you see some error message about MYSQL, it is mysql_query($query) that fails.
By the way, your code has a SQL Injection problem.
IT doesn't load below ?> because script fails. This is common behaviour when there is a bug.
Check tail -f /var/log/apache2/error.log on linux (terminal)
Check tail -f /var/log/apache2/error_log on max (terminal)
windows -> I have no idea... somewhere in C:\\
At this point:
die("cannot go empty");
you stop the script. The following PHP code will not be executed and the HTML will not be sent to the user.
It's possible that there is an error when executing your PHP code, that would prevent it from going through the rest of the file.
Using your browser's Developer Tools, check the contents of the HTML that was returned, it's possible that the last line could be an error message. If you have erorr_reporting off then it would write to your error log only.
/var/log/apache2/error.log is a common location for the error log file if you are using Apache on a Linux machine.
As a side note, that code you have is very dangerous, do not use data sent from the client directly in a SQL statement, you need to sanitize otherwise you make your web app vulnerable to SQL injection.
Consider using a prepared statement
http://php.net/manual/en/pdo.prepare.php
Try:
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
I think setting the top margin to -800px will cause it to disappear from the screen.
Also, make sure your image is of .jpg.

Trouble with form validation using PHP

I have a relatively simple sounding question that hopefully entails a simple answer. I am currently developing a website that is a scroll-down type; everything is on one page, you know the one. My 'contact' section is at the very bottom of the page, and I am of course doing form validation with PHP. The validation part works, I have no trouble with that. However, if validation fails, the browser takes me back all the way back to the top of the page; this is inconvenient for obvious reasons.
I am aware of the 'header()' function, which I can use to keep me at the bottom of the page if an error occurs. As an example, at the top of my HTML page before the DOCTYPE, I can write:
if ($errors) {
header(Location: 'somelocation.php#contact');
}
This works, but for some reason it prevents my PHP embedded in my html to work. If some errors occur, I want to display them using PHP on the page:
<h2>Contact</h2>
<?php if($errors) { ?>
<p class="warning">Please fix the errors</p>
<?php } ?>
'Please fix the errors' does not appear. It does appear however, if I remove the header function from the page, so I know the problem is related. So basically, if I remove the header() function, the page goes back to the top, and the errors show; if I keep the header() function, the page correctly stays where it is, but no errors show.
Alternatively, this question also can be asked in the case of, what happens when the form is validated correctly, the 'header' function is called, and I want to stay at the bottom of the page and display some HTML saying 'Thanks, your form has been submitted'? (I don't want to go to a 'thank-you' page or anything, just stay in the same spot and give a 'thanks' on the page) I assume I'd run into the same problem. Is there a solution to this?
Thanks in advance!
Specifying a location in the header will cause the browser to redirect to that URI. This is being called before any output is sent to the browser.
When the page is reset, $errors == false, so the paragraph isn't displayed.
It sounds like you need to integrate AJAX, or a mixture of server- and client-side code here.
A very simple and efficient way to validation of a form is using jquery, A perfect example of this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>A simple comment form with submit validation and default messages</legend>
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
<p>
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
</p>
<p>
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
Happy Coding.!!!

Trying to use preg_match on extracted html page but this is perplexing me

I've been trying the below script (within a larger app I'm working on) for hours now and I just can't understand what the problem is, no matter what I get "Notice: Undefined offset: 1" meaning that its having some problem putting the result into an array from the preg_match... I did a process that was nearly identical to a similar page earlier and it worked fine.. I would greatly appreciate any advice as I just don't know what to do at this point as I've already spent hours trying to troubleshoot this, I don't have tons of regex experience but I have used it a fair amount and I just can't figure out what could be preventing this from working correctly.
<blink>
<?PHP
$email_saved_page = '
<meta name="viewport" content="width=device-width"/>
<title>Sign in to Hushmail Mobile</title>
<style type="text/css">
div#logo{padding:0.3em;}
/* */
body{font-family:Arial;font-size:0.8em;margin:0em;}
h2{padding:0.3em;color:#fff;font-weight:bold;background- color:#006699;font- size:1.1em;margin:0em;padding-left:0.3em;}
h2 a{color:#fff;text-decoration:none;padding:0.3em;padding-left:0em;width:100%;}
/* */
div.content{padding:0.4em;}
div.menu{padding:0.3em;padding-left:0em;}
/* */
div.user{background-color: #D7E4F0;padding:0.5em;margin-bottom:0.5em;}
/* */
div.noticeContainer{padding-top:0.1em;}
div.success{background-color:#54b067;}
div.error{background-color:#aa4444;}
div.info{background-color:#ff9900;}
div.notice{padding:0.5em;color:#fff;font-weight:bold;}
div.notice a{color:#fff;text-decoration:none;}
/* */
div.search_results{margin-bottom:1em;}
div.search_results h4{margin-bottom:0em;}
/* */
div.listItem{border-bottom:dotted 1px #ccc;padding:0.5em;padding-left:0em;padding- right:0em;}
div.listItem a.subject{font-size:1.2em;}
div.listItem div.unread{font-weight:bold;}
span.date{color:green;}
/* */
div.headers{padding-top:1em;padding-bottom:1em;}
div.headers label{font-weight:bold;}
div.messageBodyContainer{padding-top:1em;padding-bottom:1em;}
div.message{border-left:solid 3px #eee;padding-left:0.5em;padding-right:0.5em;}
div.messageTruncated{background-color:#eee;padding:0.5em;}
/* */
.background{background-color:#f0f0f0;padding:0.3em;}
/* */
form#compose label.block{display:block;}
/* */
.copy {padding-top: 1em;color: #aaa;}
</style>
</head>
<body>
<div id="logo">
<"/authentication?next_webapp_name=hushmail5&next_webapp_url_name=m&skin=mobile">
branding/hushmailcom/image/logo_small" border="0"/></a>
</div>
<h2>Sign in</h2>
<div class="content">
<div class="noticeContainer" id="authenticationform_hush_username"
style="display:
none;padding: ;width: ">
</div>
<div class="noticeContainer" id="authenticationform_hush_passphrase"
style="display:
none;padding: ;width: ">
</div>
<div class="noticeContainer" id="authenticationform_hush_remember_me"
style="display:
none;padding: ;width: ">
</div>
<form name="authenticationform" id="authenticationform"
action="/authentication/login?skin=mobile&next_webapp_name=hushmail5& amp;next_webapp_url_name=m" method="post">
<input type="hidden" name="form_token" value="a476281f4d85"/>
<input type="hidden" name="next_webapp_page" value="folder/INBOX/1"/>
<p><label for="hush_username">Email address:</label><br/>
<input type="email" name="hush_username" id="hush_username" value="benjuuuhvvihushmailcom"/></p>
<p><label for="hush_passphrase">Passphrase:</label><br/>
<input type="password" name="hush_passphrase" id="hush_passphrase" maxlength="1000" value=""/></p>
<p><input type="checkbox" name="hush_remember_me" id="hush_remember_me" value="on"
/><label for="hush_remember_me">Stay signed in when I close my browser</label></p>
<p><input type="submit" value="Sign In"/></p>
<input type="hidden" name="hush_customerid" value="0000000000000000"/>
</form>
<p>About</p>
<p>To learn more about Hushmail, please visit <wwwhushmailcom/" title="Hushmail - Free Email with Privacy"
>wushmailc/</a> on your computer.</p>
</div>
<!--
-->
<div class="content copy">
© 2008-2010 Hush Communications Ltd.
</div>
';
$preg_string = '%<label>From:</label>(.*)<br>%' ;
preg_match($preg_string, $email_saved_page, $res);
$email_from = $res[1];
echo $email_from ;
?>
</blink>
Change the br part to something like this:
<br ?/?>
your pattern seems to be multiline, isn't it? So you have to set your regexp as multiline too I guess, using the m modifier (see here). Just add 'm' after your second % character.

Categories