I want to store the filename in session for storing file name in a database on another button click. But my session return empty - php

while using dropzone file upload plug in in php session is not assigning file string.
actually i want to store multipe file in session in array form and upload the file in folder after that another form action fetch file in variable and store it to database with all form data.
but i get allways session blank.
upload.php
<?php
session_start();
if (!isset($_SESSION['fileupload']) && empty($_SESSION['fileupload'])) {
$_SESSION['fileupload'] = '';
}
if (isset($_FILES['blog_Image']) && !empty($_FILES['blog_Image'])) {
// echo "<pre>";
// print_r($_FILES['blog_Image']);
$_SESSION['fileupload'] == "uploaded";
}
if (isset($_POST['btnsavedata'])) {
echo $_SESSION['fileupload'];
}
?>
output:
its return empty.
i want to store file name in session and store in database on another page.. or button click...

Related

How to enable Delete button in PHP when Admin is logged in but not for Viewer (normal user)?

I am working on a simple report viewer, where PDF's stored in a folder are displayed in the table and can be opened when user clicks on it. That thing is working fine. I also have a Upload functionality which lets the user upload the files to the respective folders and later can be displayed in the table. I also can delete the files by showing a delete link right in front of the file name in table.
At first, I wanted there to be only one user which could do all the things. Now, we want the Delete link and Upload menu to be displayed only when the username is 'Admin'. We do not want to use any databases, because data is not so classified and we are fine using a script based solution. However, I can't figure out how to enable Delete and Upload only for Admin. The code I am using is attached below:
From login.php
<?php session_start(); /* Starts the session */
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('reader' => '123456','admin' => '654321','username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
?>
Before every page, we insert this code:
<?php session_start(); /* Starts the session */
if(!isset($_SESSION['UserData']['Username'])){
header("location:login.php");
exit;
}
?>
And this is what we are doing inside the table to display list of files and a link to delete them:
foreach($files as $file)
{
if(isset($_GET['delete']))
{
unlink($file);
break;
//a better approach for deletion will be appreciated
}
echo'<tr><td>'.returnFile($file).'</td>
<td>Download</td>
<td>Delete</td>
</tr>';
}
It worked when I changed $_SESSION['UserData']['Username']=$logins[$Username]; into $_SESSION['UserData']['Username']=$Username; in login.php.
Finally adding if($_SESSION['UserData']['Username'] == 'admin') before any code I wanted to appear only when Admin is signed in. Thank you everyone.

File session: is it always generated?

Does Php always create a session file as soon as session_start() is called, even though there's nothing to keep track of (= no variable written in $_SESSION[])? If so, why?
Default PHP file-based sessions encode the session ID into the session file's filename. Since that's the only place the ID is kept normally, SOMETHING has to be kept to store the id. That means you'll get a file created, even if nothing is EVER written to $_SESSION.
In PHP-like pseudo code, basically this is occuring:
function session_start() {
if (isset($_COOKIE[ini_get('session.name')])) {
// session ID was sent from client, get it
$id = $_COOKIE[ini_get('session.name')];
} else {
// no session ID received, generate one
$id = generate_new_id();
setcookie(ini_get('session.name'), $id, ......);
}
$session_file = ini_get('session.save_path') . '/sess_' . $id;
if (file_exists($session_file)) {
// found a session file, load it
$raw_data = file_get_contents($session_file);
$_SESSION = unserialize($raw_data);
} else {
// brand new session, create file and initialize empty session
file_put_contents($session_file, serialize(array());
$_SESSION = array();
}
// lock the session file to prevent parallel overwrites.
flock($session_file);
}

Handle tmp file in form upload and pass the file to other form before uploaded

I need help badly , can't fix it to working like i want..!
I have two forms , one is contact form , and the other is image upload inside the contact form,the forms using AJAX for proccsesing.
I dont want to move_upload_file unless the all form(contact)is submited. so so far its all working, exept when i try to pass the file over the contact form and use#move_upload_file it wont move the file to the server.
I using this way to transfer the file and when i am doing var_dump its working perfect :
if ($proc == "question")
{
// Handle some normal form 'contact us'.
// ... Some proccses code when submited via ajax ...
$fileElementName = 'ImageBrowse';
//This session coming from other proccses form down if isset.
if(isset($_SESSION['imgfilename']) && !empty($_SESSION['imgfilename'])){
//Then i handle it with list to make the rest of the proccses.
list($uploadFilename,$_FILES['ImageBrowse']) = $_SESSION['imgfilename'];
//unset session for security.
unset($_SESSION['imgfilename']);
}
var_dump($_FILES['ImageBrowse']);
// will print the file array perfect.
//Trying now to move_uploaded_File
if(#move_uploaded_file($_FILES['ImageBrowse']['tmp_name'],$uploadsDirectory.$uploadFilename)){
echo 'Uploaded!';
}else{
echo 'Not Uploaded';
}
// and here is the problem , it wont move uploaded file , even if there is array of the file..
}
else if ($proc == "sendQuestionUploadImg")
{
// Handle img upload via ajax.
$fileElementName = 'ImageBrowse';
$uploadsDirectory = '../uploads/';
$allowedTypes = array
(
'image/jpeg',
'image/jpg',
'image/pjpeg',
'image/pjpeg',
'image/png',
'application/x-rar-compressed'
);
// ... Some more proccses code when submited via ajax ...
// In the end if goes well...
// I want to pass the file array to the other if above.
if (isset($msg) && !empty($msg))
{
// I insert the file array into session for take the rest of the proccses in above form if.
$_SESSION['imgfilename'] = array($uploadFilename,$_FILES['ImageBrowse']);
//If i use here , it will work.
if(#move_uploaded_file($_FILES['ImageBrowse']['tmp_name'],$uploadsDirectory.$uploadFilename)){
echo 'Uploaded!';
}else{
echo 'Not Uploaded';
}
//
}
else
{
#unlink($_FILES[$fileElementName]);
}
As you see i pass the whole file array into session, and call it above in the other if proccses for more proccses, when i using #move_upload_file inside the $proc == "sendQuestionUploadImg" it will work perfect and will upload the file , but if i try to use #move_upload_file inside the other if it won't any one know why?
To clear one thing out: if you have a $_FILES array without error, the file is uploaded already and stored in a temporary folder on the server ini_get('upload_tmp_dir');
The function move_uploaded_file() just moves the temporary file to a location of your choice safely.
http://php.net/manual/en/function.move-uploaded-file.php
If this fails, your php process most likely is not able to write to the destination folder.
To debug this
enable error reporting:
ini_set( 'error_reporting', E_ALL );
remove the error suppressing # in front of your move_uploaded_file function
use a tool like Firebug to see the Ajax response
http://ajaxian.com/archives/ajax-debugging-with-firebug

Session persistence with Zend framework

I'm having problems with storing variables in a $_SESSION variable.
I'm using Zend framework and building a 3 step application form. Now, when the first step is done, I store the data in MySQL database, and store the returned insert id in a session variable. Then I forward the page to another controller (step 2). When I forward the request, everything works fine and I can read the id from the session variable. But when I submit the second form (which has the same controller of step 2 as an action) the session is lost. I try to var_dump it, and it returns NULL.
Here's the code:
public function organizationAction()
{
$this->view->vals="";
$form=$this->getOrganizationForm();
$this->aplid=$_SESSION['appid'];
var_dump($_SESSION);
$firsttime=$this->getRequest()->getParam('firsttime',0);
//if(null==$this->aplid) $this->_forward('index','index');
if ($this->getRequest()->isPost() && $firsttime==0) {
if (!$form->isValid($_POST)) {
// Failed validation; redisplay form
$this->view->form = $form;
return false;
}
var_dump($_SESSION);
$values = $form->getValues();
$db=new Util_Database();
if($db->insertOrganization($values,$this->aplid))
$this->_forward('final');
else echo "An error occured while attempting to submit data. Please try agian";
}
$this->view->form=$form;
}
What is the problem here? I tried storing the session_id in the form, and then setting it before session_start(), but it starts a whole new session. Please help!
I'm not sure if this is going to help, because I'm not sure if something else might be happening in step 2. But here goes.
You might be inadvertently overwriting your session data. Here is what I came up with that might help give some ideas.
public function organizationAction() {
$this->view->vals = "";
$form = $this->getOrganizationForm();
$db = new Util_Database();
//This will only submit the form if the is post and firsttime == 0
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('firsttime') == 0) {
//if form is valid set session and save to db
if ($form->isValid($this->getRequest()->getPost())) {
//We only want to initialize the session this time, if we do it
//on the next pass we may overwrite the information.
//initialize session namespace
$session = new Zend_Session_Namespace('application');
//get values from form, validated and filtered
$values = $form->getValues();
//assign form value appid to session namespace
$session->appid = $form->getValue('appid');
//assign session variable appid to property aplid
$this->aplid = $session->appid;
if ($db->insertOrganization($values, $this->aplid))
$this->_forward('final');
else
echo "An error occured while attempting to submit data. Please try agian";
} else {
//if form is not vaild populate form for resubmission
//validation errors will display of form page
$form->populate($this->getRequest()->getPost());
}
}
//if not post display form
$this->view->form = $form;
}
P.S. If your gonna go ZF...Go ZF! :)

Session doesn't get cleared

I have a google chrome extension talking to a PHP script via XHR. I have a flag in the PHP script to check if a button is clicked in a popup if proper POST data is sent. If this button is clicked, the current session needs to be destroyed and when new data is entered by clicking the add button it shouldn't be appending data to an existing session but start a new one instead. It's currently just re-appending the data to the array. It's as if the clear session command is being ignored, however the IF statement is being called correctly to the console. How do I get the clear session statement to clear the session?
PHP script:
<?php $json = $_POST['data'];
if($json['button'] == "clear"){
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}
if (!isset ($_COOKIE[ini_get($_SESSION['data'])])) {
session_start();
}
if(!isset($_SESSION['data'])){
$_SESSION['data'] = $json;
} elseif (isset($_SESSION['data'])){
array_push($_SESSION['data'], $json);
}
print_r($_SESSION['data']);
?>
You must call session_start() first:
if($json['button'] == "clear")
{
session_start(); // <-- first
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}

Categories