Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent" - php

i am getting Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at error
If i submit form data to a different file for processing, it works. But if i submit form data to the same page, it gives this error.
please suggst
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li>Catalog
<ul><li>Products</li>
<li>Bulk Upload</li>
</ul>
<div class="clear"></div>
</li>
<li>Purchase
</li>
<li>Customer Service
<ul>
<li>Contact Us</li>
<li>CS Panel</li>
</ul>
<div class="clear"></div>
</li>
<li>All Reports</li>
<li>Configuration
<ul> <li>Look and Feel </li>
<li>Business Details</li>
<li>CS Details</li>
<li>Emaqil Template</li>
<li>Domain and Analytics</li>
<li>Courier</li>
</ul>
<div class="clear"></div>
</li>
<li>Accounts
<ul><li>Ledgers</li>
<li>Account Details</li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
Here is the code for Display
<?php
require("includes/conn.php");
$sql = "select CategoryID, CategoryName, FileName, Status from Categories";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<table border='0' cellpadding='10'>";
echo "<tr><td> </td><td>Category ID</td><td>Category Name</td><td>Status</td><td>Edit</td><td>Delete</td></tr>";
echo "<tr><td> <img src=\"images/" . $row['FileName'] . "\" alt=\"\" /> </td>";
echo "<td>". $row['CategoryID'] . "</td>";
echo "<td>". $row['CategoryName'] . "</td>";
echo "<td>". $row['Status']. "</td>";
echo "<td> <a href= 'edit.php?CategoryID=" .$row['id']. "'> Edit </a></td>";
echo "<td> <a href= 'delete.php?CategoryID=" .$row['id']. "'> Edit </a></td>";
echo "</tr> </table>";
}
?>
Nothing is happening here. Please suggest

You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li>Catalog
<ul><li>Products</li>
<li>Bulk Upload</li>
</ul>
<div class="clear"></div>
</li>
<li>Purchase
</li>
<li>Customer Service
<ul>
<li>Contact Us</li>
<li>CS Panel</li>
</ul>
<div class="clear"></div>
</li>
<li>All Reports</li>
<li>Configuration
<ul> <li>Look and Feel </li>
<li>Business Details</li>
<li>CS Details</li>
<li>Emaqil Template</li>
<li>Domain and Analytics</li>
<li>Courier</li>
</ul>
<div class="clear"></div>
</li>
<li>Accounts
<ul><li>Ledgers</li>
<li>Account Details</li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>

I had the same issue, but my solution wasn't as obvious as the suggested ones. It turned out that my php-file was written in UTF-8, which caused issues. I copy/pasted the content of the entire file into a new php-file (Notepad++ tells me this is written in ANSI rather than UTF-8), and now it work flawlessly.

The answer is above by Ross.
Firstly, putting session_start() as the first line of code will mean that you cannot deserialise any objects correctly into session variables.
The reason for getting this issue is 99% likely to be trailing spaces at the end of your include files (yes - I know it sounds unlikely but just try it). The offending file is in the error message. I wanted to back up Ross answer which worked for me but this site is counter intuitive.
IGNORE the nonsense answers. Remove the trailing spaces, newlines etc... and all will be well. ROSS knows what he is talking about.
Putting session_start() at the top of your file DOES work but it isnt the correct solution.

replace session_start(); with #session_start(); in your code

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.
To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).
The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:
include "header.php";
This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.
<?php
session_start();
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>

use ob_start(); before session_start(); at top of your page like this
<?php
ob_start();
session_start();

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.
HTH

Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line

Just replace session_start with this.
if (!session_id() && !headers_sent()) {
session_start();
}
You can put it anywhere, even at the end :)
Works fine for me. $_SESSION is accessible as well.

use session_start() at the top of the page.
for more details please read the link session_start

I was able to solve similar Warning: session_start(): Cannot send session cache limiter - headers already sent by just removing a space in front of the <?php tag.
It worked.

I had a website transferring from one host to another, it seemed to work fine on the old host but a few pages on the new host threw the error Warning: session_start(): Cannot send session cache limiter - headers already sent
while I always kept the
&lt?php
session_start();
at the top of the page no spaces and nothing inserted before
it really bugged me that I stared every page with the session opening, and it worked on some pages and run through a bug on others
I picked the pages that had the problems, backed them up, created new blank pages and simply copied and pasted the code as is, saved and uploaded and boom, problem gone!
this is something you guys may need to consider, it may have been the encoding of the page, or something, not sure the exact source of the problem, but here is a fix to look at in case you guys run into a similar problem
cheers!

