The environment is MAMP, PHP version is 7.1.19.
We are assuming a contact form on the landing page that we do not use framework etc.
Because the code is long, the part which does not correspond to the question content is deleted
Below, select an image in form.html, push "submit" to "Confirmation screen", then display the image data in $ _FILES in the log to add the code of the image upload processing in confirm.php I want to.
However, even if you try to display the contents of $ _FILES in the log file with error_log ('confirm-files:'. Print_r ($ _ FILES, true), '0'); Array () I can not see the contents. By the way, file name is displayed in $ _POST.
Please tell us why the contents of $ _ FILES can not be seen.
After that, save the database as a tmp file on the server without using the database, after the transition to thanks.php, we will add the process to register to the customer management system.
Thank you.
・contact form
<form method="post" action="<?=$sfm_script?>" class="form" enctype="multipart/form-data">
<div class="file">
<label for="file1">Select files
<input type="file" id="file1" name="file1" onchange="$('.file_name1').text($(this).val())" class="file_name1"></label><span class="file_name1">
</div>
<button type="submit">To confirmation screen</button>
<input type="hidden" name="mailToNum" id="mailToNum" value="3">
<input type="hidden" name="autoReply" id="autoReply" value="1">
<input type="hidden" name="mode" id="mode" value="CONFIRM">
<?php if (array_key_exists('pram', $formvalue)):?>
<input type="hidden" name="pram" id="pram" value="<?=$formvalue['pram']?>">
<?php else:?>
<input type="hidden" name="pram" id="pram" value="">
<?php endif; ?>
</form>
・confirm.php
<?php header("Content-type: text/html; charset=utf-8") ?>
<?php
include_once('config.php');
if (!extension_loaded('mbstring')) {
Err('mbstring');
}
$internalEnc = 'UTF-8';
mb_language('ja');
mb_internal_encoding($internalEnc);
// main
if (!isset($mailTo[0])) {
Err('mailaddress');
}
$mode = (isset($_POST['mode'])) ? $_POST['mode'] : '';
error_log ('confirm-files:' . print_r($_FILES,true), '0');
switch ($mode) {
case 'SEND':
session_cache_limiter('nocache');
session_start();
//Om
include_once('thanks.html');
break;
case 'CONFIRM':
if ($_SERVER['HTTP_REFERER'] != 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] && $refCheck) {
Err('It can not be used from outside');
}
session_cache_limiter('nocache');
session_start();
unset($_SESSION['SFM']);
$error = $email = '';
foreach ($_POST as $key => $value) {
if (is_array($value)) {
$value = implode("\t", $value);
}
if (!$ill_slash) {
$value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;
}
if (!$ill_char) {
$value = mb_convert_encoding($value, $internalEnc, $baseEnc);
}
$value = mb_convert_kana($value, 'KV', $internalEnc);
$name = preg_replace('/(.+)_i$/', "$1", $key);
if (preg_match('/_i$/', $key) && $value == '') {
$_SESSION['SFM'][$name] = '::INPUT ERROR::';
$error = 1;
} elseif ($name == 'email' && $value) {
if (!preg_match("/^[\w\-\.\+]+\#[\w\-\.]+\.([a-z]+)$/", $value)) {
$_SESSION['SFM']['email'] = '::EMAIL ERROR::';
$error = $email = 1;
} else {
$_SESSION['SFM']['email'] = $email = $value;
}
} elseif ($name == 'emailcheck') {
if ($email != 1 && $email != $value) {
$_SESSION['SFM']['email'] = '::EMAIL CHECK ERROR::';
$error = 1;
}
} elseif ($maxText && strlen($value) > $maxText) {
$_SESSION['SFM'][$name] = '::MAXTEXT ERROR::';
$error = 1;
} else {
$_SESSION['SFM'][$name] = $value;
}
}
$_SESSION['SFM']['InputErr'] = $error;
//$sfm_script = $script_name . ((SID) ? '?'.strip_tags(SID) : '');
$sfm_script = "thanks.php";
include_once('confirm.html');
break;
default:
session_cache_limiter('private_no_expire');
session_start();
unset($_SESSION['SFM']);
//$sfm_script = $script_name;
$sfm_script = "confirm.php";
include_once('form.html');
}
exit;
function FORM_DATA_H($name) {
$errArray = array(
'::INPUT ERROR::' => '<span class="req">Required</span>',
'::EMAIL ERROR::' => 'E-mail address is invalid',
'::EMAIL CHECK ERROR::' => 'Mail address does not match',
'::MAXTEXT ERROR::' => 'Too many characters (upper limit ' . number_format($GLOBALS['maxText']) . ')'
);
$value = (isset($_SESSION['SFM'][$name])) ? $_SESSION['SFM'][$name] : '';
$value = (get_magic_quotes_gpc()) ? stripslashes($value) : $value;
$value = str_replace("\t", "\n", $value);
$value = nl2br(htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
$value = (preg_match('/::.+::/', $value)) ? '<span class="ERR">' . $errArray[$value] . '</span>' : $value;
$value = ($value != '') ? $value : ' ';
return mb_convert_encoding($value, $GLOBALS['baseEnc'], $GLOBALS['internalEnc']);
}
?>
・$_FILES log
[10-Mar-2019 09:15:55 Asia/Tokyo] files:Array
(
)
・Upload process I want to add in the future
foreach ($_FILES as $key => $file) {
if ($file['size'] > 0) {
$time = strtotime('today');
if (!file_exists('./files/' . $time)) {
mkdir('./files/' . $time);
chmod('./files/' . $time, 0777);
}
$tmp_name = str_replace('/Applications/MAMP/tmp/php', '', $file['tmp_name']);
move_uploaded_file($file['tmp_name'], './files/' . $time . $tmp_name);
$_FILES[$key]['tmp_name'] = './files/' . $time . $tmp_name;
}
}
Your issue is very well documented and, if I bothered to look for an instance your question should be closed as a duplicate of the many times this has been asked and answered here. You haven't set the form encoding so it is defaulting to URL encoding.
It should be enctype="multipart/form-data"
Related
I'm receiving an error with the email form not going through and receiving an error message. I've checked for parse and syntax errors and didn't come across any. I think that I need to upgrade the email form from php to smtp email settings, but not sure where exactly to start. Has anyone navigated this before and any tips on troubleshooting this issue? Could it be something else that is causing the error message?
<?php
/*
=== Copyright (c) x2cms.com 2011 === BUILDER_VERSION:12
*/
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr(str_replace('\\\\','\\',$_SERVER['PATH_TRANSLATED']),0, -1*strlen($_SERVER['SCRIPT_NAME'])));
/* initialize a session. */
session_start();
require("mailer.php");
require("template-loader.php");
require("settings-loader.php");
$settings['captcha_required'] = array_key_exists('captcha',$_POST);
// disable magic quotes
// --------------------------------------------------------------------------------------------
// languages
// --------------------------------------------------------------------------------------------
// load language
read_language_xml(BASE_PATH.'/emaileverything.php.xml');
// add default language for form
add_language_def('email_message','The following information was posted from your %s form');
add_language_def('email_subject','%s form results');
add_language_def('error_required','is a required field');
add_language_def('mail_sender','Mail sender IP address:');
add_language_def('go_back','« back');
add_language_def('error_captcha','The validation code you entered was invalid');
add_language_def('error_no_email_to','You must enter an email address');
add_language_def('error_no_email_from','You must enter an email address to send to.');
add_language_def('error_no_message','You must enter a message');
add_language_def('success_message','Thank you, the form has been processed successfully.');
add_language_def('error_message','The following error(s) occured: ');
// uploader
add_language_def('error_file_size','%s file is too big, the maximum file size is (%smb)');
add_language_def('file_link','File Link');
add_language_def('error_upload','Unable to save uploaded file, please check site uploaded directory and permissions.');
add_language_def('error_file_type','allowed files are %s. Yours was %s.');
// settings
// --------------------------------------------------------------------------------------------
$settings['form_id'] = ''; // form identifier
$settings['form_name'] = $_SERVER['HTTP_HOST']; // the name of the form used, defaults to the script address
$settings['confirmation_message'] = ''; // the confirmation message used with the template
$settings['confirmation_url'] = ''; // if specified we redirect to a confirmation page
$settings['email_subject'] = ''; // the email subject
$settings['email_to'] = ''; // who do we send the email to
$settings['email_from'] = ''; // the customer's email submitting the form
$settings['copy_mail_to_sender'] = 'false'; // whether we copy the form email to the mail sender $email_from
$settings['required_fields'] = ''; // required field names seperated by |
$settings['email_template'] = ''; // the email template to use
$settings['upload_max_size'] = '20'; // size in mb per file
$settings['upload_check_extension'] = 'false';
$settings['upload_allowed_extensions'] = 'jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx|zip'; // allowed file extensions
// general functions
// --------------------------------------------------------------------------------------------
if(!function_exists('str_ireplace'))
{
function str_ireplace($needle, $str, $haystack)
{
$needle = preg_quote($needle, '/');
return preg_replace("/$needle/i", $str, $haystack);
}
}
// ensure filename is in friendly format
function safe_filename($filename)
{
$filename = trim($filename);
$filename = str_replace("/", "", $filename);
$filename = str_replace("\\", "", $filename);
$filename = str_replace(">", "", $filename);
$filename = str_replace("<", "", $filename);
return $filename;
}
// check for required fields
function isRequired($field_name)
{
global $required_fieldsarr;
if(is_array($required_fieldsarr))
{
foreach ($required_fieldsarr as $required_field_name)
{
if(strtoupper($required_field_name) == strtoupper($field_name))
{
return true;
}
}
}
return false;
}
function get_file_extension($filename)
{
return end(explode(".", $filename));
}
// uploaded files
function uploadedFiles()
{
$returnStr = '';
$returnStr .= uploadFile("userfile");
for($i = 0; $i<10; $i++)
{
$returnStr .= uploadFile("userfile".$i);
}
return $returnStr;
}
function uploadFile($fieldName)
{
global $error_message, $_FILES, $language, $settings;
if(!isset($_FILES[$fieldName]))
{
return;
}
$allowed_file_ext_arr = explode("|", $settings['upload_allowed_extensions']);
$returnStr = '';
// try array of files first
if(is_array($_FILES[$fieldName]))
{
foreach ($_FILES[$fieldName]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $name, $settings['upload_max_size']).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= sprintf($language['error_file_type'], $settings['upload_allowed_extensions'], $file_type).'<br/>';
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
}
else // try single file
{
if($_FILES[$fieldName]["error"] == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $key, ($maxSize/1000)).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= $key." Allowed files are ".$settings['upload_allowed_extensions'].". Yours was ".$file_type."<br/>";
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
return $returnStr;
}
// read POST and GET data
// --------------------------------------------------------------------------------------------
// did we specify a form name in either GET OR POST
// get the form id
if(trim($_POST['id']) != '')
{
$settings['form_id'] = trim($_POST['id']);
}
if(trim($_GET['id']) != '')
{
$settings['form_id'] = trim($_GET['id']);
}
// 5.1 get parameters from XML
load_config('emaileverything-settings.xml');
load_config($settings['form_id'].'.xml');
// parse_settings_xml(safe_filename($settings['form_id']).'-settings.xml');
// check_referrer();
// get parameters from POST, POST overwrites settings from XML
if(trim($_POST['FormName']) != '')
{
$settings['form_name'] = trim($_POST['FormName']);
}
if(trim($_POST['EmailSubject']) != '')
$settings['email_subject'] = trim($_POST['EmailSubject']);
if(trim($_POST['EmailTo']) != '')
$settings['email_to'] = trim($_POST['EmailTo']);
if(trim($_POST['email']) != '')
$settings['email_from'] = trim($_POST['email']);
if(trim($_POST['OKMessage']) != '')
$settings['confirmation_message'] = trim($_POST['OKMessage']);
if(trim($_POST['OKURL']) != '')
$settings['confirmation_url'] = trim($_POST['OKURL']);
if(trim($_POST['CopyToSender']) != '')
$settings['copy_mail_to_sender'] = trim($_POST['CopyToSender']);
if(trim($_POST['UseTemplate']) != '')
$settings['email_template'] = trim($_POST['UseTemplate']);
if(trim($_POST['TemplateID']) != '')
$settings['template_id'] = trim($_POST['TemplateID']);
if(trim($_POST['RequiredFields']) != '')
$settings['required_fields'] = trim($_POST['RequiredFields']);
// alternative field names from trellix
if(trim($_POST['tlx_Subject']) != '')
$settings['email_subject'] = trim($_POST['tlx_Subject']);
if($_POST['tlx_EmailTo'] != '')
$settings['email_to'] = trim($_POST['tlx_EmailTo']);
if($_POST['tlx_OKMessage'] != '')
$settings['confirmation_message'] = trim($_POST['tlx_OKMessage']);
// build the email
// --------------------------------------------------------------------------------------------
// now we do some work with our required fields, split on | to get each required field name
$required_fieldsarr = explode("|", $settings['required_fields']);
$error_message = '';
// check required fields
foreach ($_POST as $key => $val)
{
// see if field is required
if(isRequired($key) && ($val == ''))
{
$error_message .= $key." ".$language['error_required'].".<br/>";
}
}
// build email message
if($settings['email_template'] != '') // are we using a email template
{
// safe file name
$settings['email_template'] = safe_filename($settings['email_template']);
// check to see if template exists
if(file_exists($settings['email_template']))
{
$email_message = file_get_contents($settings['email_template']);
// replace key with value
foreach ($_POST as $key => $val)
{
$email_message = str_ireplace('{'.$key.'}', $val, $email_message);
}
// remove remaining
$email_message = preg_replace('/\{(\w*)\}/', '', $email_message);
}
}
else
{
$email_message = sprintf($language['email_message'],$settings['form_name']);
$email_message .= '<br/><br/><table cellpadding="5" cellspacing="5" border="1"><tr><th>Field Name</th><th>Value</th></tr>';`
foreach ($_POST as $key => $val)
I am using Moodle version 3.8.4+ and PHP version 7.2.33 . Today I noticed a strange issue when I was trying to send a message to students, the message was:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays! More information about this error
I purge all caches as the suggestion was on "more information" section but it did not work.
I run the same Moodle version and PHP version on non production environment with the debugging mode and then I got this error message:
Coding error detected, it must be fixed by a programmer: Url parameters values can not be arrays!
More information about this error
Debug info:
Error code: codingerror
Stack trace:
line 405 of /lib/weblib.php: coding_exception thrown
line 460 of /lib/weblib.php: call to moodle_url->params()
line 49 of /mod/reservation/messageselect.php: call to moodle_url->param()
Output buffer: Invalid array parameter detected in required_param(): messagebody
line 655 of /lib/moodlelib.php: call to debugging()
line 30 of /mod/reservation/messageselect.php: call to optional_param()
The messageselect.php file is this but I am not able to see any issues here:
require_once('../../config.php');
require_once($CFG->dirroot.'/message/lib.php');
$id = required_param('id', PARAM_INT);
$messagebody = optional_param('messagebody', '', PARAM_CLEANHTML);
$send = optional_param('send', '', PARAM_BOOL);
$preview = optional_param('preview', '', PARAM_BOOL);
$edit = optional_param('edit', '', PARAM_BOOL);
$returnto = optional_param('returnto', new moodle_url('/mod/reservation/view.php', array('id' => $id)), PARAM_LOCALURL);
$format = optional_param('format', FORMAT_MOODLE, PARAM_INT);
$deluser = optional_param('deluser', 0, PARAM_INT);
if (isset($id)) {
if (! $cm = get_coursemodule_from_id('reservation', $id)) {
error('Course Module ID was incorrect');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
error('Course is misconfigured');
}
}
$url = new moodle_url('/mod/reservation/messageselect.php', array('id' => $id));
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
if ($send !== '') {
$url->param('send', $send);
}
if ($preview !== '') {
$url->param('preview', $preview);
}
if ($edit !== '') {
$url->param('edit', $edit);
}
if ($returnto !== '') {
$url->param('returnto', $returnto);
}
if ($format !== FORMAT_MOODLE) {
$url->param('format', $format);
}
if ($deluser !== 0) {
$url->param('deluser', $deluser);
}
$modulecontext = context_module::instance($cm->id);
$PAGE->set_url($url);
$PAGE->set_context($modulecontext);
require_login($course->id, false, $cm);
$coursecontext = context_course::instance($course->id);
$systemcontext = context_system::instance();
require_capability('moodle/course:bulkmessaging', $coursecontext);
if (empty($SESSION->reservation_messageto)) {
$SESSION->reservation_messageto = array();
}
if (!array_key_exists($id, $SESSION->reservation_messageto)) {
$SESSION->reservation_messageto[$id] = array();
}
if ($deluser) {
$idinmessageto = array_key_exists($id, $SESSION->reservation_messageto);
if ($idinmessageto && array_key_exists($deluser, $SESSION->reservation_messageto[$id])) {
unset($SESSION->reservation_messageto[$id][$deluser]);
}
}
if (empty($SESSION->reservation_messageselect[$id]) || $messagebody) {
$SESSION->reservation_messageselect[$id] = array('messagebody' => $messagebody);
}
$messagebody = $SESSION->reservation_messageselect[$id]['messagebody'];
$count = 0;
if ($data = data_submitted()) {
require_sesskey();
foreach ($data as $k => $v) {
if (preg_match('/^(user|teacher)(\d+)$/', $k, $m)) {
if (!array_key_exists($m[2], $SESSION->reservation_messageto[$id])) {
$returnfields = 'id,firstname,lastname,idnumber,email,mailformat,lastaccess, lang, maildisplay';
if ($user = $DB->get_record_select('user', "id = ?", array($m[2]), $returnfields)) {
$SESSION->reservation_messageto[$id][$m[2]] = $user;
$count++;
}
}
}
}
}
$strtitle = get_string('message', 'reservation');
$PAGE->navbar->add($strtitle);
$PAGE->set_title($strtitle);
$PAGE->set_heading($strtitle);
echo $OUTPUT->header();
// If messaging is disabled on site, we can still allow users with capabilities to send emails instead.
if (empty($CFG->messaging)) {
echo $OUTPUT->notification(get_string('messagingdisabled', 'message'));
}
if ($count) {
if ($count == 1) {
$heading = get_string('addedrecip', 'moodle', $count);
} else {
$heading = get_string('addedrecips', 'moodle', $count);
}
echo $OUTPUT->heading($heading);
}
if (!empty($messagebody) && !$edit && !$deluser && ($preview || $send)) {
require_sesskey();
if (count($SESSION->reservation_messageto[$id])) {
if (!empty($preview)) {
echo '<form method="post" action="messageselect.php" style="margin: 0 20px;">
<input type="hidden" name="returnto" value="'.s($returnto).'" />
<input type="hidden" name="id" value="'.$id.'" />
<input type="hidden" name="format" value="'.$format.'" />
<input type="hidden" name="sesskey" value="' . sesskey() . '" />
';
echo "<h3>".get_string('previewhtml')."</h3>";
echo "<div class=\"messagepreview\">\n".format_text($messagebody, $format)."\n</div>\n";
echo '<p align="center"><input type="submit" name="send" value="'.get_string('sendmessage', 'message').'" />'."\n";
echo '<input type="submit" name="edit" value="'.get_string('update').'" /></p>';
echo "\n</form>";
} else if (!empty($send)) {
$fails = array();
foreach ($SESSION->reservation_messageto[$id] as $user) {
if (!message_post_message($USER, $user, $messagebody, $format)) {
$user->fullname = fullname($user);
$fails[] = get_string('messagedselecteduserfailed', 'moodle', $user);
};
}
if (empty($fails)) {
echo $OUTPUT->heading(get_string('messagedselectedusers'));
unset($SESSION->reservation_messageto[$id]);
unset($SESSION->reservation_messageselect[$id]);
} else {
echo $OUTPUT->heading(get_string('messagedselectedcountusersfailed', 'moodle', count($fails)));
echo '<ul>';
foreach ($fails as $f) {
echo '<li>', $f, '</li>';
}
echo '</ul>';
}
echo '<p align="center">'.get_string('backtoparticipants').'</p>';
}
echo $OUTPUT->footer();
exit;
} else {
echo $OUTPUT->notification(get_string('nousersyet'));
}
}
echo '<p align="center">'.get_string("keepsearching").''.
((count($SESSION->reservation_messageto[$id])) ? ', '.get_string('usemessageform') : '').'</p>';
if ((!empty($send) || !empty($preview) || !empty($edit)) && (empty($messagebody))) {
echo $OUTPUT->notification(get_string('allfieldsrequired'));
}
if (count($SESSION->reservation_messageto[$id])) {
require_sesskey();
require("message.html");
}
$PAGE->requires->yui_module('moodle-core-formchangechecker',
'M.core_formchangechecker.init',
array(array(
'formid' => 'theform'
))
);
$PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
echo $OUTPUT->footer();
```php
It looks like the massagebody param in the request that initiates this process is using array syntax, like ?messagebody[]=foo instead of ?messagebody=foo, so the error is in whatever page the request originated from. You can either try to figure out why that is and change it, or make a change to this messageselect.php file to flatten the parameter. To do that you would change this:
<?php
if ($messagebody !== '') {
$url->param('messagebody', $messagebody);
}
to this:
<?php
if ($messagebody !== '') {
if(is_array($messagebody))
{
$messagebody = array_shift($messagebody);
}
$url->param('messagebody', $messagebody);
}
However be aware that if the page is sending this parameter as an array, it is quite likely that others will be sent that way as well. Usually you would send parameters using array syntax so that multiple records can be processed in one request, so that messagebody[1] would correlate to format[1], messagebody[2] would correlate to format[2], and so on. The code in messageselect.php is clearly not expecting this. I would be interested to find out what the story is for the page that sends requests here.
Based on a checkbox value this form will add subscribers to a corresponding list, but it can't save more than one value.
How do you merge, in order, to select and save more than one checkbox value?
if(isset($_POST['checkbox_list']) && in_array('Austin Metro', $_POST['checkbox_list'])){
$listID = '3';
if ($listID){
$indeed_mail->indeed_wysija_subscribe( $listID, $email );
}
break;
} else if(isset($_POST['checkbox_list']) && in_array('Central Austin', $_POST['checkbox_list'])){
$listID = '4';
if ($listID){
$indeed_mail->indeed_wysija_subscribe( $listID, $email );
}
break;
} else if(isset($_POST['checkbox_list']) && in_array('Georgetown', $_POST['checkbox_list'])){
$listID = '5';
if ($listID){
$indeed_mail->indeed_wysija_subscribe( $listID, $email );
}
break;
}
This might be what you're looking for... ?
$myValues = array('Austin Metro','Central Austin','Georgetown');
$myIds = array('3','4','5');
if (isset($_POST['checkbox_list']) && array_search($_POST['checkbox_list'], $myValues) !== false)
{
$index = array_search($_POST['checkbox_list'], $myValues);
$indeed_mail->indeed_wysija_subscribe( $myIds[$index], $email );
}
EDIT : I just read your comment above...
To grab your checkboxes as an array use :
<input type="checkbox" name="checkbox_list[]" value="Austin Metro">
<input type="checkbox" name="checkbox_list[]" value="Central Austin">
<input type="checkbox" name="checkbox_list[]" value="Georgetown">
Then
foreach($_POST['checkbox_list'] as $check)
{
// do your stuff as explained above...
if (isset(check) && array_search($check, $myValues) !== false)
{
$index = array_search($check, $myValues);
$indeed_mail->indeed_wysija_subscribe( $myIds[$index], $email );
}
}
I'm a complete newb in PHP, and the only reason I got this far was because I was trying to guess what everything does. I guess I was lucky that it worked this far.
So basically, I'm using the PHP Wake On LAN code that I found here to make a simple page that I log into, to remotely turn on my computer. I decided to add a username, rather than just a password, so maybe I could have multiple users. I've done everything successfully so far except one thing. When I log in, check my computer, and hit "Wake all selected", it logs me out immediately and doesn't send the magic packet. Any tips on what I could change to fix this? As soon as I remove the 'and' and the username bit in the if statement that checks for both user and pass to be correct, it works. But then there's no user and pass verifying going on. The if statement I'm talking about is the second if under the === Test for password protection === part.
You can demo the code on my site to see the issue in action here: http://trivisionzero.com/wol/
Just use 'user', 'pass'. (to recreate it, select any computer and press wake button)
Full code so far:
<center>
<br><br><br><br><br>
<?php
/* ============================== Configuration settings ====================================== */
/* List of PCs that may be woken */
$config_network_data_array[] = array("name" => "Shane-EPC", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "7";
$my_password = 'pass';
$my_username = 'user';
$html_title = '<H2>TrivisionZero PC Waker</H2>';
$config_table_columns = array('name', 'IP', 'MAC', 'links');
# The following function is copied (with some edits, to suppress output and return TRUE or an error message) from:
# http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html
# Wake on LAN - (c) HotKey#spr.at, upgraded by Murzik
# Modified by Allan Barizo http://www.hackernotcracker.com
flush();
function WakeOnLan($addr, $mac,$socket_number) {
$separator = ':';
if (strstr ( $mac, '-' ) ) {
$separator = '-';
}
$addr_byte = explode($separator, $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
// send it to the broadcast address using UDP
// SQL_BROADCAST option isn't help!!
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false) {
// echo "Error creating socket!\n";
// echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
return "Error creating socket!\nError code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_erro
($s));
// return FALSE;
}
else {
// setting a broadcast option to socket:
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret <0) {
// echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
return "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
// return FALSE;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
// echo "Magic Packet sent successfully!";
socket_close($s);
return TRUE;
}
else {
// echo "Magic packet failed!";
return "Magic packet failed!";
// return FALSE;
}
}
}
/* ============================== some predefined texts ====================================== */
$display_sent = 'Magic Packet sent successfully!';
$button_text = 'Wake!';
$button_text2 = 'Wake all selected';
//this is where I added my username part
$username_element = "<P>Username: <input type=\"text\" name=\"username\" />";
$password_element = "<P>Password: <input type=\"password\" name=\"password\" /><input type=\"submit\" name=\"submit\" value = \"Login\" />";
$table_html = "<TABLE border=\"2\">\n";
$logout_html = '';
/* ========================= Test for password protection ==================================== */
$wake_MAC_array = array();
if (!isset ($_POST['logout'])) {
$input_password = $_POST['password'];
$input_username = $_POST['username'];
}
//($my_password === '') is if you want no password
if (($input_password === $my_password) and ($input_username === $my_username)) {
$logged_in = TRUE;
$hidden_login = "<input type=\"hidden\" name=\"password\" value=\"$my_password\"/>";
if ($my_password !== '') {
$logout_html = "\n<P><input type=\"submit\" name=\"logout\" value=\"Log Out\"/>\n";
}
if ( (isset ($_POST['tickbox'])) and (is_array($_POST['tickbox']) ) ) {
$checkbox_array = $_POST['tickbox'];
foreach ($checkbox_array as $mac_address => $tickbox_setting) {
$wake_MAC_array[$mac_address] = $tickbox_setting;
}
}
} else {
$logged_in = FALSE;
$hidden_login = '';
$table_html_user = $username_element;
$table_html = $password_element;
}
/* ================================ LOGGED-IN users only ===================================== */
/* ======================= construct table for listing of devices ============================ */
if ($logged_in == TRUE) {
$table_row = "\n<TR>";
foreach ($config_table_columns as $key => $column_heading) {
$table_row .= '<TD>' . $column_heading . '</TD>';
}
$table_row .= '<TD>Wake Up!</TD>';
$table_row .= '<TD>status</TD>';
$table_html .= $table_row . "</TR>\n";
foreach ($config_network_data_array as $device_key => $device_values) {
$table_row = "\n<TR>";
$mac = $device_values['MAC'];
$device_name = $device_values['name'];
$status_cell = '<TD> </TD>';
foreach ($config_table_columns as $key => $column_heading) {
if (isset ( $device_values[$column_heading])) {
$value = $device_values[$column_heading];
if ($column_heading == 'MAC') {
/* special coding for MAC address column; prepare clickable button */
$this_MAC = $value;
$value = "<input type=\"submit\" name=\"wake_MAC\" value = \"$value\" />";
if (( $_POST['wake_MAC'] === $this_MAC ) or (array_key_exists ($this_MAC,
$wake_MAC_array))) {
$status = WakeOnLan ($device_values['WakeIP'], $this_MAC, $socket_number) ;
if ( $status === TRUE ) {
$status = $display_sent;
}
$status_cell = "<TD>$status</TD>";
}
}
} elseif ($column_heading == 'links') {
/* special coding for links column; prepare clickable links from $config_network_links_array */
$value = '';
if (isset ( $config_network_links_array[$device_name])) {
foreach ($config_network_links_array[$device_name] as $link_title => $link_URL) {
if ( $value !== '') {
$value .= '<BR />';
}
$value .= '' . $link_title . '';
}
}
} else {
$value = '';
}
if ($value === '') {
$value = ' ';
}
$table_row .= '<TD>' . $value . '</TD>';
}
/* now add a checkbox to wake up this device */
$table_row .= '<TD>' . "<input type=\"checkbox\" name=\"tickbox[$this_MAC]\" />" . '</TD>';
/* now add the status message (if applicable) for the attempt to send a packet to this device */
$table_row .= $status_cell;
$table_html .= $table_row . "</TR>\n";
}
$table_html .= "</TABLE>\n";
$table_html .= "<P><input type=\"submit\" name=\"wake all\" value = \"$button_text2\" />\n";
}
/* =========================================================================================== */
/* ======================= Now output the html that we've built ============================== */
echo $html_title;
echo "<FORM name=\"input\" action=\"" .$_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo '<P>';
echo $table_html_user;
echo $table_html;
echo $hidden_login;
echo $logout_html;
echo "</FORM>\n";
?>
</center>
When you are logged in and then submit the form to wake a machine, you are passing the password in a hidden field, but not the username.
As you are not passing the username, $input_username = null and thus the check if (($input_password === $my_password) and ($input_username === $my_username)) becomes if (('pass' === 'pass') and (null === 'user')) which is false and this is why you get logged out.
Background
Using Centos 5.5 final, Apache Tomcat 6, Java 1.6.0_24, PHP/Java Bridge 6.2.1, and JasperReports 4.0.1.
Problem
PHP fails to add a text value to a java.util.HashMap.
Question
Does any one have any suggestions on how to accomplish this task?
Source
If I comment out the line $map->put("text", "This is a test string");, the report compiles and runs.
<?php
/**
* see if the java extension was loaded.
*/
function checkJavaExtension()
{
if(!extension_loaded('java'))
{
$sapi_type = php_sapi_name();
$port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'])>1024)) ? $_SERVER['SERVER_PORT'] : '8080';
if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" || $sapi_type == "cli")
{
if(!(PHP_SHLIB_SUFFIX=="so" && #dl('java.so'))&&!(PHP_SHLIB_SUFFIX=="dll" && #dl('php_java.dll'))&&!(#include_once("java/Java.inc"))&&!(require_once("http://127.0.0.1:$port/java/Java.inc")))
{
return "java extension not installed.";
}
}
else
{
if(!(#include_once("java/Java.inc")))
{
require_once("http://www.webserver.net:$port/JavaBridge/java/Java.inc");
}
}
}
if(!function_exists("java_get_server_name"))
{
return "The loaded java extension is not the PHP/Java Bridge";
}
return true;
}
/**
* convert a php value to a java one...
* #param string $value
* #param string $className
* #returns boolean success
*/
function convertValue($value, $className)
{
// if we are a string, just use the normal conversion
// methods from the java extension...
try
{
if ($className == 'java.lang.String')
{
$temp = new Java('java.lang.String', $value);
return $temp;
}
else if ($className == 'java.lang.Boolean' ||
$className == 'java.lang.Integer' ||
$className == 'java.lang.Long' ||
$className == 'java.lang.Short' ||
$className == 'java.lang.Double' ||
$className == 'java.math.BigDecimal')
{
$temp = new Java($className, $value);
return $temp;
}
else if ($className == 'java.sql.Timestamp' ||
$className == 'java.sql.Time')
{
$temp = new Java($className);
$javaObject = $temp->valueOf($value);
return $javaObject;
}
}
catch (Exception $err)
{
echo ( 'unable to convert value, ' . $value .
' could not be converted to ' . $className);
return false;
}
echo ( 'unable to convert value, class name '.$className.
' not recognised');
return false;
}
checkJavaExtension();
$map = new Java("java.util.HashMap");
$map->put("text", "This is a test string");
$compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
$report = $compileManager->compileReport(realpath("test.jrxml"));
$fillManager = new JavaClass("net.sf.jasperreports.engine.JasperFillManager");
$emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");
$jasperPrint = $fillManager->fillReport($report, $map, $emptyDataSource);
$outputPath = realpath(".")."/"."output.pdf";
$exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
$exportManager->exportReportToPdfFile($jasperPrint, $outputPath);
header("Content-type: application/pdf");
readfile($outputPath);
unlink($outputPath);
?>
Source
Here is some code to pass parameters from PHP to JasperReports automatically, based on a naming convention for user input fields.
<?php
include_once( 'db-account.php' );
checkjavaExtension();
function report_parse_post_parameters() {
# Automatically extract report parameters (data types converted in report).
$params = new java('java.util.HashMap');
# Pass the remaining POST "report_TYP" variables as report parameters.
foreach( $_POST as $name => $value ) {
if( strpos( $name, 'report_' ) === 0 ) {
$length = strlen( 'report_' );
if( strpos( $name, 'report_int_' ) === 0 ) {
$value = intval( $value );
$length = strlen( 'report_int_' );
$value = convertValue( $value, 'java.lang.Integer' );
$params->put( substr( $name, $length ), $value );
}
else if( strpos( $name, 'report_arr_' ) === 0 ) {
$length = strlen( 'report_arr_' );
$arrays = array_filter( explode( ',', $_POST[ $name ] ) );
# Map the values of the array form parameter to a java.util.ArrayList.
$arrayList = new java( 'java.util.ArrayList' );
foreach( $arrays as $value ) {
$arrayList->add( $value );
}
# Pass values into the report (without the "report_arr_" prefix).
$params->put( substr( $name, $length ), $arrayList );
}
else {
$params->put( substr( $name, $length ), $value );
}
}
}
return $params;
}
function report_execute( $filename = 'FILENAME' ) {
global $dbhost;
global $dbname;
global $dbuser;
global $dbpass;
$conn = null;
$report = realpath( '/PATH/TO/REPORT.jasper' );
try {
$params = report_parse_post_parameters();
# Load the PostgreSQL database driver.
java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );
# Attempt a database connection.
$conn = java( 'java.sql.DriverManager' )->getConnection(
"jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );
# Use the fill manager to produce the report.
$fm = java('net.sf.jasperreports.engine.JasperFillManager');
$pm = $fm->fillReport($report, $params, $conn);
header('Cache-Control: private');
header('Content-Description: File Transfer');
header("Content-Disposition: attachment, filename=$filename.pdf");
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
java_set_file_encoding('ISO-8859-1');
$em = java('net.sf.jasperreports.engine.JasperExportManager');
$result = $em->exportReportToPdf($pm);
$conn->close();
header('Content-Length: ' . strlen( $result ) );
echo $result;
}
catch( Exception $ex ) {
if( $conn != null ) {
$conn->close();
}
throw $ex;
}
}
?>
Usage
Change this line:
function report_execute( $filename = 'FILENAME' ) {
Change this line:
$report = realpath( '/PATH/TO/REPORT.jasper' );
Change these lines to match your database software:
java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );
$conn = java( 'java.sql.DriverManager' )->getConnection(
"jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );
Edit db-account.php:
<?php
$dbhost = 'HOSTNAME';
$dbname = 'DATABASE';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
?>
Example Form Input
Use a report_ prefix for user inputs, such as:
<form method="post" action='report.dhtml' class="climate" id="report-form">
<input type="hidden" name="report_int_ReportId" value="1" />
<input type="hidden" name="report_int_Radius" value="35" />
<input type="hidden" name="report_int_Trend" value="0" />
<input type="hidden" name="report_int_Relevance" value="1" />
<select id="category" name="report_int_CategoryId" value="2"></select>
<input type="text" id="city" name="report_int_CityId" />
<input class="submit-button" id="submit" type="submit" name="submit" value="Report" />
</form>
These values are then passed automatically into the report.
Note
You should not have to change the code for checkjavaExtension().