I am trying to put a function that I will commonly use in its own file. Then, I want to include that file so I have access to the function (or so I think).
activity.php (this is the function I want to be able to use)
<?php
function activity() {
$inactive = 600;
// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
$_SESSION["loggedIn"] = false;
session_destroy();
echo "session destroyed";
}
}
else {
echo "You need to log in.";
}
}
?>
Here is showuser.php (the file where the error occurs):
<?php
include ('activity.php');
session_start();
// check to see if $_SESSION["timeout"] is set
activity();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password="xxx"; // Mysql password
$db_name="itit"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
if($_SESSION["loggedIn"]) {
$stmt = $mysqli->prepare("SELECT email FROM users WHERE username = ?");
$stmt->bind_param("s", $_SESSION["username"]);
$stmt->execute();
$stmt->bind_result($em);
$stmt->fetch();
}
else {
echo "You are not logged in.";
}
?>
<h2>Username - Email</h2>
<div id="userinfo"><? echo $_SESSION["username"] ?> - <? echo $em ?></div>
<?
$stmt->close();
mysqli_close($mysqli);
?>
The function should check to see if the session has timed out, unless I am doing something wrong with that code...
I get these errors when running the scripts which include the file:
Warning: include(activity.php) [function.include]: failed to open stream: No such file or directory in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: include() [function.include]: Failed opening '/activity.php' for inclusion (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear') in /Users/Eamon/Sites/templates/showuser.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Users/Eamon/Sites/templates/showuser.php:2) in /Users/Eamon/Sites/templates/showuser.php on line 3
Fatal error: Call to undefined function activity() in /Users/Eamon/Sites/templates/showuser.php on line 6
UPDATE
I did this instead
include ('../activity.php');
This got rid of all the errors except for the "Warning: session_start" error.
Looks like a problem with the directory where PHP is looking for the file.
Try changing it to include ('./activity.php');
If activity.php is in /Users/Eamon/Sites/templates/ you can change your include to
include (__DIR__'."/activity.php');
and it should work for you.
Related
I've seen the use of header in the php to redirect to a page.
I've used the method in the code below and the a redirect error as given below the code.
I need to know what went wrong with the code.
Here is the code (php) :
<?php
/**
* Created by PhpStorm.
* User: Priyabrata
* Date: 3/18/14
* Time: 8:58 PM
*/
function connect_to_db($uid, $pass){
$con=mysqli_connect("localhost", "root", "12345", "MyDB");
if (mysqli_connect_errno()){
echo "Failed to establish link!!";
}else{
echo mysqli_connect_error();
}
$result=mysqli_query($con, "SELECT `pwd` from `login_table` where `uid` = "."'".$uid."'");
if (!$result){
echo "Error!!";
exit();
}
while($xx = mysqli_fetch_array($result)){
if ($xx['pwd'] == hash("MD5", $pass)){
header("location:../Html/Login-Existing-Users1_success.htm");
exit();
}else{
echo "Invalid Login Credentials!!";
exit();
}
}
mysqli_close($con);
}
function validate_credentials(){
if ((isset($_POST["username"]))&&(isset($_POST["password"]))){
$uid = $_POST["username"];
$pwd = $_POST["password"];
if (($uid == "")||($pwd == "")){
echo "Please enter User name and password";
}else{
//Check user name and password
connect_to_db($uid, $pwd);
}
}else{
echo "Please enter User name and password";
}
}
validate_credentials();
Here is the error I get, instead of a redirect when uploaded to the server:
Warning: Cannot modify header information - headers already sent by (output started at /home/opticfhb/public_html/helpvssupport.net/login.php:19) in /home/opticfhb/public_html/helpvssupport.net/login.php on line 27
Additional Info : This works perfectly in my local machine and creates the problem in the server.
You can't call header() after you've already echoed any output. HTTP requests contain header information and data. Any output is part of the data, and data comes after all the headers have already been sent.
PHP has a function called headers_sent to check whether or not the headers have already been sent or not. You might consider writing a function that issues the Location header if they haven't been, or echo out some simple redirect HTML if they have -- perhaps by including this tag in the <head>:
<meta http-equiv="refresh" content="0;http://www.website.com/redirect/url" />
hello this is my first post on stackoverflow i am at beginner level at php, mysql and work on a php log in page connected to a mysql database which i did try to test through xampp and getting the following error message
Warning: include(../storescripts/connect_to_mysql.php): failed to open stream: No such
file or directory in C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php
on line 15
Warning: include(): Failed opening '../storescripts/connect_to_mysql.php' for
inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\myonlinestore
\storeadmin\admin_login.php on line 15
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in
C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php on line 18
That information is incorrect, try again Click Here
I was able to successfully connect to the mysql database through dreamwavercs6 on win7 64bit and created a user for the db as also i created a administrator with full privileges in the created admin table. With a successful log in it should direct you to a follow up page called index.php which is a second index page only for admins to choose tasks, located in a subfolder in the same directory. The home page index.php is located here C:\xampp\htdocs\myonlinestore\index.php\
the file with the script called admin_login.php is shown under here
<?php
session_start();
if (isset($_SESSION["manager"])){
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])){
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]);
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND
password='$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount == 1){
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
the script connect_to_mysql.php under here
<?php
$db_host = "localhost";
$db_username = "user";
$db_pass = "user";
$db_name = "myonlinestore_db";
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to
mysql");
mysql_select_db("$db_name") or die ("no database");
?>
the script index.php which is the landing page where on successful login from admin_login should redirect you to, under here
<?php
session_start();
if(!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i', '',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);
include"../storescripts/connect_to_mysql.php";
$sql=mysql_query("SELECT*FROM admin WHERE id='$managerID' AND username='$manager' AND
password='$password' LIMIT 1"); // query the person
$existCount=mysql_num_rows($sql); // count the nums
if ($existCount==0){//evaluate the count
echo "Your login session data is not on record in the database";
exit();
}
?>
the problem is that i can not log in through my firefox browser and getting the error as mentioned at the top. All addons,extensions in my firefox browser are on disable and accepting cookies is selected, can anyone help to fix this problem?
Many thanks in advance
Here in your script you are not being able to include your connect_to_mysql.php file.
include "../storescripts/connect_to_mysql.php";
You are trying to provide relative path. Make sure you are properly able to access that file from relative path you are including. i.e. your admin_login.php file.
You can try passing absolute path in your include:
include "C:\xampp\htdocs\myonlinestore\storescripts\connect_to_mysql.php";
please check path in your file manager if it is correct absolute path.
Remove one of the dots from the include("../if the scripts are in
C:\xampp\htdocs\myonlinestore\storescript.
From
C:\xampp\htdocs\myonlinestore\storeadmin\admin_login.php
"../" will take you to htdocs, so you need "./" to get to htdocs\myonlinestore
may be it will help you.
<?php
$server = "localhost";
$connection = mysqli_connect ($server,"root","","your_database_name");
if(!$connection){
// if not connected it will gives the error here
echo "server not found".mysql_error();
}
else{
echo "Connected";
}
?>
I am having an issue with my header location. I am new to php and I am unable to redirect to my index page after this separate php file is run. In addition my function is unable to tell whether the contents of a text box is blank or equal to the default value of "<>".
Thank you
<?php
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
{
// the form was submitted
//remove hacker HTML
$email2=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email2'";
$result=mysql_query($sql2);
//Direct back to homepage
echo "heloooo";
header('location:/index.php');
}
else
{
header('location:/index.php');
}
}
else
{
header('Location:http://www.google.com');
`enter code here`}
?>
EDIT
After making the changes suggested my error log is as follows
Notice: Use of undefined constant db_selected - assumed 'db_selected' in /home/clubbtpk/public_html/connectionFile.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /home/clubbtpk/public_html/connectionFile.php:15) in /home/clubbtpk/public_html/addEmail.php on line 28
The code in the connection file is:
<?php
$host="localhost";
$username="username";
$password ="password";
// Create connection to mysql server
$con=mysql_connect("$host","$username","$password");
// Check connection
if (!$con)
{
die ("Failed to connect to MySQL: " . mysql_error());
}
// Select database
$db_selected = mysql_select_db("DB", $con);
if(!db_selected)
{
die ("Cannot connect : " . mysql_error());
}
?>
EDIT 2
Resolved first error by changing
if(!db_selected)
to
if(!$db_selected)
RESOLVED
Added the following line of code to my index.php file:
<?php
if(isset($_REQUEST["emailAdd"])){
include("addEmail.php");
}
?>
Then changed the action of the form to "" so that it reloads the current page:
<form name="emailAddr" method="post" action="">
You must not output anything before your redirect.
So this is not allowed:
echo "heloooo";
header('location:/index.php');
EDIT: You should definitely enable error_reporting on your script. I found another error in your query:
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
should be
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
Furthermore you should not use the mysql_* functions anymore but upgrade to mysqli_* functions. And always check the inputted data before inserting them into sql-queries.
EDIT2: Add this at the beginning of your script:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
EDIT3:
You have to change this line too:
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
Should be:
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>")
If you would turn error_reporting on you would see it yourself.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Warning: Cannot modify header information - headers already sent
Headers already sent by PHP
Error: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\GameHutWebsite\data\connection.php:1) in C:\xampp\htdocs\GameHutWebsite\login.php on line 21
I am getting this error when the user enters the correct username and password in the login screen to send the user in the home page. This is the code:
<?php
if ($_POST)
{
$dsLogin = $dataobj->validateLogin($_POST["txtUsername"],$_POST["txtPassword"]);
if (mysql_num_rows($dsLogin))
{
$dsUserDetails = mysql_fetch_array($dsLogin);
$_SESSION["UserEmail"] = $dsUserDetails["UserEmail"];
$_SESSION["Username"] = $dsUserDetails["Username"];
$_SESSION["UserTypeId"] = $dsUserDetails["UserTypeId"];
header ("Location: index.php");
}
else
{
$msg = "Invalid Username and Password!";
}
}
?>
Connection Class:
<?php
class connection
{
function connect($sql)
{
$server = 'localhost';
$myDB = 'gamehutdb';
//connection to the database
$dbhandle = mysql_connect($server, 'root', "")
or die("Couldn't connect to SQL Server $server");
//select a database to work with
$selected = mysql_select_db($myDB)
or die("Couldn't open database $myDB");
//execute the SQL query and return records
$result = mysql_query($sql);
//return result set
return $result;
//close the connection
mysql_close($dbhandle);
}
}
?>
You have used
header ("Location: index.php");
AFTER sending something to the client (ie, using echo or print), make sure that there is nothing sent to the client before that code.
Another reason might be a BOM problem.
This is probably due to the fact that your connection class is emitting some kind of output
Comment out the "header" line and run your script. If you get some output, then that's the reason.
You should conditionally launch the "header" line based on whether you get an error or not, at least while you troubleshoot your problem.
I've changed my hosting server from a Windows to a Linux system. But when I run my PHP program, I get this errors:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/p/y/c/francis/html/login/login.php:2) in /home/content/p/y/c/francis/html/login/login.php on line 4
and
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/p/y/c/francis/html/login/login.php:2) in /home/content/p/y/c/francis/html/login/login.php on line 4
This is the code of my program:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect(***,***,***);
mysql_select_db("phploginregister") or die("Couldn't find db");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows != 0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//check to see if they match!
if ($username == $dbusername && md5($password) == $dbpassword)
{
echo "You're in! <a href='member.php'>Click</a> here to enter the member page.";
$_SESSION['username'] = $dbusername;
}
else
echo "Incorrect password";
}
else
die("That user doens't exist!");
}
else
die("Please enter an username and password");
?>
What is wrong in the code, because it workend fine on a Windows host...
You get the error because there are some output before you have initiated session_start(); This could be caused because of your editor that include a BOM character in the beginning of your file. Try open the code in notepad and see if there are any lines before session_start(), (spaces) or things like that and remove them.
To fix your editor if it add a bom in your file, you need to go to your settings and turn it off.
You have a leading BOM, new line or other whitespace character before the opening <?php tag.
The errors talk about line 2 and line 4, but in the actual code above session_start() is called on line 3. Therefore, leading whitespace is the problem...
i think you should add
ob_start();
in the first of your code
and in the bottom add
ob_get_contents();
ob_end_flush();
because of
session send headers to server , also you added echo ( this also tell server its html with headers )
server now has to headers so use the ob_start(); and ob_end_flush(); to work :)