Good day folks,
Please I'm trying to implement something simple but I'm not finding the proper solution in PHP. I would like to ask for some advises, please.
I have one list of servers in the Array/Vector called $lines, now I would like to SELECT each server name in a MySQL DB in order to collect additional infos.
Could you please give me ideas regarding how to do a loop from the server names in, to SELECT / QUERY each one ?
Thanks!!
<html>
<head>
</head>
<body>
<form name="form1" method="post">
<textarea rows="10" name="servers[]" cols="50" ></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxx","userxxxx","xxxxxxxx","xxxxxxx");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
foreach($lines as $servers)
{
echo ($servers."<br>");
}
}
else
{
echo 'Please write something';
}
}
?>
</body>
</html>
I've got the result as I needed, I hope it can help:
<body>
<form name="form1" method="post">
<textarea rows="1000" name="servers[]" cols="100" style="width:300px;height:300px;"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxxx:portxx","userx","passxx","msdb");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
//BREAKING IN AN ARRAY
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
//foreach($lines as $servers)
//{
//echo ($servers."<br>");
//}
//REMOVING BLANK SPACES:
function trim_value(&$value)
{
$value = trim($value);
}
//ADDING QUOTES BETWEEN THE VALUES
function add_quotes($str) {
return sprintf("'%s'", $str);
}
//REMOVING BLANK LINES
array_walk($lines, 'trim_value');
$VCSAC2 = "VCSAC2";
$LPAR = "LPAR";
$HOSTF = "HOSTF";
$CLASSG = "CLASSG";
$IP = "IP";
$STATUS = "STATUS";
//USING IMPLODE
//$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', $lines).")");
$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', array_map('add_quotes',$lines)).")");
//USED TO CHECK SQL SINTAX
//echo $sql;
$result=mysqli_query($con,$sql);
}
else
{
echo 'Please write something';
}
}
?>
<table id="demo1" cellpadding="0" cellspacing="0" style="width:100%" style="font-size:13px">
<thead>
<tr>
<th align=left>HostName</th>
<th align=left>VCS</th>
<th align=left>LPAR</th>
<th align=left>IP</th>
<th align=left>Class</th>
</tr>
</thead>
<?php while($dado = mysqli_fetch_array($result)) {?>
<tbody>
<tr>
<td align=left style="font-size:14px"><?php echo $dado[$HOSTF]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$VCSAC2]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$LPAR]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$IP]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$CLASSG]; ?></td>
</tr>
</tbody>
<?php } ?>
</table> <br><br>
</body>
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>
I've created a form that is supposed to update table contents in input boxes, when the content of the input boxes are changed and submitted the database is supposed to update.
This is my first page:
<body>
<form action="qa1.php" method="post">
<ul>
<li><a class="active" href="df1.php">Disease</a></li>
<li><a href="drug.php" >Drug</a></li>
<li>Interaction</li>
Alternate Drug
</ul>
<?php
$query = "SELECT * FROM disease;";
$result = mysqli_query($dp, $query);
echo "<table border=5>
<tr>
<th>Select</th>
<th>Edit</th>
<th>Disease ID</th>
<th>Disease</th>
<th>Sub Disease</th>
<th>Associated Disease</th>
<th>Ethinicity</th>
<th>Source</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='select' value=".$row['Disease_id']."/> </td>";
echo "<td>".$row{'Disease_id'}."</td>";
echo "<td><a href='edit.php?Disease_id=".$row['Disease_id']."'>edit</a></td>";
echo "<td>".$row{'Disease'}."</td>";
echo "<td>".$row{'SubDisease'}."</td>";
echo "<td>".$row{'Associated_Disease'}."</td>";
echo "<td>".$row{'Ethinicity'}."</td>";
echo "<td>".$row{'Source'}."</td>";
echo "</tr>";}
echo "</table>";
$selectedRow=$_POST['select'];
?>
<div>
<table border="0" align="center" style="border-spacing: 40px 30px;">
<caption><strong>QualityAnalysis:</br></br></strong></caption></br></br>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="4" WIDTH="40%">
</br><div><center>
<button style="color: red">Add</button>
<input type = 'submit' value = 'Delete' name = 'submitdelete' button style="color: red"></button>
<input type = 'submit' value = 'Update' name = 'submitupdate'>
</center></div> </TABLE>
</body>
</html>
This is my editing page: edit.php
<body>
<form action="edit.php" method="post">
<ul>
<li><a class="active" href="df1.php">Disease</a></li>
<li><a href="drug.php" >Drug</a></li>
<li>Interaction</li>
Alternate Drug
</ul>
<div>
<?php
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
if(isset($_GET['Disease_id']))
{
if(isset($_POST['Update']))
{
$id=$_GET['Disease_id'];
$name=$_POST['Ethinicity'];
$query3=mysqli_query("update disease set Ethinicity='$name', where Disease_id='$id'");
if($query3)
{
header('location:qa1.php');
}
}
$query1=mysqli_query("select * from disease where Disease_id='$id'");
$query2=mysqli_fetch_array($query1);
?>
<table border="2" align="center" style="border-spacing: 40px 30px;">
<caption><strong>Edit</br></br></strong></caption></br></br>
<tr>
<td>Ethinicity<input type="text" list="Ethinicity" name="Ethinicity" value="<?php echo $row['Ethinicity'];?>"/>
<input type="hidden" name="Disease_id" value="<?php echo $row['Disease_id']; ?>"/>
<input type="submit" name="Update" value ="Update">
<?php
}
?>
</center></div></div>
</form>
But Data is not getting updated in the database. Can anyone help me with this?
Firstly, mysqli_query requires the connection parameter.
Secondly, there's a syntax error with your UPDATE query, there isn't a need for a comma.
So, it should be:
$query3=mysqli_query($conn, "update disease set Ethinicity='$name' where Disease_id='$id'");
$query1=mysqli_query($conn, "select * from disease where Disease_id='$id'");
Also, if($query3) won't check if the row is successfully inserted, use mysqli_affected_rows instead.
my home.php is
required("conn.php");
<html>
<body>
<form action="like.php" name="art" method="post">
<?php
//$email=$data['email'];
?>
<table align="center" border="2">
<tr><th colspan="4"><h2 align="center">Articals</h2></th></tr>
<tr> <th>Name</th><th>Artical</th><th>Status</th><th colspan="2">option</th>
</tr>
<?php
$r = mysql_query("select * from ar ");
while($ro=mysql_fetch_array($r)){
?>
<tr>
<td> <?php echo $ro["fname"]?></td>
<td><textarea rows="2" cols="25"><?php echo $ro["post"]?></textarea></td>
<td><?php echo $ro["status"]?></td>
<td><a name="like" href="like.php?id=<?php echo $ro['id']?>"> like</a></td>
<!--<td><a href="delart.php?id=<?php //echo $row["id"]?>" >Delete</a></td>
<td>Upadate</td>
-->
</tr>
<?php
}
mysql_close($con);
?>
</form>
</table>
</body>
</html>
and like.php is
<?php
session_start();
if(!isset($_SESSION['user']))
{
header('Location:index.php');
}
require("conn.php");
$id=$_GET['id'];
mysql_query("insert into `like` ar where id='$id'");
?>
when i am click on link like so the error "The requested URL /25-8/like.php was not found on this server." is come pls help i am new to php
i want there to count the no of like and on click on that like button it automatically change to unlike
YOu Must put the home.php and like.php in the same directory?
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
<?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.