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 );
}
}
Related
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"
I try to make a function to insert more fields in database.
I find an example, but maybe more parameters is deprecated...or i have an error.
Here is my code:
private function _setUserPersonalDetails($blog_id, $personal_data, $operation = 'insert') {
global $wpdb;
// Strip any html tags from the about and address fields.
$tmp = array();
foreach ($personal_data as $key => $val) {
if (($key === 'about') || ($key === 'address')) {
$tmp[$key] = strip_tags($val);
}
else {
$tmp[$key] = $val;
}
}
$personal_data = $tmp;
if ($operation == 'insert') {
// Save personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('INSERT INTO wp0_users_conta_data (blog_id, type, data) VALUES (%d, %s, %s)', $blog_id, $type, $encoded_data);
$wpdb->query($q);
}
if ($operation == 'update') {
// Update personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('UPDATE wp0_users_conta_data set data=%s where blog_id=%d and type=%s', $encoded_data, $blog_id, $type);
$wpdb->query($q);
}
}
}
I spent more one week to solve the problem, but i don't find any solutions. I appreciate any helps. Thank you!
Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks
I'm using a WordPress plugin called User Submitted Posts. The plugin allows for users to upload multiple photos. I have it set up so that users can upload 0 to a max of 3. When I try to upload more than one pic, however, only one of them gets posted.
HTML:
<div id="usp">
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<ul id="usp_list">
<li class="usp_title">
<label for="user-submitted-title" class="usp_label">Post Title</label>
<div>
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
</div>
</li>
<li class="usp_tags">
<label for="user-submitted-tags" class="usp_label">Post Tags <small>(separate tags with commas)</small></label>
<div>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="" />
</div>
</li>
<li class="usp_content">
<label for="user-submitted-content" class="usp_label">Post Content</label>
<div>
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
</div>
</li>
<li class="usp_images">
<label for="user-submitted-image" class="usp_label">Upload an Image</label>
<div id="usp_upload-message"></div>
<div>
<input class="usp_input usp_clone" type="file" size="25" id="user-submitted-image" name="user-submitted-image[]" />
Add another image
</div>
</li>
<li class="usp_submit">
<input class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post" />
</li>
</ul>
</form>
PHP:
if (!class_exists('Public_Submission_Form')) {
class Public_Submission_Form {
var $version = '1.0';
var $_post_meta_IsSubmission = 'is_submission';
var $_post_meta_Submitter = 'user_submit_name';
var $_post_meta_SubmitterUrl = 'user_submit_url';
var $_post_meta_SubmitterIp = 'user_submit_ip';
var $_post_meta_Image = 'user_submit_image';
var $_post_meta_ImageInfo = 'user_submit_image_info';
var $settings = null;
function Public_Submission_Form() {
register_activation_hook(__FILE__, array(&$this, 'saveDefaultSettings'));
add_action('admin_init', array(&$this, 'checkForSettingsSave'));
add_action('admin_menu', array(&$this, 'addAdministrativeElements'));
add_action('init', array(&$this, 'enqueueResources'));
add_action('parse_request', array(&$this, 'checkForPublicSubmission'));
add_action('parse_query', array(&$this, 'addSubmittedStatusClause'));
add_action('restrict_manage_posts', array(&$this, 'outputUserSubmissionLink'));
add_filter('the_author', array(&$this, 'replaceAuthor'));
add_filter('the_author_link', array(&$this, 'replaceAuthorLink'));
add_filter('post_stati', array(&$this, 'addNewPostStatus'));
add_shortcode('user-submitted-posts', array(&$this, 'getPublicSubmissionForm'));
}
function addAdministrativeElements() {
add_options_page(__('User Submitted Posts'), __('User Submitted Posts'), 'manage_options', 'user-submitted-posts', array(&$this, 'displaySettingsPage'));
}
function addNewPostStatus($postStati) {
$postStati['submitted'] = array(__('Submitted'), __('User submitted posts'), _n_noop('Submitted', 'Submitted'));
return $postStati;
}
function addSubmittedStatusClause($wp_query) {
global $pagenow;
if (is_admin() && $pagenow == 'edit.php' && $_GET['user_submitted'] == '1') {
set_query_var('meta_key', $this->_post_meta_IsSubmission);
set_query_var('meta_value', 1);
set_query_var('post_status', 'pending');
}
}
function checkForPublicSubmission() {
if (isset($_POST['user-submitted-post']) && ! empty($_POST['user-submitted-post'])) {
$settings = $this->getSettings();
$title = stripslashes($_POST['user-submitted-title']);
$content = stripslashes($_POST['user-submitted-content']);
$authorName = stripslashes($_POST['user-submitted-name']);
$authorUrl = stripslashes($_POST['user-submitted-url']);
$tags = stripslashes($_POST['user-submitted-tags']);
$category = intval($_POST['user-submitted-category']);
$fileData = $_FILES['user-submitted-image'];
$publicSubmission = $this->createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData);
if (false == ($publicSubmission)) {
$errorMessage = empty($settings['error-message']) ? __('An error occurred. Please go back and try again.') : $settings['error-message'];
if( !empty( $_POST[ 'redirect-override' ] ) ) {
$redirect = stripslashes( $_POST[ 'redirect-override' ] );
$redirect = add_query_arg( array( 'submission-error' => '1' ), $redirect );
wp_redirect( $redirect );
exit();
}
wp_die($errorMessage);
} else {
$redirect = empty($settings['redirect-url']) ? $_SERVER['REQUEST_URI'] : $settings['redirect-url'];
if (! empty($_POST['redirect-override'])) {
$redirect = stripslashes($_POST['redirect-override']);
}
$redirect = add_query_arg(array('success'=>1), $redirect);
wp_redirect($redirect);
exit();
}
}
}
function checkForSettingsSave() {
if (isset($_POST['save-post-submission-settings']) && current_user_can('manage_options') && check_admin_referer('save-post-submission-settings')) {
$settings = $this->getSettings();
$settings['author'] = get_userdata($_POST['author']) ? $_POST['author'] : $settings['author'];
$settings['categories'] = is_array($_POST['categories']) && ! empty($_POST['categories']) ? array_unique($_POST['categories']) : array(get_option('default_category'));
$settings['number-approved'] = is_numeric($_POST['number-approved']) ? intval($_POST['number-approved']) : - 1;
$settings['redirect-url'] = stripslashes($_POST['redirect-url']);
$settings['error-message'] = stripslashes($_POST['error-message']);
$settings['min-images'] = is_numeric($_POST['min-images']) ? intval($_POST['min-images']) : $settings['max-images'];
$settings['max-images'] = (is_numeric($_POST['max-images']) && ($settings['min-images'] <= $_POST['max-images'])) ? intval($_POST['max-images']) : $settings['max-images'];
$settings['min-image-height'] = is_numeric($_POST['min-image-height']) ? intval($_POST['min-image-height']) : $settings['min-image-height'];
$settings['min-image-width'] = is_numeric($_POST['min-image-width']) ? intval($_POST['min-image-width']) : $settings['min-image-width'];
$settings['max-image-height'] = (is_numeric($_POST['max-image-height']) && ($settings['min-image-height'] <= $_POST['max-image-height'])) ? intval($_POST['max-image-height']) : $settings['max-image-height'];
$settings['max-image-width'] = (is_numeric($_POST['max-image-width']) && ($settings['min-image-width'] <= $_POST['max-image-width'])) ? intval($_POST['max-image-width']) : $settings['max-image-width'];
$settings['usp_name'] = stripslashes($_POST['usp_name']);
$settings['usp_url'] = stripslashes($_POST['usp_url']);
$settings['usp_title'] = stripslashes($_POST['usp_title']);
$settings['usp_tags'] = stripslashes($_POST['usp_tags']);
$settings['usp_category'] = stripslashes($_POST['usp_category']);
$settings['usp_content'] = stripslashes($_POST['usp_content']);
$settings['usp_images'] = stripslashes($_POST['usp_images']);
$settings['upload-message'] = stripslashes($_POST['upload-message']);
$settings['usp_form_width'] = stripslashes($_POST['usp_form_width']);
$this->saveSettings($settings);
wp_redirect(admin_url('options-general.php?page=user-submitted-posts&updated=1'));
}
}
function displaySettingsPage() {
include ('views/settings.php');
}
function enqueueResources() {
wp_enqueue_script('usp_script', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.js', array('jquery'), $this->version);
wp_enqueue_style('usp_style', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.css', false, $this->version, 'screen');
}
function getPublicSubmissionForm($atts = array(), $content = null) {
if ($atts === true) {
$redirect = $this->currentPageURL();
}
ob_start();
include (WP_PLUGIN_DIR.'/'.basename(dirname(__FILE__)).'/views/submission-form.php');
return ob_get_clean();
}
function outputUserSubmissionLink() {
global $pagenow;
if ($pagenow == 'edit.php') {
echo '<a id="usp_admin_filter_posts" class="button-secondary" href="'.admin_url('edit.php?post_status=pending&user_submitted=1').'">'.__('User Submitted Posts').'</a>';
}
}
function replaceAuthor($author) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
if ($isSubmission && ! empty($submissionAuthor)) {
return $submissionAuthor;
} else {
return $author;
}
}
function replaceAuthorLink($authorLink) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
$submissionLink = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
if ($isSubmission && ! empty($submissionAuthor)) {
if ( empty($submissionLink)) {
return $submissionAuthor;
} else {
return "<a href='{$submissionLink}'>{$submissionAuthor}</a>";
}
} else {
return $authorLink;
}
}
function saveDefaultSettings() {
$settings = $this->getSettings();
if ( empty($settings)) {
$currentUser = wp_get_current_user();
$settings = array();
$settings['author'] = $currentUser->ID;
$settings['categories'] = array(get_option('default_category'));
$settings['number-approved'] = -1;
$settings['redirect-url'] = ''; //site_url();
$settings['error-message'] = __('There was an error. Please ensure that you have added a title, some content, and that you have uploaded only images.');
$settings['min-images'] = 0;
$settings['max-images'] = 1;
$settings['min-image-height'] = 0;
$settings['min-image-width'] = 0;
$settings['max-image-height'] = 500;
$settings['max-image-width'] = 500;
$settings['usp_name'] = 'show';
$settings['usp_url'] = 'show';
$settings['usp_title'] = 'show';
$settings['usp_tags'] = 'show';
$settings['usp_category'] = 'show';
$settings['usp_content'] = 'show';
$settings['usp_images'] = 'hide';
$settings['upload-message'] = ''; // 'Please select your image(s) to upload:';
$settings['usp_form_width'] = '300'; // in pixels
$this->saveSettings($settings);
}
}
function getSettings() {
if ($this->settings === null) {
$defaults = array();
$this->settings = get_option('User Submitted Posts Settings', array());
}
return $this->settings;
}
function saveSettings($settings) {
if (!is_array($settings)) {
return;
}
$this->settings = $settings;
update_option('User Submitted Posts Settings', $this->settings);
}
function createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData) {
$settings = $this->getSettings();
$authorName = strip_tags($authorName);
$authorUrl = strip_tags($authorUrl);
$authorIp = $_SERVER['REMOTE_ADDR'];
if (!$this->validateTitle($title)) {
return false;
}
if (!$this->validateContent($title)) {
return false;
}
if (!$this->validateTags($tags)) {
return false;
}
$postData = array();
$postData['post_title'] = $title;
$postData['post_content'] = $content;
$postData['post_status'] = 'pending';
$postData['author'] = $settings['author'];
$numberApproved = $settings['number-approved'];
if ($numberApproved < 0) {} elseif ($numberApproved == 0) {
$postData['post_status'] = 'publish';
} else {
$posts = get_posts(array('post_status'=>'publish', 'meta_key'=>$this->_post_meta_Submitter, 'meta_value'=>$authorName));
$counter = 0;
foreach ($posts as $post) {
$submitterUrl = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
$submitterIp = get_post_meta($post->ID, $this->_post_meta_SubmitterIp, true);
if ($submitterUrl == $authorUrl && $submitterIp == $authorIp) {
$counter++;
}
}
if ($counter >= $numberApproved) {
$postData['post_status'] = 'publish';
}
}
$newPost = wp_insert_post($postData);
if ($newPost) {
wp_set_post_tags($newPost, $tags);
wp_set_post_categories($newPost, array($category));
if (!function_exists('media_handle_upload')) {
require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php');
}
$attachmentIds = array();
$imageCounter = 0;
for ($i = 0; $i < count($fileData['name']); $i++) {
$imageInfo = getimagesize($fileData['tmp_name'][$i]);
if (false === $imageInfo || !$this->imageIsRightSize($imageInfo[0], $imageInfo[1])) {
continue;
}
$key = "public-submission-attachment-{$i}";
$_FILES[$key] = array();
$_FILES[$key]['name'] = $fileData['name'][$i];
$_FILES[$key]['tmp_name'] = $fileData['tmp_name'][$i];
$_FILES[$key]['type'] = $fileData['type'][$i];
$_FILES[$key]['error'] = $fileData['error'][$i];
$_FILES[$key]['size'] = $fileData['size'][$i];
$attachmentId = media_handle_upload($key, $newPost);
if (!is_wp_error($attachmentId) && wp_attachment_is_image($attachmentId)) {
$attachmentIds[] = $attachmentId;
add_post_meta($newPost, $this->_post_meta_Image, wp_get_attachment_url($attachmentId));
$imageCounter++;
} else {
wp_delete_attachment($attachmentId);
}
if ($imageCounter == $settings['max-images']) {
break;
}
}
if (count($attachmentIds) < $settings['min-images']) {
foreach ($attachmentIds as $idToDelete) {
wp_delete_attachment($idToDelete);
}
wp_delete_post($newPost);
return false;
}
update_post_meta($newPost, $this->_post_meta_IsSubmission, true);
update_post_meta($newPost, $this->_post_meta_Submitter, htmlentities(($authorName)));
update_post_meta($newPost, $this->_post_meta_SubmitterUrl, htmlentities(($authorUrl)));
update_post_meta($newPost, $this->_post_meta_SubmitterIp, $authorIp);
}
return $newPost;
}
function imageIsRightSize($width, $height) {
$settings = $this->getSettings();
$widthFits = ($width <= intval($settings['max-image-width'])) && ($width >= $settings['min-image-width']);
$heightFits = ($height <= $settings['max-image-height']) && ($height >= $settings['min-image-height']);
return $widthFits && $heightFits;
}
function validateContent($content) {
return ! empty($content);
}
function validateTags($tags) {
return true;
}
function validateTitle($title) {
return ! empty($title);
}
function currentPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
}
$publicSubmissionForm = new Public_Submission_Form();
include ('library/template-tags.php');
}
== Template Tags ==
To display the images attached to user-submitted posts, use this template tag:
<?php post_attachments(); ?>
This template tag prints the URLs for all post attachments and accepts the following paramters:
<?php post_attachments($size, $beforeUrl, $afterUrl, $numberImages, $postId); ?>
$size = image size as thumbnail, medium, large or full -> default = full
$beforeUrl = text/markup displayed before the image URL -> default = <img src="
$afterUrl = text/markup displayed after the image URL -> default = " />
$numberImages = the number of images to display for each post -> default = false (display all)
$postId = an optional post ID to use -> default = uses global post
Additionally, the following template tag returns an array of URLs for the specified post image:
<?php get_post_images(); ?>
This tag returns a boolean value indicating whether the specified post is a public submission:
<?php is_public_submission(); ?>
What does var_dump($_FILES) look like? It looks like you're generating a unique field name for each file upload field, using $key = "public-submission-attachment-{$i}";. if that's the case, then your file access structure is incorrect. PHP will generate the $_FILES data for each fieldname 1 of 2 ways:
If you're using a unique somestring field name, you get a structure like:
$_FILES['somestring'] = array(
'name' => 'somefile.txt',
'type' => 'text/plain',
'size' => 1234,
'error' => 0,
'tmp_name'] => '/tmp/asdfasdfasdfa'
);
If you're using the PHP-centric array notation, somestring[] (note the []) for the field name, you get:
$_FILES['somestring'] = array(
'name' => array(
0 => 'somefile1.txt',
1 => 'somepic.jpg'
),
'type' => array(
0 => 'text/plain',
1 => 'image.jpeg'
)
etc...
);
Given that it you seem to be generating a unique field name, WITHOUT the array notation, you'd have to use option #1.
I am trying to read a vcf, I am already getting the values, but unable to retrieve the type and prefixes.
Please see following code
<?php
require_once( 'Contact_Vcard_Parse.php' );
if ( $_FILES['file']['tmp_name'] )
{
$parse = new Contact_Vcard_Parse();
$cardinfo = $parse->fromFile( $_FILES['file']['tmp_name'] );
foreach( $cardinfo as $card )
{
$first = $card['N'][0]['value'][0][0];
$last = $card['N'][0]['value'][1][0];
$email = $card['EMAIL'][0]['value'][0][0];
$telcount=0;
while($telcount<50)
{
$teltitle = $card['TEL'][$telcount]['node'][0][0];
$tel = $card['TEL'][$telcount]['value'][0][0];
if(strlen($tel)>=10)
{
echo 'title : '.$teltitle.' TEL : '.$tel.'<br>';
}
$telcount++;
}
?>
email : <?php echo( $email ); ?>
<br>n : <?php echo( $first ); ?> <br>fn : <?php echo( $last ); ?> <br>
<?php
}
}
?>
https://github.com/nuovo/vCard-parser
I was this vCard-parser before an year. Its working like a charm. You can use this library in your code.
PS: Dont reinvent the wheel.. :)
If you don't want to use any libraries:
$VArquivoApple = fopen("./contactsapple.vcf", 'r');
$VArrayApple = [];
while (($VLinha = fgetcsv($VArquivoApple)) !== false)
$VArrayApple[] = $VLinha[0];
fclose($VArquivoApple);
$VAContatosApple = [];
for ($Vi = 0; $Vi < count($VArrayApple); $Vi++) {
if ($VArrayApple[$Vi] == "BEGIN:VCARD")
$VContatoApple = new stdClass();
if ($VArrayApple[$Vi] != "BEGIN:VCARD" && $VArrayApple[$Vi] != "VERSION:3.0") {
if ($VArrayApple[$Vi] != "END:VCARD") {
$VAtributo = isset(explode(":", $VArrayApple[$Vi])[0]) ? explode(":", $VArrayApple[$Vi])[0] : "";
$VValor = isset(explode(":", $VArrayApple[$Vi])[1]) ? explode(":", $VArrayApple[$Vi])[1] : "";
$VContatoApple->{$VAtributo} = $VValor;
} else
$VAContatosApple[] = $VContatoApple;
}
}
foreach ($VAContatosApple as $value) {
var_dump($value);
}