When including session I can not use $_FILES - javascript

I am uploading a csv file and sending it to page to process using the js fetch api. I have session included using my init file and all works well accept for the page that should process to file info. Without including the session it works fine and I can process the file, when including it, I can see al the session info, but $_FILES just stops working, I can't see any of the info for some reason.
I really hope this is something stupid
Some code if needed
The init file
<?php
//define Site Root and Includes Path
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null : define('SITE_ROOT', __DIR__ . DS );
defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', SITE_ROOT);
//get class files
include(INCLUDES_PATH.DS."Session.php");
require_once(INCLUDES_PATH.DS."functions.php");
require_once(INCLUDES_PATH.DS."DB.php");
require_once(INCLUDES_PATH.DS."Validation.php");
require_once(INCLUDES_PATH.DS."User.php");
require_once(INCLUDES_PATH.DS."Swp.php");
require_once(INCLUDES_PATH.DS."Incident.php");
require_once(INCLUDES_PATH.DS."Hira.php");
require_once(INCLUDES_PATH.DS."Mail.php");
The Session.php page
<?php
class Session
{
private $logged_in;
public $user_id;
function __construct()
{
session_start();
$this->check_login();
}
public function is_logged_in() {
return $this->logged_in;
}
private function check_login() {
if (isset($_SESSION['UserID'])) {
$this->user_id = $_SESSION['UserID'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
The form page
<?php
//get all the includes
require_once("../php_functions/_init.php");
print_r($_FILES);
//all rows from csv file
$rows = array_map('str_getcsv', file($_FILES['file']['tmp_name'][0]));
//get only the headers
$header = array_shift($rows);
//declare the array
$csv = array();
//create associative array using array_combine
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($csv);
like I mentioned if I removed the require once from this page it works as expected. Any ideas would help
Just in case you need it here is the js for uploading the file
document.querySelector("#upload_file").addEventListener("click", function () {
const url = 'php/employee/upload_employee_csv_form.php';
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('file[]', file);
}
console.log(formData);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});

I actually figured it out. So my session was being included before I actually added it, to fix this instead of just saying session_start I check to see if the session is there and then only start if necessary.
The code
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Bonus tip :-)
The above code will work for php 5.4 and up if you are running something lower than 5.4 you can do the following:
if(session_id() == '') {
session_start();
}
Hope this helps

Related

PDF file not downloading or being saved to folder

I posted about this issue not that long ago, and I thought I had figured it out but nothing is happening.
Issue: I am trying to generate a PDF file that captures the signature of a client. Essentially they type in their name in a box and that name gets displayed in the pdf.php file along with all the other information(e.g. date, terms & conditions etc..).
I created a class that extends from FPDF and though JavaScript I am sending the name that gets filled and it gets processed through that pdf.php file and should return a "signed" pdf file.
However my pdf file is not downloading, saving or any of the options (I, D, F, S).
Below is a snippet of that section in my code.
pdf.php
$tempDir = "C:/PHP/temp/";
$thisaction = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$answers = filter_input(INPUT_POST, 'encFormData');
$decFD = json_decode($answers);
$pdf = new WaiverFPDF();
// Pull values from array
$returnVals = array();
$returnVals['result'];
$returnVals['html'] = '';
$returnVals['errorMsg'] = '';
//the name of the person who signed the waiver
$name = $decFD->signWaiver;
$today = date('m/d/Y');
if($thisaction == 'waiverName'){
// Generate a new PDF
$pdf = new WaiverFPDF();
$pdf->AddPage()
$pdfFile = "Waiver". $name . ".pdf";
....
// Output form
$pdf->Write(8, 'I HEREBY ASSUME ALL OF THE RISKS...');
// Line Break
$pdf-> all other info...
$outFile = $tempDir . $pdfFile;
//output pdf
$pdf->Output('D', $pdfFile);
$returnVals['result'] = true;
}
else{
$returnVals['errorMsg'] = "There was an error in waiver.php";
$returnVals['result'] = false;
}
echo json_encode($returnVals);
?>
.js file (JSON)
function sendWaiver(){
var formHash = new Hash();
formHash.signWaiver = $('signWaiver').get('value');
console.log ("name being encoded");
waiverNameRequest.setOptions({
data : {
'encFormData' : JSON.encode(formHash)
}
}).send();
return true;
}
waiverNameRequest = new Request.JSON({
method : 'post',
async : false,
url : 'pdf.php',
data : {
'action' : 'waiverName',
'encFormData' : ''
},
onRequest : function() {
// $('messageDiv').set('html', 'processing...');
console.log("waiver onRequest");
},
onSuccess : function(response) {
$('messageDiv').set('html', 'PDF has been downloaded');
if (response.result == true) {
console.log('OnSuccess PDF created');
} else {
$('messageDiv').set('html', response.errorMsg);
console.log('PDF error');
}
}
});
I know my error handling is very simple, but all I am getting is success messages, but no generated pdf file... I'm not sure what i am doing wrong. I also made sure the file (when i save to a file) is writable.
class_WaiverFPDF.php
class WaiverFPDF extends FPDF
{
// Page header
function Header()
{
// Arial bold 15
$this->SetFont('Arial','B',12);
// Position XY X=20, Y=25
$this->SetXY(15,25);
// Title
$this->Cell(179,10, 'Accident Waiver ','B','C');
// Line break
$this->Ln(11);
}
// Page footer
function Footer()
{
// Position from bottom
$this->SetY(-21);
// Arial italic 8
$this->SetFont('Arial','I',8);
$this->Ln();
// Current date
$this->SetFont('Arial','I',8);
// $this->Cell(179,10,$today,0,1,'R',false);
// $today= date('m/d/Y');
$this->Cell(115,10,' Participant Name',0,0,'C');
$this->Cell(150,10,'Date',0,'C',false);
// Page number
//$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}

create a session using php and ajax

I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance

Login with facebook in codeigniter

I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated
Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.
Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.

POSTing data serverside AND execute javascript code on submitting a form

My goal is to upload some images to a server and provide them with a description.
On clicking an upload button, this is what I want to happen:
1) a javascript function dynamically adds a form to get a description
of the images.
2) on submitting the form:
a) the description entered in the form must be available $_POST['description'] at server side.
b) the images are sent to the server using an XMLHttpRequest
In the code I wrote the description is not available $_POST['description'].
When i remove the check if(!isset($_POST['description'])), the imagefiles are perfectly uploaded.
This is my code:
javascript code
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt () {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
php code upload.php
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
I'd really advise against creating your own asynchronous file upload functionality when there is a plethora of developers who have already programmed the same thing better. Check out these options:
Blueimp's jQuery file uploader
Uploadifive (Uploadify's HTML5 implementation)
I've used these two before and they work very well. For BlueImp, you can use this option to send additional form data:
$('#fileupload').fileupload({
formData: $('.some_form').serialize()
});
The above captures a form and serializes its inputs. Alternatively, you can populate an array or object using specific values (i.e. from specific elements in your DOM):
var array = new Array();
$('.description').each(function() {
array[this.id] = this.value;
});
You'd use IDs to link your files and descriptions.

How do you access other files stored on an website with JavaScript?

I am trying to write a webpage for a list of files to download. The files are stored with the webpage and I want the webpage to dynamically list all the files in the folder to download. That way when more are added I don't have to modify the webpage. I know how to use JavaScript to create links on the webpage but I need to use it to find the names of the files first.
I found a website that had code for navigating files like a file browser but it only uses a string to store the current location.
This is in the header:
<script type="text/javascript"><!--
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var fileref = locarray.join("/");
//--></script>
this is in the body:
<form>
<input type=button value="Show Files" onClick="window.location=fileref;">
</form>
However this doesn't really help since I am trying to create download links to files not have a file browser.
Edit:
When you host a traditional HTML page you upload the htmlfile and any images or content for the page to what ever server you use.
I want to use javascript to dynamically link to every file hosted with the webpage.
I am trying to combine this with hosting the files in a Dropbox public folder for a simple way to make the files available.
If you want a list of files on the server you will need to use a server-side script to gather their names:
JS--
//use AJAX to get the list of files from a server-side script
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) {
//check the response to make sure it's a success
if (serverResponse.status == 'success') {
var len = serverResponse.output.length,
out = [];
//iterate through the serverResponse variable
for (var i = 0; i < len; i++) {
//add output to the `out` variable
out.push('<li>' + serverResponse.output[i] + '</li>');
}
//place new serverResponse output into DOM
$('#my-link-container').html('<ul>' + out.join('') + '</ul>');
} else {
alert('An Error Occured');
}
});
PHP--
<?php
//check to make sure the `get_list` GET variable exists
if (isset($_GET['get_list'])) {
//open the directory you want to use for your downloads
$handle = opendir('path/to/directory');
$output = array();
//iterate through the files in this directory
while ($file = readdir($handle)) {
//only add the file to the output if it is not in a black-list
if (!in_array($file, array('.', '..', 'error_log'))) {
$output[] = $file;
}
}
if (!empty($output)) {
//if there are files found then output them as JSON
echo json_encode(array('status' => 'success', 'output' => $output));
} else {
//if no files are found then output an error msg in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
} else {
//if no `get_list` GET variable is found then output an error in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
?>

Categories

Resources