Does session upload progress work with nginx and php-fpm? - file-upload

I'm running nginx 1.2.3 / php-fpm 5.4.6 and trying to use the Session upload progress feature. During an upload $_SESSION never contains any upload data whatsoever. At first I assumed coding errors, but even the most simple/basic upload progress tests failed to produce anything within $_SESSION.
I now suspect that the file is being POSTed directly to nginx, which completely handles the upload from beginning to end, THEN nginx passes the upload on to php-fpm so quickly that there is no real "progress" to report. Am I correct in this assessment? If so, how can I get around this?
phpconfig confirms that the session.upload settings are all set correctly.
Below is the current test code, borrowed from this blog.
<?php
/* File upload progress in PHP 5.4 */
/* needs a 5.4+ version */
$version = explode( '.', phpversion() );
if ( ($version[0] * 10000 + $version[1] * 100 + $version[2]) < 50400 )
die( 'PHP 5.4.0 or higher is required' );
if ( !intval(ini_get('session.upload_progress.enabled')) )
die( 'session.upload_progress.enabled is not enabled' );
session_start();
if ( isset( $_GET['progress'] ) ) {
$progress_key = strtolower(ini_get("session.upload_progress.prefix").'demo');
if ( !isset( $_SESSION[$progress_key] ) ) exit( "uploading..." );
$upload_progress = $_SESSION[$progress_key];
/* get percentage */
$progress = round( ($upload_progress['bytes_processed'] / $upload_progress['content_length']) * 100, 2 );
exit( "Upload progress: $progress%" );
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<?php if ( isset($_GET['iframe']) ): /* thank you Webkit... */ ?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="demo">
<input type="file" name="uploaded_file">
<input type="submit" value="Upload">
</form>
<script type="text/javascript">
window.location.hash = ""; /* reset */
jQuery("form").bind("submit", function() { window.location.hash = "uploading"; });
</script>
<?php else: ?>
<iframe src="?iframe" id="upload_form"></iframe>
<script type="text/javascript">
jQuery(document).ready(init);
function init() {
/* start listening on submit */
update_file_upload_progress();
}
function update_file_upload_progress() {
if ( window.frames.upload_form.location.hash != "#uploading" ) {
setTimeout( update_file_upload_progress, 100 ); /* has upload started yet? */
return;
}
$.get( /* lather */
"?progress",
function(data) {
/* rinse */
jQuery("#file_upload_progress").html(data);
/* repeat */
setTimeout( update_file_upload_progress, 500 );
}
).error(function(jqXHR, error) { alert(error); });
}
</script>
<div id="file_upload_progress"></div>
<?php endif; ?>

A note in the documentation page on php.net says :
s.zarges 19-Jun-2012 09:32
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.

Related

Empty post value : CodeIgniter

While uploading the file through codeigniter, I am getting the following error:
My file upload result is:
My Controller function is below:
public function Upload files($data='')
{
ini_set("display_errors",1); // I added so it would help me show errors
error_reporting(E_ALL);
print_r($_POST);exit('I am in the tp');
$config['upload_path'] = 'assets/images/uploads/';
//$config['allowed_types'] = 'gif|jpg|png';
//$config['max_size'] = 100;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);exit('The first loop');
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
print_r($data);exit();
$this->load->view('upload_success', $data);
}
}
And my view file:
<div id="Upload_div">
<?php //echo $error;?>
<form action="<?php echo site_url() ?>/Admin/Upload_files/" method="POST" enctype="multipart/form-data">
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="userfile"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</div>
Can anyone help me figure out why post value is empty?
Thanks
$_POST does not contain any file data.
Remove the line
print_r($_POST);exit('I am in the tp');
And then tell us what happens.

Converting Pdo OOP To Mysqli Procedural