In my case I had to set the file encoding without BOM.

This started for me when I redirected my site to https:// (for SSL Certificate). From my experience with this issue, the session_start() had to be before the browser saw any HTML code. For my example, I was using session_start() in nav.php to determine the options of the navigation bar. I ended up placing session_start() right after the php comments in the index.php file and every page which called nav.php. I was able to keep the php comments before session_start() but could not keep the HTML comments above the php.

Check any extra space before php tag.

Related

Cannot Input image to database. Image File Upload Error: Undefined index: file_img

Hi everyone i need some help regarding this error. Im trying to create a module that will allow users to upload their image and display it to the other page. I am using 3 forms (index.php for displaying, create.php for sql query and addform.php for adding records). But everytime I run the program it always shows an error: Undefined index: file_img
index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="assets/jquery-1.11.3-jquery.min.js"> </script>
</head>
<body>
<div class="container">
<h2 class="form-signin-heading">Employee Records.</h2><hr />
<button class="btn btn-info" type="button" id="btn-add"> <span class="glyphicon glyphicon-pencil"></span> Add Employee</button>
<button class="btn btn-info" type="button" id="btn-view"> <span class="glyphicon glyphicon-eye-open"></span> View Employee</button>
<hr />
<div class="content-loader">
<table cellspacing="0" width="100%" id="example" class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Photos</th>
</tr>
</thead>
<?php
require_once 'dbconfig.php';
$sql = $db_con->prepare("select id, name, content, imgname from tblkeanu");
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>' . $result["name"] . '</td>';
echo '<td>' . $result["content"] . '</td>';
echo "<td><img src = 'images/" . $result['imgname'] . "' height='350px;' width='300px;' class='img'></td>";
echo "<td><a id = $result[id] class = 'edit_link' href='#' title = 'EDIT'> EDIT </a></td>";
echo "<td><a id = $result[id] class = 'delete_link' href='#' title = 'DELETE'> DELETE </a></td>";
echo ' </td>';
echo '</tr>';
}
?>
</table>
</div>
</div>
<br />
<div class="container">
<div class="alert alert-info">
Tutorial Link
</div>
</div>
</body>
</html>
create.php
<?php
require_once 'dbconfig.php';
if($_POST)
{
$name = $_POST['txtname'];
$content = $_POST['txtcontent'];
$filetmp = $_FILES['file_img']['tmp_name'];
$filename1 = $_FILES['file_img']['name'];
$filetype = $_FILES['file_img']['type'];
$filepath = 'images/'.$filename1;
try{
move_uploaded_file($filetmp,$filepath);
$sql = $db_con->prepare("INSERT INTO `tblkeanu`(`name`, `content`, `imgname`, `imgpath`, `imgtype`) Values (:name,:content,:filename1,:filepath,:filetype)");
$sql->bindParam(":name",$name);
$sql->bindParam(":content",$content);
$sql->bindParam(":filename1",$filename1);
$sql->bindParam(":filetype",$filetype);
$sql->bindParam(":filepath",$filepath);
if($sql->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
addform.php
<form method='post' id='emp-SaveForm' action="#" enctype="multipart/form-data">
<table class='table table-bordered'>
<tr>
<td>Title</td>
<td><input type='text' name='txtname' class='form-control' placeholder='EX : john doe' required /></td>
</tr>
<tr>
<td>Content</td>
<td><input type='text' name='txtcontent' class='form-control' placeholder='EX : Web Design, App Design' required></td>
</tr>
<tr>
<td>Photo</td>
<td><input type='file' name='file_img'/></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-save" id="btn-save">
<span class="glyphicon glyphicon-plus"></span> Save this Record
</button>
</td>
</tr>
</table>
The tricky part here is if i combined the addform.php to create.php and address bar is "..../..../create.php" the program runs smoothly and the input type was identified. but i need these 2 to be separated and not combined on one page so the webpage will not be refreshed everytime because im also using a javascript and jquery and the address should only be "..../..../index.php".
It will be much appreciated if you could help me out.
In your addform.php file the form dosen't have an action yet, The form action should be create.php.
In the create.php file the condition:
if($sql->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
Should be modified as :
if($sql->execute())
{
header("Location: index.php");
}
else{
echo "Query Problem";
}
This way after saving the records to the database you will be redirected to index.php .
**IN This Section **
<tr>
<td>Photo</td>
<td><input type='file' name='file_img'/></td>
</tr>
Please try this edit, It may help..
<tr>
<td>Photo</td>
<td><input type='file' name='file_img' accept='image/*'/></td>
</tr>

Update query is not working correctly

I am making a code for editing a text area. The query runs correctly without any errors but the textarea is not updated. Can anyone help me with it please?
<html>
<body bgcolor="skyblue">
<form method= "post" enctype="multipart/form-data" action="upd.php">
<table align="center" width="795" border="2" bgcolor="#CCC">
<?php
$i=0;
$sel="select * from video";
$sel_query=mysqli_query($con, $sel);
while($row=mysqli_fetch_array($sel_query)){
$i++;
$var_id=$row['v_id'];
$var=$row['video'];
?>
<tr align="center">
<td align="right">
<br>
<h2>Upadte Video <?php echo $i; ?> Link: </h2>
<button type="submit" name="btn">
<a name="upd" href="upd.php?insert_brand=<?php echo $var_id; ?>&fram=<?php echo $var; ?>">Update</a>
</button>
<td align="left"><br><textarea name="vids" rows="4" cols="50"><?php echo $var; ?>"</textarea></td>
</td>
</tr>
<?php
}
?>
</table>
</form>
upd.php
<?php
include ("includes/db.php");
$check=#$_GET['insert_brand'];
if(isset($_POST['btn'])){
$vids=$_POST['vids'];
$upds="UPDATE `video` SET `video`='$vids' WHERE `v_id`='$check'";
$query=mysqli_query($con, $upds);
if($query){
echo 'The query is executed';
}
else{
echo 'There was an error'. mysqli_error($con);
}
}
?>
Have you tried mysql_real_escape_string() to retrieve textarea data.

table with pagination populated by drop down

im working on a page that populates a drop down menu, from an sql query to show vehicles that belong to a certain user. once a vehicle is selected it runs a function that opens a table with invoices tied to that vehicle. the problem is the number of invoices is rather large and i would like to use pagination to move forward and backwards through them. so far, it brings up the first page just fine. when i click next it gives me an error saying undefined index q and it also looses all my html formatting, most likely because in forwards to my getuser.php page. please take a look at my code and tell me what im doing wrong, ive been trying to get this to work for hours
source code for securedpage.php
<?php
include('config.inc');
include('func.inc.php');
include('db.inc.php');
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'ServiceHistoryDB'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// This could be supplied by a user, for example
$username = $_SESSION['username'];
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM customers
WHERE username='%s'",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['CustNum'];
$custnum = $row['CustNum'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arndt Automotive</title>
<style type="text/css">
body {
background-image: url(Background.png);
}
</style>
</head>
<body>
<table width="1050" border="0" align="center">
<tr align="center">
<td><img src="Banner.png" width="1050" height="275" alt="Banner" /></td>
</tr>
</table>
<table width="1200" height="638" border="0" align="center" background="backgroundmaybe2.png" " style="background-repeat: no-repeat; background- position: center;>
<tr align="center">
<td><table width="1090" height="638" border="0" align="center">
<tr align="left">
<td width="225"><table width="225" height="638" border="0" id="Left">
<tr>
<td align="center" valign="top" background="backgroundtable1.png"><p> </p>
<p><img src="Home.png" width="170" height="30" alt="Home" /></p>
<p><img src="About Us.png" width="170" height="30" alt="About Us" /></p>
<p><img src="Services.png" width="170" height="30" alt="Services" /></p>
<p><img src="Recent Work.png" width="170" height="30" alt="Recent Work" /></p>
<p><img src="My Account.png" width="170" height="30" alt="My Account" /></p>
<p><img src="Contact Us.png" width="170" height="30" alt="Contact Us" /></p>
<p><img src="Promotions.png" width="170" height="30" alt="Promotions" /></p>
<p><img src="Location.png" width="170" height="30" alt="Location" /></p>
<p><img src="Hours.png" width="170" height="150" alt="Hours" /></p></td>
</tr>
</table></td>
<td width="125"> </td>
<td width="850"><table width="850" height="638" border="0" background="backgroundtable2.png" >
<tr>
<td align="center"><html>
<head>
<title></title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<body>
<?php echo $username?></b>
<?php echo $custnum?></b>
<form>
<select name="dropdown" onChange="showUser(this.value)">
<?php query() ;
?>
</select>
<?php close() ?>
</form>
<div id="txtHint"><b>Invoice info will be listed here.</b></div></td>
<p>Logout</p>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
<table width="1050" height="275" border="0" align="center" background="Footer.png">
<tr>
<td><table width="950" border="0" align="center">
<tr>
<td width="256" align="left"><img src="AC Delco Logo.png" width="245" height="47" alt="AC Delco" /></td>
<td width="265" align="center"><img src="ASA Logo.png" width="248" height="115" alt="ASA" /></td>
<td width="141" align="center"><img src="ASE Logo.png" width="112" height="115" alt="ASE" /></td>
<td width="270"><img src="Jasper Logo.png" width="252" height="81" alt="Jasper" /></td>
</tr>
</table></td>
</tr>
</table>
<p> </p>
</body>
</html>
and this is the source code for getuser.php
<?PHP
// Connects to your Database
mysql_connect('localhost', 'root') or die(mysql_error());
mysql_select_db("ServiceHistoryDB") or die(mysql_error());
$q=$_GET["q"];
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM invoices") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 10;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM invoices WHERE CarNum = '".$q."' $max") or die(mysql_error());
//This is where you display your query results
echo "<table border='1'>
<tr>
<th>Date</th>
<th> Service </th>
</tr>";
while($info = mysql_fetch_array( $data_p ))
{ echo "<tr>";
echo "<td>" .date('M d Y', strtotime($info['Date'])) . "</td>";
echo "<td>" . $info['BriefDescription'] . "</td>";
echo "<br>";
echo "</tr>";
}
echo "</table>";
// This shows the user what page they are on, and the total number of pages
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
Try out this useful Jquery Plugin.
Jquery Plugin for data Table

PHP. session_start() [function.session-start]: Cannot send session cookie error

Im having problem in my web where it works perfectly on my local server which is a WAMPSERVER i can run my website completely but after adding to the web server it give me error saying
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/multisl/public_html/udrivetest/index.php:2) in /home/multisl/public_html/udrivetest/init.php on line 4
init.php
<?php
ob_start();
session_start();
mysql_connect("localhost","***","***");
mysql_select_db('****');
include 'function/user.func.php';
include 'function/car.func.php';
include 'function/image.func.php';
?>
header1.php
<head>
<title></title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
.style4 {
font-size: 16px;
font-weight: bold;
}
.style5 {
font-size: 12px
}
.a {
color:#000000;
text-decoration:none;
}
-->
</style>
</head>
<body>
<div style="margin-left:10px;">U Drive.lk</div>
<div class="style5" style="text-align:right; padding:10px;">
Contact Us | Disclaimer | Site Map</div>
</div>
<div>
<div style="background-image:url(images/Car3.png); border:#FFFFFF; border-style:solid; border-width:2px; border-top:none; border-bottom:none; width:920px; height:450px; margin-left:auto; margin-right:auto;" align="center">
<br/>
<img src="images/Car6.png" width="920px" height="135px" />
<div style="margin-top:-22px; height:22px; margin-left:55px;" align="left"><a class="a">Home</a></div>
<div style="margin-top:-22px; height:22px; margin-left:200px;" align="left"><a class="a">Gallery</a></div>
<div style="margin-top:-22px; height:22px; margin-left:350px;" align="left"><a class="a">Leasing</a></div>
<div style="margin-top:-22px; height:22px; margin-left:490px;" align="left"><a class="a">Testimonial</a></div>
<div style="margin-top:-22px; height:22px; margin-left:640px;" align="left"><a class="a">Forum</a></div>
<div style="margin-top:-22px; height:22px; margin-left:790px;" align="left"><a class="a">FAQ</a></div>
<div style="margin-left:auto; margin-right:auto; margin-top:20px;" >
<script type="text/javascript">
AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','920','height','135','src','Flash/Flash Header2','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','Flash/Flash Header2' ); //end AC code
</script><noscript><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="920" height="135">
<param name="movie" value="Flash/Flash Header2.swf" />
<param name="quality" value="high" />
<embed src="Flash/Flash Header2.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="920" height="135"></embed>
</object></noscript>
</div>
<div align="left">
<table width="100%" border="0" style="margin-top:10px;">
<tr>
<td width="20%" valign="top" ><div align="left"><img src="images/Buy_men.png" /> <img src="images/Sell_men.png" /> <img src="images/Rent_men.png" /></div>
<div style="color:#FFFFFF;margin-top:-90px; width:38px; margin-left:10px;">Buy</div>
<div style="color:#FFFFFF;margin-top:-18px; width:38px; margin-left:65px;">Sell</div>
<div style="color:#FFFFFF;margin-top:-20px; width:38px; margin-left:115px;"><a style="color:#FFFFFF;">Rent</a></div></td>
<td width="38%"><fieldset style="background-color:#cccccc">
<span class="style4">Quick Search</span>
</fieldset></td>
<td width="42%"><fieldset style="background-color:#cccccc">
<span class="style4">Login</span>
<?php include_once('login.php'); ?>
</fieldset></td>
</tr>
</table>
</div>
</div>
</div>
<div style="margin-left:auto; margin-right:auto; width:920px;">
login.php
<?php
if (logged_in()) {
echo '<br/> View User Profile <br/>Log Out';
} else {
?>
<form action="" method="post">
<table width="100%" border="0" style="margin-top:-5px;" >
<tr>
<td><div align="left">User Name :</div></td>
<td><input type="text" name="Quick_Name" size="25" /></td>
</tr>
<tr>
<td><div align="left">Password :</div></td>
<td> <input type="text" name="PassWord" size="25" /> <input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
Forgot your password / Register User
<?php
}
if (isset($_POST['Quick_Name'], $_POST['PassWord'])) {
$forgotEmail = $_POST['Quick_Name'];
$login_password = $_POST['PassWord'];
if (empty($forgotEmail) || empty($login_password)) {
$errors[] = 'Email and Password required';
} else {
$login = login($forgotEmail, $login_password);
if ($login === false) {
$errors[] = 'Unable to Log you in';
}
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo $error, '<br/>';
}
} else {
$_SESSION['user_id'] = $login;
header('Location:index.php');
exit();
}
}
?>
index.php
<?php include 'init.php'; include 'widgets/header1.php'; ?>
<div>
</div>
</div>
</body>
</html>
Please Can any one help me out to solve this problem or give me a clue what I am doing here?
Thanks in Advance
In PHP, headers get sent as soon as the page starts to print something - which can occur unintentionally due to whitespace.
Based on your error message (output started at /home/multisl/public_html/udrivetest/index.php:2)
I am guessing this line of index.php:
<?php include 'init.php'; include 'widgets/header1.php'; ?>
appears on line 2 of the file? But you cannot have a line of whitespace above it, it needs to be line 1 since one of the includes is dealing with headers (cookie for session).
Otherwise the blank line 1 is "printing something" - a new line - which sends headers probably before you are intending.
Basically, check all files for not having blank lines above opening tags <?php and don't have blank lines below closing tags ?>.
This is most likely that there exists some whitespace that is sent before the session_start command, try removing the closing PHP tag (?>) and report back the results.
By doing this you remove the possibility of it outputting any invalid whitespace.
There should have some blank space sending back to client. It is a good practise to leave php closing tag ?> if your last line of code is a php code.
Make sure that you dont leave any blank space before and after the php opening tag and php closing tag
You can prevent any output to send to client by using object buffering with ob_start() .
put the ob_start at the very beginning of your php code can save you time.
I would like to consider removing ob_start() from init.php to index.php.
thanks

delete selected images with the help of checkboxes

This is a page where users can edit their uploaded images. There is a checkbox near each image. I want to delete the selected images after user clicks the "delete selected images" button (each checkbox contains the image name as value). How can I do that?
<?php
session_start();
//////////////if user already logged in go to login.php/////////
if (isset($_SESSION['email'] )&& isset($_SESSION['password'] ))
{
} else{header( "Location: login.php" ); }
include('includes/config.php');
if (isset($_POST['esubmit']) ){
$checkbox=$_POST['delete'];
echo $checkbox;
}//main one
if (isset($_POST['esubmit']) ){
} else { $clickeditid=$_GET["id"];
$_SESSION['eid']= $clickeditid ;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="css/css.css" rel="stylesheet" type="text/css" />
<style rel="stylesheet" type="text/css">
input {
border-style: solid;
border-color: #000000;
border-width: 1px;
background-color: #ffffff;
}
</style>
<script src="js/css_browser_selector.js" type="text/javascript"></script>
</head>
<body>
<?php
include('includes/topmenu.php');//top menu
echo '<br />';
include('includes/usermenu.php');///bcoz of this menu error occurs
////////////////////
include('includes/edit_img_menu.php');
?>
<form id="form1" name="form1" method="post" action="editimg.php?id=<?php echo $_SESSION['eid'];?>">
<table align="center" width="70%" cellspacing="0">
<tr>
<td colspan="3" align="center" bgcolor="#FFFFFF"></td>
</tr>
<tr>
<td colspan="3" align="center" bgcolor="#FFFFFF"><?php
$imgcheck=mysql_query("
SELECT *
FROM `images`
WHERE `deal_id` =$_SESSION[eid]
LIMIT 0 , 30
");
$numimgcheck=mysql_num_rows($imgcheck);
if($numimgcheck==0){echo '<span style=color:#ff0000; >No pictures uploaded</span>';}
while ($rowimg2= mysql_fetch_array($imgcheck)){
$imgname=$rowimg2['name'];
{
echo ' <a href="users/'.$_SESSION['userid'].'/images/'.$imgname.'" rel="lightbox[slide]" caption=".">';
}
{ echo '<img src="users/'.$_SESSION['userid'].'/images/thumbs/'.$imgname.'" border="0" />';}
{ echo '</a><input type="checkbox" name="delete" id="delete" value="'.$imgname.'">
';}
}
?></td>
</tr>
<tr>
<td colspan="3" align="center" bgcolor="#FFFFFF"> </td>
</tr>
<tr>
<td colspan="3" align="center" bgcolor="#95F8FD"><input name="esubmit" type="submit" class="red" id="esubmit" value="Delete selected images" /></td>
</tr>
<tr>
<td width="89"> </td>
<td colspan="2"> </td>
</tr>
</table>
</form>
</body>
</html>
You have to create a form to submit the data of the checked checkboxes and treate the submited result with the php code : if you want to put the php code on the same page, you can check if there is any data in the POST vars and create a SQL Query to delete the corresponding pictures.
You can find a very well documented tutorial here : http://sharemyphp.wordpress.com/2009/12/21/ajax-jquery-php-multiple-delete-item-with-check-box/
Regards,
Max
I use the below code to delete images in my admin panel. I saved the file as deletephoto.php. Note that this script works without login. You need to make some changes to fit your use case
<form method="post" action="deletepho.php">
<center>
<input type="submit" value="Delete" name="Delete">
</center>
<?php
\\lets assign the folder name in $title
\\You can assign any name
$title= "test";
\*$directory corresponds to whole path. Edit to your preference. (i assume u store your
images in directory named "images") */
$directory = "$title/images";
\\The array specifies the format of the files
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;
$dir_handle = #opendir($directory) or die("There is an error with your image directory!");
while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
$nomargin='';
if(in_array($ext,$allowed_types))
{
if(($i+1)%4==0)
$nomargin='nomargin';
echo'
<div id="picture">
<img src="'.$directory.'/'.$file.'" width="150" height="150"><br>
Select <input type="checkbox" value="'.$directory.'/'.$file.'" name="imgfile[]">
\* I specified input name as an array . So that we can store in an array and delete it.*/
</div>';
}
$i++;
}
closedir($dir_handle);
\\Now we have the list of images within form elements
?>
</form>
Now here is the actual code to delete the photos. I saved it as deletepho.php.
$file = $_REQUEST['imgfile'];
$num_files=count($file);
for($i=0;$i<$num_files;$i++)
{
unlink ("$file[$i]");
}
echo "Images successfully deleted.Go <a href='deletephoto.php'>back</a>";

Categories