I'm working on a project that is to take a standalone PHP application and move it to WordPress. I've done that and now within WordPress, I am working a particular registration sequence for soccer players to register themselves as players for a team. At a point in the sequence the user uploads an image of themselves. In the code, it is the file 'select-image.php' that is then attempting to retrieve 'upload-image.php' and edit-image.php' but returning error codes 301 an 302 respectively for each.
I've attached a screenshot showing the network activity when upload-image.php and edit-image.php are attempted to be retrieved. Neither resource has been moved permanently. I've also attached a screenhot showing the file is in fact where it is supposed to be on the server.
'select-image.php'
<?php
require_once $_SERVER ['DOCUMENT_ROOT'] . '/required-php-db-connect.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/session-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/ACS-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/org-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/constants-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/cart-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/division-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/team-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/user-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/form-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/image-library.php';
// request page post variables here, ensure that '/libraries/form-library.php' is required above
$return_page = "";
if(!empty($_POST["return_page"])){
$return_page = $_POST["return_page"];
}
// pre-header php functions (such as ACS activities)
$return_page = "";
if(!empty($_POST["return_page"])){
$return_page = $_POST["return_page"];
}
$image_mode = get_session_value('image_mode');
if ($image_mode == "") {
$image_mode = optional_form_item('image_mode');
}
if ($image_mode == 'cart_image_mode'){
$debug_mode = get_session_value('debug_mode');
$debug_string = "";
$transaction_id = get_session_value('transaction_id');
$user_cart = new Cart();
$user_cart->load_cart($transaction_id);
$cart_user_info = new cart_user_info();
$cart_user_info->load_cart_user_info_by_transaction_id($transaction_id);
$user_id = $cart_user_info->get_cart_user_info_user_id();
} else {
$user_id = optional_form_item('user_id');
$team_id = optional_form_item('team_id');
set_session_value('edit_team_id',$team_id);
}
set_session_value('image_edit_user_id', $user_id);
// load jquery libraries
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/jquery-link-library.php';
// load common css libraries
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/css-link-library.php';
$age_level = get_session_value('age_level');
if($age_level == 'youth') {
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/bootstrap-library.php';
}
//get default season
$this_season = new Season();
$season_text = $this_season->display_current_soccer_year();
$error_message = get_session_value('error_message');
set_session_value('error_message', null);
// load page specific css libraries
//require once $_SERVER['document_root'].'/libraries/roster.css';
?>
<!-- all local style references go here. USE SPARINGLY! -->
<style type=text/css>
.inactive_step {
font-weight: normal;
border:thin #000000 solid;
display:inline-block;
}
.active_step {
font-weight: bold;
border: thin #FF0000 solid;
display:inline-block;
}
</style>
</head>
<body id='body'>
<div class="wrapper">
<!-- location of libraries that display data to the page, in the order that the data is displayed -->
<?php if($age_level == 'youth') { require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/new-menu-bar.php'; } else { require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/menu-bar.php'; } ?>
<?php require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/admin-header.php'; ?>
<div class="main_body">
<!-- place all content here -->
<?php
if($age_level == 'youth'){
echo '<div class="jumbotron" style="margin: auto;">';
}
//$image_path = determine_user_image_path($user_id) . "/". get_user_image_file_name($user_id);
$image_path = get_image_database_path_and_name($user_id);
//1:
//place ACS and id user info here
//$user_id = get_cart_session_id();
if (empty($error_text)){
//create page output here
} else {
$display_data = $error_text;
}
?>
<font style="font-size: 18pt; color: red; align: center;"><?php echo $error_message; ?></font>
<table align="center" cellspacing="0" cellpadding ="0" width="1000" style="border: solid black 2px; align-self: center; margin: auto;">
<?php
if ($image_mode == 'cart_image_mode' && $age_level != 'youth'){
echo '<tr style = "border-bottom: solid black 2px;">';
echo '<td colspan="2" width="1000" align="center">';
display_progress(3);
echo "</td> </tr>";
} else if($image_mode == 'cart_image_mode' && $age_level == 'youth') {
echo '<tr>
<td colspan=2>
<h1>Youth Player Registration</h1>
<h3>' . trim($season_text) . '</h3>
</td>
</tr>
<tr>
<td colspan="2" width="970" align="center">';
display_new_progress(5);
echo "</td> </tr>";
}
?>
<tr>
<td valign="top" colspan =2 align= 'center' style = "font-size: 18px;"> <!-- BOTH sides of box -->
<table cellspacing=0 cellpadding=3 border=0 width=1000 align='center' >
<tr>
<td colspan="2" align="left" style="padding-left: 10px;">
<br />
Click <strong>Browse</strong> to upload your picture or take a picture with your cell phone.
<br />
<br />
Please select a picture that clearly shows your face.
<br /><br />
A small camera picture works MUCH better than a facebook picture. You will have a chance to rotate and crop the picture to select just your face. If you cannot get a picture to load correctly, it is probably too large in size or dimension. Use a smaller picture.
<br /> <br />
You MUST click on the box, shown below on the left (Current Picture), at least once for your picture to show up correctly.<br /><br /> Once you find the file or select your picture, click <strong>Upload Picture</strong>.
<br />
<br />
</td>
</tr>
<tr >
<td align="center">
<font style="font-size:16px;">Current Picture</font>
<br>
<img src="<?php echo $image_path; ?>" height="200px;" width="200px;"><br />
<br />
</td>
<td align="center" >
<br />
<form enctype="multipart/form-data" method="post" id="select_image_form" action="/images/upload-image.php" style='font-size: 18px;'>
<div class="row">
<label for="fileToUpload" style='font-size: 18px;'></label>
<button style='height: 70px; width: 250px; font-size:18px;' onclick="document.getElementById('fileToUpload').click();">Click here to select a file or take a pic with your phone</button>
<div style='height: 0px;width: 0px; overflow:hidden;'>
<input type="file" accept="capture=camera" name="fileToUpload" id="fileToUpload" style='font-size: 18px;' onchange="var x = document.getElementById('fileToUpload').value;document.getElementById('file_display').value = x; "/>
</div><br />
File to upload: <input type=text id="file_display" ></input>
<input type="hidden" name = "user_id" value = "<?php echo $user_id ?>">
<input type="hidden" name = "return_page" value = "<?php echo $return_page ?>">
</div>
<div class="row">
<br />
<input type="submit" style='font-size: 18px;' value="Upload This Picture" />
</div>
</form>
<br>
<form action="/images/edit-image-action.php" method="post">
<input type = 'hidden' name = 'image_action' value = 'save_old' />
<input type='hidden' name='old_path' value = '<?php echo $image_path; ?>' />
<input type="submit" style='font-size: 18px;' value="Keep the Current Pic and Skip This Step">
</form>
</td>
</tr>
</table><br />
<!-- Add in javascript based 'press button once' feature -->
</td>
</tr>
</table>
</div> <!-- end of main content area -->
<?php require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/user-footer.php'; ?>
</div> <!-- end of wrapper -->
</body>
</html>
<script type="text/javascript">
$( "#select_image_form" ).validate({
rules: {
fileToUpload: {
required: true,
accept: "image/*"
}
},
messages: {
fileToUpload:{
required: "You must select a picture to continue",
accept: "You must select an Image File."
}
}
});
</script>
'upload-image.php'
<?php
require_once $_SERVER ['DOCUMENT_ROOT'] . '/required-php-db-connect.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/session-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/ACS-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/user-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/cart-library.php';
require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/image-library.php';
$debug_mode = get_session_value('debug_mode');
$debug_string = "";
$debug_string .= "<br/> Debug Mode: $debug_mode";
$redirect_url = "/images/edit-image.php";
//set memory limit to accomodate uploading of 8MB images -TF
ini_set("memory_limit", "512M");
//$user_id = get_cart_session_id();
$image_mode = get_session_value('image_mode');
if ($image_mode == 'admin_image_mode'){
$user_id = get_session_value('image_edit_user_id');
}else {
$transaction_id = get_session_value('transaction_id');
$cart_user_info = new Cart_user_info();
$cart_user_info->load_cart_user_info_by_transaction_id($transaction_id);
$user_id = $cart_user_info->get_cart_user_info_user_id();
}
if ($_FILES['fileToUpload']['error'] > 0) {
$debug_string .= UploadException($_FILES['fileToUpload']['error']);
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strtolower(strrchr($_FILES['fileToUpload']['name'], "."));
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
// we are renaming the file so we can upload files with the same name
// we simply put current timestamp in front of the file name
$newName = time() . '_' . $_FILES['fileToUpload']['name'];
$destination = '/images/temp/' . $newName;
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], 'c:/inetpub/wwwroot'.$destination)) {
$manipulator = new ImageManipulator();
$manipulator->setImageFile($_SERVER[ 'DOCUMENT_ROOT' ] . $destination);
$manipulator->rotate('360');
// rotate 360 degrees
//$newImage = rotateImage($image, 360);
//$manipulator->setImageResource($newImage);
$manipulator->save($_SERVER[ 'DOCUMENT_ROOT' ] . $destination);
//redirect_post($redirect_url, 'destination', $destination);
set_session_value("destination",$destination);
//header('Location: ' . $redirect_url);
}
} else {
$debug_string .= " <br/>You must upload an image...<br/> If the file you attempted to upload was an image, it may not be compatible with this system. Please try again with another file.";
}
}
?>
<html>
<head>
<title>save a picture</title>
<!-- all stylesheets go here -->
<link rel="stylesheet" href="/CSS/login.css" type="text/css" />
<link rel="stylesheet" href="/CSS/menu.css" type="text/css" />
<link rel="stylesheet" href="/CSS/common.css" type="text/css" />
<link rel="stylesheet" href="/images/demos.css" type="text/css" />
<link rel="stylesheet" href="/images/jquery.Jcrop.css" type="text/css" />
</head>
<body style="text-align:center;">
<div class="wrapper">
<!-- location of libraries that display data to the page, in the order that the data is displayed -->
<?php require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/logo-header.php'; ?>
<?php require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/menu-bar.php'; ?>
<?php require_once $_SERVER ['DOCUMENT_ROOT'] . '/libraries/admin-header.php'; ?>
<div class="main_body">
<!-- place all content here -->
<?php
$next_page = $redirect_url;
$debug_string .= "<br/> Next page: $next_page";
$debug_string .= "<br/> Debug Mode: $debug_mode";
echo $debug_string;
upload_image_button($user_id);
header("location: $next_page");
continue_or_debug($next_page, $debug_mode);
?>
</div>
</div>
</body>
</html>
If you need 'edit-image.php' I can post that.
I don't understand why the error is saying the resource 'upload-image.php' has been permenently moved when it is very clearly sitting in the directory it needs to be in?
What gives?
Thanks,
CM
Network activity screenshot
screenshot of resource on server
Related
I am trying to delete files inside folder, using delete_file.php, which is action file offcourse. It can recieve data as $_POST['filename1'] only, but for every foreach() iteration , this value is getting over-written. Any suggestions, what else can SOLVE this subject? Thanks in Advance.
Problem:
delete_file.php is catching filename1 as $_POST['filename1']
But with each foreach iteration, filename1 is getting over-written.
And delete_file.php, is deleting LAST ENTRY ONLY, EVERY TIME.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--[if lte IE 8]>
<script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css"/>
<!--[if lte IE 8]>
<link rel="stylesheet" href="assets/css/ie8.css"/><![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="assets/css/ie9.css"/><![endif]-->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.leanModal.min.js"></script>
</head>
<body class="no-sidebar">
<table border="1px solid" style="text-align:center; margin-left:auto; margin-right:auto; width:900px">
<tr>
<th><strong>S.No</strong></th>
<th><strong>Image-Name</strong></th>
<th><strong>Image/Logo</strong></th>
<th><strong>Image Size</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
$dirname = "../assets/img/logos/";
$images = glob($dirname . "*.{jpg,png,gif,tiff,jpeg,JPG}", GLOB_BRACE);
$sn = 1;
foreach ($images as $image) {
$imageName = str_replace("../assets/img/logos/", "", $image);
$variable_id = str_replace(".", "_", $imageName);
?>
<!---///////////////////// IMAGE-<?= $sn++ ?> STARTS //////////////////////----------->
<tr>
<td><?= $sn++ ?></td>
<td><?php echo $imageName; ?></td>
<td><img src="<?php echo $image; ?>" width="150px" height="100px"/></td>
<td><?php echo filesize($image) / 1000 . " KB"; ?></td>
<!-------
<td>
<a id="delete" href="delete_plogos.php?filename=<?//=$imageName ?>" style="color:#D00A0D"><strong>Delete</strong></a>
</td>
-------->
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="#<?= $variable_id ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
</tr>
<!----------------------popup for delete----------------------->
<div id="<?= $variable_id ?>" class="popupContainer" style="display:none;">
<header class="popupHeader" style="background: #F4F4F2;
position: relative;
padding: 10px 20px;
border-bottom: 1px solid #DDD;
font-weight: bold; height: 55px;">
<span class="header_title">Delete</span>
<span class="modal_close"><i class="fa fa-times"></i></span>
</header>
<section class="popupBody">
<!-- Register Form -->
<div class="deleteplogo_<?= $variable_id ?>">
<form id="newpageform_<?= $variable_id ?>" name="newpageform_<?= $variable_id ?>" method="post">
<input name="filename_<?= $variable_id ?>" id="filename_<?= $variable_id ?>" type="text" style="display:none"
value="<?= $imageName ?>"/>
<p><strong><?= $imageName ?> - Image will be deleted Permanently. <br/>Proceed
?</strong></p>
<br/>
<div class="action_btns">
<div class="one_half" style="float:none;">
<a id="ajax-submit_<?= $variable_id ?>" class="btn btn_red" style="cursor: pointer"
>Yes! I
Agree
.Delete</a></div>
</div>
</form>
</div><!--------delete_plogo----------->
</section>
</div> <!----------------------#modal ENDS----------------------->
<!---------------- delete image : pop up ------------------------------>
<script type="text/javascript">
var magica = "<?php echo $variable_id; ?>";
$('#modaltrigger_' + magica).leanModal({top: 200, overlay: 0.6, closeButton: ".modal_close"});
$(function () {
$('#modaltrigger_' + magica).click(function () {
$('.deleteplogo_' + magica).show();
return false;
});
})
/////// 3.) AJAX-FORM SUBMIT - + then reload
$("#ajax-submit_"+magica).click(function () {
var filename = $("#filename_"+magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_plogos_action.php", {filename1: filename}, function (data) {
$("span.modal_close > i").trigger("click"); // to auto-close leanModal window
alert(data).fadeOut("slow");
window.location=trustedpartners_listviewdel_logos.php;
//close_modal("modal");
});
}
});
</script>
<!---///////////////////// IMAGE-ENDS //////////////////////----------->
<?php
}
?>
</table>
</body>
</html>
You can try something like removing the php loop:
<script type = "text/javascript" >
$(function() {
$('div[id^="modaltrigger_"]').leanModal({
top: 200,
overlay: 0.6,
closeButton: ".modal_close"
});
$('div[id^="modaltrigger_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
$('.deleteplogo_' + magica).show();
return false;
});
})
$('div[id^="ajax-submit_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
var filename = $("#filename_" + magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_file.php", {
filename1: filename
}, function(data) {
$("span.modal_close > i").trigger("click");
//alert(data).fadeOut("slow"); damn you can't fade out a alert box :))
window.location = mypage.php;
} // else ends here
});
}); < /script>
A better solution will be to replace the ids with a class and append a data-attribute to the elements iwth the value of magica
Deleted all AJAX-JQUERY code & used :
file1.php
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="delete.php?id=<?php echo $imageName; ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
delete.php
<?php
$filePath = "D:/folder/".$_GET['id'];
if(is_file($filePath)){
#unlink($filePath);
echo ('<strong>SUCCESS! Deleted: <span style="color:red">'. $_GET['id']. '</span>, file from Directory</strong>');
}
else if(!unlink($filePath)){
echo ("Error deleting file : ". $_GET['id']. " Already deleted OR doesn't EXIST");
}
?>
Worked like Charm ! Thanks !
I want to pass a variable to next page but i doesn't seem to work as expected. I have done samething on a different page but now it dosen't work.
This is the metod im using to pass the variables (email.php):
<div class='alternativ'> <td width="50%" style=" padding:5px;"> <form method='GET' action='excelimport.php'> <input type='hidden' name='pidnew3' value='$pidnew2'> <input type="submit" name="submit"> </form></td> </div>
and in excelimport.php i have this:$pidnew4 = $_POST['pidnew3'];
Im getting 2 error in excelimport.php:
Notice: Undefined index: pidnew3 in D:\home\site\wwwroot\devlopment\excelimport.php on line 77
its reffering to this: $pidnew4 = $_POST['pidnew3'];
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\home\site\wwwroot\devlopment\excelimport.php on line 102
and this is reffering to this: $recResult = mysql_fetch_array($sql);
I have this php (email.php) page that i want to pass to another.:
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions2.php';
include_once 'includes/config.php';
error_reporting(-1); ini_set( 'display_errors', 1 );
//Start av sessions
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'Inloggad';
} else {
$logged = 'utloggad';
}
$uploadedStatus = 0;
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
}
$storagename = "discussdesk.xlsx";
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename);
$uploadedStatus = 1;
}
} else {
echo "Ingen fil vald <br />";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Kandidater</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.709">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="shortcut icon" href="logo/wfmini.png">
<script type="text/javascript" language="javascript">
function checkedbox(element) {
var checkboxes = document.getElementsByTagName('input');
if (element.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
</script>
<script src="js/tinymce/js/tinymce/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
</head>
<body class="dashboardadmin">
<ss="container-fluid" style="width:50%;">
<br>
<center><h3>Skicka email till kandidater</h3></center>
<br>
<p>Välj kandidater</p>
<form method="post" action="">
<?php
$pidnew2 = $_GET['pidnew'];
// Retrieve Email from Database
$getemail = mysql_query("SELECT * FROM Email_Users WHERE pid='".$pidnew2."'");
if (!$getemail) die('MySQL Error: ' . mysql_error());
echo '<table class="table table-bordered">';
echo "<thead>
<tr>
<th><input type='checkbox' onchange='checkedbox(this)' name='chk'/></th>
<th>Förnamn</th>
<th>Efternamn</th>
<th>Email</th>
</tr>
</thead>";
if (mysql_num_rows($getemail) == 0) {
echo "<tbody><tr><td colspan='3'>No Data Avaialble</td></tr></tbody>";
}
while ($row = mysql_fetch_assoc($getemail)) {
echo "<tbody><tr><td><input value='".$row['Email']."' type='checkbox' name='check[]'/></td>";
echo "<td >".$row['fornamn']."</td>";
echo "<td >".$row['efternamn']."</td>";
echo "<td >".$row['Email']."</td></tr></tbody>";
}
echo "</table>";
?>
</form>
</center>
<br>
</div>
<table width="600" style="margin:115px auto; background:#f8f8f8; border:1px solid #eee; padding:10px;">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<tr><td colspan="2" style="font:bold 15px arial; text-align:center; padding:0 0 5px 0;">Ladda upp kandidater</td></tr>
<tr>
<td width="50%" style="font:bold 12px tahoma, arial, sans-serif; text-align:right; border-bottom:1px solid #eee; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Välj fil</td>
<td width="50%" style="border-bottom:1px solid #eee; padding:5px;"><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td style="font:bold 12px tahoma, arial, sans-serif; text-align:right; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Send</td>
<div class='alternativ'>
<td width="50%" style=" padding:5px;">
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form></td>
</div>
</tr>
</table>
<?php if($uploadedStatus==1){
header('Location: excelimport.php');
}?>
</form>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-38304687-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
And here's the other one (excelimport.php):
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions2.php';
include_once 'includes/config.php';
error_reporting(-1); ini_set( 'display_errors', 1 );
//Start av sessions
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'Inloggad';
} else {
$logged = 'utloggad';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="shortcut icon" href="logo/wfmini.png">
</head>
<body class="dashboardadmin">
<div class="innehall">
</div>
<p>
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
$pidnew4 = $_POST['pidnew3'];
$inputFileName = 'discussdesk.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$userfName = trim($allDataInSheet[$i]["A"]);
$usereName = trim($allDataInSheet[$i]["B"]);
$userMobile = trim($allDataInSheet[$i]["C"]);
$query = "SELECT name FROM Email_Users WHERE fornamn = '".$userfName."' and efternamn '".$usereName."' and email = '".$userMobile."' and pid = '".$pidnew4."'";
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$existName = $recResult["fornamn"];
if($existName=="") {
$insertTable= mysql_query("insert into Email_Users (fornamn, efternamn, email, pid) values('".$userfName."', '".$usereName."', '".$userMobile."', '".$pidnew4."');");
$msg = 'Record has been added. <div style="Padding:20px 0 0 0;">Go Back to tutorial</div>';
} else {
$msg = 'Record already exist. <div style="Padding:20px 0 0 0;">Go Back to tutorial</div>';
}
}
echo "<div style='font: bold 18px arial,verdana;padding: 45px 0 0 500px;'>".$msg."</div>";
?>
</body>
</html>
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form>
In this form, you mentioned GET method and you are passing variable using GET method in your another page.
You can not get pidnew3 variable to another page because you are using POST method to get pidnew3 variable.
You just need to change the below line from
$pidnew4 = $_POST['pidnew3'];
to
$pidnew4 = $_GET['pidnew3'];
I just realised what can be wrong, you didn't display the $pidnew2 value here
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form>
You should replace that block with
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='<?php echo $pidnew2; ?>'>
<input type="submit" name="submit">
</form>
Then you get the value of the variable $pidnew2 and not the string '$pidnew2'
You should change the method in the form by POST, as you are trying to get a variable passed through 'GET'. Or as below you can get the variable using the 'GET' method.
$pidnew4 = $_GET['pidnew3'];
i am new to php to developing simple content management system i have a field like menu, position, visible, img_des, content, information_id .. it almost all working correctly now i need to insert image field to that . i have a separate file for forms and new page creation
now the following code
if (isset($_POST['submit'])) {
$errors = array();
// clean up data before putting in the database
$information_id = mysql_prep($_GET['info']);
$menu = trim(mysql_prep($_POST['menu'])); // cut out whitespace for menu
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$image = mysql_prep($_POST['image']);
$img_des = mysql_prep($_POST['img_des']);
$content = mysql_prep($_POST['content']);
if(empty($errors)){
$query = "INSERT INTO pages (
menu, position, visible, img_des, content, information_id
) VALUES (
'{$menu}', {$position}, {$visible},'{$img_des}', '{$content}', {$information_id}
)";
if ($result = mysql_query($query, $connection)) {
$message = "The new page was created successfully";
$new_page_id = mysql_insert_id();
redirect_to("content.php?page={$new_page_id}");
} else {
$message = "The page failed to create";
}
?>
before img_des i want to insert image. what type i have i have to use and what code i have to put to insert and retrieve image.
You shouldn't be storing images in the database. Save the image on the server and save a link to the files location in the database.
see this question for more information: What should I use to save a image in database
try this code.
<?php
$images_arr = array();
//This is the directory where images will be saved
$target_dir = "uploads/";
$target = $target_dir.$_FILES['photo']['name'];
//$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysql_connect("Localhost", "remote", "remote123") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO dbProfiles (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)){
//Tells you if its all ok
echo "The file ". $target_dir.$_FILES['photo']['name']. " has been uploaded, and your information has been added to the directory";
$images_arr[] = $target;
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" href="http://www.thesoftwareguy.in/favicon.ico" type="image/x-icon" />
<!--iOS/android/handheld specific -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Upload multiple images create thumbnails and save path to database with php and mysql">
<meta name="keywords" content="php, mysql, thumbnail,upload image, check mime type">
<meta name="author" content="Shahrukh Khan">
<title>Upload multiple images create thumbnails and save path to database with php and mysql </title>
<link rel="stylesheet" href="style.css" type="text/css" />
<style>
.files{height: 30px; margin: 10px 10px 0 0;width: 250px; }
.add{ font-size: 14px; color: #EB028F; border: none; }
.rem a{ font-size: 14px; color: #f00; border: none; }
.submit{width: 110px; height: 30px; background: #6D37B0; color: #fff;text-align: center;}
</style>
<script src="jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
$(".add").click(function() {
$('<div><input class="files" name="user_files[]" type="file" ><span class="rem" ><a href="javascript:void(0);" >Remove</span></div>').appendTo(".contents");
});
$('.contents').on('click', '.rem', function() {
$(this).parent("div").remove();
});
});
</script>
</head>
<body>
<form name="f1" action="index.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="image_form_submit" value="1"/>
<div id="container">
<div id="body">
<div class="mainTitle" >Upload multiple images create thumbnails and save path to database with php and mysql</div>
<div class="height20"></div>
<article>
<div class="height20"></div>
<div style="width: 380px; margin: 0 auto;">
<h3 style="text-align: center;">Image will be resized to 100px X 100px </h3>
<p>Please Enter the Band Members Name.</p>
<p> Band Member or Affiliates Name:</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</div>
<table class="bordered">
<?php
// fetch all records
$sql = "SELECT * FROM dbProfiles WHERE 1 "; ?>
<?php
$sql="SELECT * FROM dbProfiles";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<tr>
<td><p><?php echo $row['nameMember'] ?>"</p></td>
<td><img src="uploads/<?php echo $row['photo'] ?>" width="200px" height="200px;"/><p><?php echo $row['nameMember'] ?>"</p></td>
</tr>
<?php
}
?>
</table>
</article>
</div>
</div>
<div class="height10"></div>
</form>
</body>
</html>
<?php
function errorMessage($str) {
return '<div style="width:50%; margin:0 auto; border:2px solid #F00;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
}
function successMessage($str) {
return '<div style="width:50%; margin:0 auto; border:2px solid #06C;padding:2px; color:#000; margin-top:10px; text-align:center;">' . $str . '</div>';
}
?>
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.
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>";