Folks, :)
My 3+ pages are all in mysqli procedural. I cannot just switch to pdo and oop and throw 6 mnths of work down the drain! And so, let's try converting the following code suggestion by another to mysqli procedural.
I really need the following code converted to mysqli procedural from pdo oop. Once that is done, my 7 months project will come to an end. And, I can move-on to learning pdo. Right now, can't afford to jump into pdo without finishing my current project.
So, who will help me convert ? Other newbies would learn from your conversion.
Thanks!
[code]
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include 'config.php';
// check if user is already logged in
if (is_logged() === true)
{
//Redirect user to homepage page after 5 seconds.
header("refresh:2;url=home.php");
exit; //
}
if (
array_key_exists('login_username_or_email', $_POST) &&
array_key_exists('login_password' , $_POST)
) {
$usernameoremail = trim($_POST["login_username_or_email"]); //
$password = $_POST["login_password"];
// don't bother trimming, they can't enter it right, don't let them log
in!
$stmt = $conn->prepare('SELECT ids, usernames, passwords, emails,
accounts_activations_statuses
FROM users WHERE ' . (
strpos($usernameoremail, '#') === false) ? 'usernames' : 'emails'
) . ' = ?
');
$stmt->bind_param('s', $_POST['login_username_or_email']);
$stmt->execute();
$stmt->bind_result(
$db_id, $db_username, $db_password, $db_email,
$db_account_activation_status
);
if (
$stmt->fetch() &&
password_verify($_POST['login_password'], $db_password)
) {
echo '
<p>Login Successful</p>
<dl>
<dt>User Id</dt>
<dd>', $db_id, '</dd>
<dt>E-Mail</dt>
<dd>', $db_email, '</dd>
<dt>Username</dt>
<dd>', $db_username, '</dd>
<dt>Activation Stats</dt>
<dd>', $db_account_activation_status, '</dd>
</dl>
';
} else echo '<p>Invalid username or password</p>';
$stmt->close();
} else echo '<p>Missing username or password</p>';
?>
<!DOCTYPE html>
<html>
<head>
<title><?php $site_name?> Member Login Page</title>
<meta charset="utf-8">
</head>
<body>
<div class = "container">
<form method="post" action="">
<h3><?= $site_name ?> Member Login Form</h3>
<fieldset>
<label for="login_name">Username/Email:</label>
<input type="text" name="login_username_or_email" id="login_name">
<br>
<label for="login_pass">Password:</label>
<input type="password" name="login_password" id="login_pass">
</fieldset>
<div class="submitsAndHiddens">
<button type="submit">Login</button><br>
Forgot your Password?<br>
Register New Account
</div>
</form>
</div>
</body>
[/code]

Wordpress sql fetch_assoc

I'm having hard time troubleshooting why i cannot seem to run this inside wordpress like on the index.php. It works when its standalone. I created additional table inside wordpress db. Im seeing blank data when i run. Somehow its not picking up the data. I came to know after research i need to use $wpdb and get_results. so I converted it from this old code :
$result = $db->query("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
/to wordpress code/
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
?>
//on the header.php
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['name', 'Rating'],
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "['".$row['name']."', ".$row['rating']."],";
}
}
?>
]);
var options = {
title: 'Figure',
width: 900,
height: 500,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
on the body html i have
<body>
<!-- Display the pie chart -->
<div id="piechart"></div>
</body>
If you are using $wpdb , then you must need to pass 'ARRAY_A' inside get_results like the following to get result in array format.
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC",'ARRAY_A');

Joomla 3.3 MVC file/pdf upload in custom component backend

I want to upload a pdf from a custom component from backend in the edit mode.
the state now is,
1.- either the pdf is uploaded correctly but the file name is not written in the database,
2.- or the file name is written in the data base, but the pdf is not seen by JFactory::getApplication()->input;
I found out is has with enctype="multipart/form-data" to do.
In case 1.- enctype="multipart/form-data" is in and the pdf is uploaded
in case 2.- the pdf file name is written in the data base.
What to do know ? I need both, of course.
Here so code, it is a little component com_job with MVC structure under Joomla! 3.3:
here just the part file administrator/components/com_job/views/tmpl/edit.php
with the enctype="multipart/form-data"
<form method="post" action="<?php echo JRoute::_('index.php?option=com_job&layout=edit&id='.(int) $this->item->id); ?>" id="adminForm" name="adminForm" enctype="multipart/form-data">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Details' ); ?></legend>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('title'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('title'); ?>
</div>
</div>
....
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('upload_pdf'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('upload_pdf'); ?>
</div>
</div>
........
here a part of the xml file administrator/components/com_job/models/forms/job.xml
<?xml version="1.0" encoding="utf-8"?>
...
<field
id="title"
name="title"
type="text"
required="true"
label="Title"
description="title_Desc"
class="inputbox"
size="40"/>
<field
id="upload_pdf"
name="upload_pdf"
type="file"
required="false"
label="Upload_pdf"
description="upload_pdf_Desc"
class="inputbox"
size="40"
accept="application/pdf"/>
.....
here the controller administrator/components/com_job/controllers/job.php
jimport('joomla.application.component.controlleradmin');
jimport('joomla.application.component.controllerform');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
class JobControllerJob extends JControllerForm
{
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$files['upload_pdf']['name'] = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($files['upload_pdf']['name'])) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
}
where is the error ? I tried to put enctype="multipart/form-data" in the form in job.xml (models), but it didn't work.
I found a temporally solution, in the save function in the controller, I add this code:
//$jform = $jinput->get(jform, null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
the first line with $jinput didn't work. I tried many ways with $jinput, but nothing worked. So finally I used directly $_POST. Of course, it is not the right way, but at least it works.
here the full function save:
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($pdf_filename)) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if ($status) {
//$jform = $jinput->get(jform, null);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
} else {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['upload_pdf'];
Try this...it is true method!!!
That should do the trick. The $file array then holds the following keys:
error
name
size
tmp_name
type

INSERT in the query part of BigQuery, using google-api-php-client

I wanted to insert thousands of records in the database using INSERT command in php script , as it will easier to access, but https://developers.google.com/bigquery/docs/query-reference , this doesn't show the INSERT command that can be used while querying in php , like ,
$quert->setQuery("Insert into ... values...") , Have tried this in the Query Table of BigQuery web console, but it doesn't seem to work , Is there anyway to use setQuery() with some other command, to insert data ?
BigQuery doesn't support the INSERT command. You would need to create a load job. See https://developers.google.com/bigquery/docs/import#localimport for more information.
In addition to Jordan's answer, here's a snippet of code that should get you started using the Google BigQuery API and the Google API PHP client library for loading your own data into BigQuery programmatically. Note, this snippet simply spits out the raw API response of the load job, including the job Id to the screen - you'll have to add your own polling logic to check on the load job status.
(We will be adding additional documentation about loading your own data, as well as more PHP samples soon).
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_BigqueryService.php";
session_start();
$client = new Google_Client();
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setScopes(array('https://www.googleapis.com/auth/bigquery'));
$client->setClientId('XXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXX');
$client->setRedirectUri('http://YOURAPPLICATION/index.php');
// Instantiate a new BigQuery Client
$bigqueryService = new Google_BigqueryService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
?>
<!doctype html>
<html>
<head>
<title>BigQuery API Sample</title>
</head>
<body>
<div id='container'>
<div id='top'><h1>BigQuery API Sample</h1></div>
<div id='main'>
<?php
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
// Your project number, from the developers.google.com/console project you created
// when signing up for BigQuery
$project_number = 'XXXXXXXXXXXXXX';
// Information about the destination table
$destination_table = new Google_TableReference();
$destination_table->setProjectId($project_number);
$destination_table->setDatasetId('php_test');
$destination_table->setTableId('my_new_table');
// Information about the schema for your new table
$schema_fields = array();
$schema_fields[0] = new Google_TableFieldSchema();
$schema_fields[0]->setName('first');
$schema_fields[0]->setType('string');
$schema_fields[1] = new Google_TableFieldSchema();
$schema_fields[1]->setName('last');
$schema_fields[1]->setType('string');
$destination_table_schema = new Google_TableSchema();
$destination_table_schema->setFields($schema_fields);
// Set the load configuration, including source file(s) and schema
$load_configuration = new Google_JobConfigurationLoad();
$load_configuration->setSourceUris(array('gs://YOUR_GOOGLE_CLOUD_STORAGE_BUCKET/file.csv'));
$load_configuration->setDestinationTable($destination_table);
$load_configuration->setSchema($destination_table_schema);
$job_configuration = new Google_JobConfiguration();
$job_configuration->setLoad($load_configuration);
$load_job = new Google_Job();
$load_job->setKind('load');
$load_job->setConfiguration($job_configuration);
$jobs = $bigqueryService->jobs;
$response = $jobs->insert($project_number, $load_job);
echo '<pre>';
print_r($response);
echo '</pre>';
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Authorize Access to the BigQuery API</a>";
}
?>
</div>
</div>
</body>
</html>