I'm trying to transform a directory url in a tree using jstree. Based on this post: Need help formatting results of a directory listing in PHP, javascript tree control by #hek2mgl, I got something like in the screenshot:. My problem is that it isn't showing the name of my directories, it just shows me the name of the files that I have inside the directory but not the name of the directory.
My php function is quite the same that #hek2mgl's post:
file: dir2json.php
header("Content-Type: application/json");
echo json_encode(dir_to_jstree_array("/var/www/html/images"));
function dir_to_jstree_array($dir, $order = "a", $ext = array()) {
if(empty($ext)) {
$ext = array (
"jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif", "ico", "xcf", "gif87", "scr"
);
}
$listDir = array(
'data' => basename($dir),
'attr' => array (
'rel' => 'folder'
),
'metadata' => array (
'id' => $dir
),
'children' => array()
);
$files = array();
$dirs = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != "..") {
if(is_file($dir."/".$sub)) {
$extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
if(in_array($extension, $ext)) {
$files []= $sub;
}
}
elseif (is_dir($dir."/".$sub)) {
$dirs []= $dir."/".$sub;
}
}
}
if($order === "a") {
asort($dirs);
}
else {
arsort($dirs);
}
foreach($dirs as $d) {
$listDir['children'][]= dir_to_jstree_array($d);
}
if($order === "a") {
asort($files);
}
else {
arsort($files);
}
foreach($files as $file) {
$listDir['children'][]= $file;
}
closedir($handler);
}
return $listDir;
}
The json returned from this dir2json.php is:
{"data":"images","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images"},"children":[{"data":".xvpics","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/.xvpics"},"children":["fundo2.jpg","mha1.gif","mha2.gif","the777.gif"]},{"data":"tree_20x20","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_20x20"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tree_25x25","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_25x25"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tree_30x30","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30"},"children":[{"data":".xvpics","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30\/.xvpics"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tst","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30\/tst"},"children":["conv.scr","tree_h.gif","tree_h.gif87","tree_h.png","tree_h.xcf","tree_l.gif","tree_l.png","tree_l.xcf","tree_t+-.gif","tree_t+-.xcf","tree_t+.gif","tree_t+.png","tree_t+.xcf","tree_t-.gif","tree_t-.png","tree_t-.xcf","tree_t.gif","tree_t.png","tree_t.xcf","tree_v.gif","tree_v.png","tree_v.xcf"]},"tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},"asc.gif","back.gif","bg.gif","cygnus.ico","desc.gif","eud_owner.png","favicon.ico","fundo2.jpg","mha.ico","mha1.gif","mha1_14_06_2007.gif","mha1_t3.gif","mha1_t4.gif","mha2.gif","mha2.png","mha2_MURILO.gif","mha2_ORIGINAL.gif","show-calendar.gif","the777.gif","tree_h.gif","tree_h.png","tree_h.xcf","tree_l.gif","tree_l.png","tree_l.xcf","tree_t+-.gif","tree_t+-.xcf","tree_t+.gif","tree_t+.png","tree_t+.xcf","tree_t-.gif","tree_t-.png","tree_t-.xcf","tree_t.gif","tree_t.png","tree_t.xcf","tree_v.gif","tree_v.png","tree_v.xcf"]}
And my php function that load javascript is:
function load_js() {
echo ' <link rel="stylesheet" type="text/css" href="/css/jstree/dist/themes/default/style.min.css" />
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jstree/dist/jstree.min.js"></script>
<script type="text/javascript">
function on_load_padrao() {
$(\'#jstree_demo_div\').jstree({
\'core\' : {
\'data\' : {
\'type\' : "POST",
\'url\' : \'mypath/dir2json.php\',
\'data\' : function (node) {
return { \'id\' : node["id"]};
}
},
\'dataType\' : \'json\'
},
\'plugins\' : ["checkbox" ]
});
}
</script> ';
}
I'd like to have this result:
What am I missing?
I found what I was doing wrong, the sctructure of array (that I was building JSON) was wrong.
I was doing this:
$listDir = array(
'data' => basename($dir),
'attr' => array (
'rel' => 'folder'
),
'metadata' => array (
'id' => $dir
),
'children' => array()
);
But the correct structure (in version 3.0 of jstree) is:
$listDir = array(
'id' => basename($dir),
'text' => basename($dir),
'children' => array()
);
So, my php file (dir2json.php) looks like this:
header("Content-Type: application/json");
echo json_encode(dir_to_jstree_array("/var/www/html/images"));
function dir_to_jstree_array($dir, $order = "a", $ext = array()) {
if(empty($ext)) {
$ext = array (
"jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif", "ico", "xcf", "gif87", "scr"
);
}
$listDir = array(
'id' => basename($dir),
'text' => basename($dir),
'children' => array()
);
$files = array();
$dirs = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != "..") {
if(is_file($dir."/".$sub)) {
$extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
if(in_array($extension, $ext)) {
$files []= $sub;
}
}
elseif (is_dir($dir."/".$sub)) {
$dirs []= $dir."/".$sub;
}
}
}
if($order === "a") {
asort($dirs);
}
else {
arsort($dirs);
}
foreach($dirs as $d) {
$listDir['children'][]= dir_to_jstree_array($d);
}
if($order === "a") {
asort($files);
}
else {
arsort($files);
}
foreach($files as $file) {
$listDir['children'][]= $file;
}
closedir($handler);
}
return $listDir;
}
for add icon to your file
you can use this code :
last code :
foreach($files as $file) {
$listDir['children'][]= $file;
}
new code :
foreach($files as $file) {
$exten = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($exten, $ext)) {
$icon = '';
if($exten == 'jpg' or $exten == 'png' or $exten == 'jpeg' or $exten == 'gif' or $exten == 'ico'){
$icon = 'fa fa fa-file-image-o';
}// end if
if($exten == 'doc' or $exten == 'docx'){
$icon = 'fa fa-file-word-o';
}
if ($exten == 'txt'){
$icon = 'fa fa-file-text-o';
}
if ($exten == 'pdf'){
$icon = 'fa fa-file-pdf-o';
}
if ($exten == 'xls'){
$icon = 'fa fa-file-excel-o';
}
if ($exten == 'zip'){
$icon = 'fa fa-file-archive-o';
}
}
$listDir['children'][]= array('id' => $dir.'/'.$file , 'text' => $file , 'icon' => $icon);
}
Related
Using Wordpress, I'm attempting to access files from one out of two file inputs using $_FILES but running into some problems:
To outline - I'm using a front-end form that has two file fields, both of which accept multiple files:
<form id="form" action="" method="post">
<input type="text" name="my_name">
<input type="file" name="reference_images[]" multiple>
<input type="file" name="photo_of_area[]" multiple>
</form>
The file inputs will be taking images, and I need to upload images from "reference_images" to one repeater field, ad "photo_of_area" to another repeater field. This form is posted via AJAX using FormData - the functions for this are below:
function saveForm(varform) {
blockUI();
jQuery.ajax({
type: "POST",
url: window.ajaxObject.ajaxUrl,
dataType: "JSON",
data: varform,
processData: false,
contentType: false,
cache: false,
success: onSuccesPing(),
crossDomain:true,
});
}
jQuery('#form').submit(function(event) {
event.preventDefault(); // Prevent form submitting as normal
var formData = new FormData(jQuery('#form')[0]);
formData.append("action", "messaging_post");
saveForm(formData);
});
I then have a function handle the messaging_post action which is below, this creates a new post with the form data, and loops over the attached images and injects them to my ACF repeater:
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
add_action('wp_ajax_nopriv_messaging_post', 'messaging_post');
function messaging_post(){
if(isset($_POST['my_name'])) {
$name = sanitize_text_field($_POST['my_name']);
$new_post = array(
'ID' => '',
'post_type' => 'quote_requests',
'post_status' => 'publish',
'post_title' => $title,
'post_content' => '',
);
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
update_field('name', $name, $post_id); // Updates the ACF text field 'name' for the inserted post
// Works, but uploads files from BOTH file inputs to the single ACF repeater:
foreach($_FILES as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post_id);
}
}
The above works, and populates the created post with the name from the form, but this attaches files from BOTH the reference_images and photo_of_area to the photo_area ACF repeater.
When trying to access $_FILES using a function such as the following:
foreach($_FILES["photo_of_area"] as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post);
This doesn't seem to work and returns nothing.
I'm assuming that after going through FormData(), the files are now not accessible on the normal $_FILES['name_of_input'], and should rather have something else done with them?
I've also tried just appending the images to the FormData, but seemed to be having the same issue.
Would anyone be able to shed some light on how I could access $_FILES["photo_of_area"], and also $_FILES["reference_images"] independently of each other after being passed through FormData()? Or any alternative ways that I should look at to achieve the desired behaviour.
Ideally, I need to access images from each file input respectively.
Thanks!
I've managed to achieve this by changing my loop over the $_FILES array as such:
$photo_of_area = $_FILES["photo_of_area"];
foreach ($photo_of_area['name'] as $key => $value) {
$errors = array();
$file_name = $photo_of_area['name'][$key];
$file_size = $photo_of_area['size'][$key];
$file_tmp = $photo_of_area['tmp_name'][$key];
$file_type = $photo_of_area['type'][$key];
$file_ext = strtolower(end(explode('.',$photo_of_area['name'][$key])));
if (empty($errors) == true) {
$wordpress_upload_dir = wp_upload_dir();
$upload_dir_path = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $upload_dir_path.$file_name);
} else {
print_r($errors);
}
$file_name_and_location = $upload_dir_path.$file_name;
$file_title_for_media_library = $photo_of_area['name'][$key];
$fildename = $photo_of_area['name'][$key];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$area_photos_array[] = array("image" => $attach_id);
}
update_field('photo_area', $area_photos_array, $post_id);
This successfully injects each image uploaded to a new row of the photo_area repeater inside the current post specified by $post_id.
I tried to translate the site to php7.0 and I have a login system and registration when I press the buttons gives an error
<br />
Notice: Array to string conversion in /var/www/html/new/lib/class/class.ajax.php on line 252
Notice: Undefined property: ajax::$Array in /var/www/html/new/lib/class/class.ajax.php on line 252
Fatal error: Uncaught Error: Function name must be a string in /var/www/html/new/lib/class/class.ajax.php:252
Stack trace:
0 {main}
My code :
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start(); // запуск сессии
date_default_timezone_set('Europe/Moscow'); //выбор временного региона Москва
require_once 'class.auth.php';
// принятие данных с ajax запросов
include_once('db.php');
require_once 'class.mix.php';
//$servers = new MixServers();
// если человек онлайн обновление информации
class ajax
{
public $ip;
protected $OOP_auth;
protected $OOP_mix;
public function __construct() {
$this->OOP_auth = new Authorization();
$this->OOP_mix = new MixServers();
if ( isset($_SESSION['auth']) )
{
$this->OOP_auth->online($_SESSION['auth']);
$this->OOP_mix->id_player = $_SESSION['auth'];
}
}
public function __destruct()
{
$this->OOP_auth = null;
$this->OOP_mix = null;
}
public function login($array)
{
//print_r($array);
// функция проверка отправленых данных
if ( isset($array['Username']) && isset($array['psw']) && $array['psw'] != '' && $array['Username'] != '' )
{
if ( isset($array['remembe']) && ($array['remembe'] == "true") )
{
SetCookie("remember",'1',time()+604800,'/');
SetCookie("login", $array['Username'],time()+604800,'/');
SetCookie("password",md5($array['psw']),time()+604800,'/');
}
else
{
SetCookie("remember",'0',time()+604800,'/');
}
$this->OOP_auth->login($array['Username'], $array['psw']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при вводе");
return json_encode($answer);
}
else
{
return json_encode(array('status' => false, 'message' => 'Логин или пароль не введены'));
}
}
public function registration($array)
{
if ( isset($array['reg_login'])
and isset($array['reg_password'])
and isset($array['reg_password1'])
and $array['reg_password'] === $array['reg_password1']
and 3 < mb_strlen($array['reg_login'], 'utf-8')
and 3 < mb_strlen($array['reg_password'], 'utf-8')
and 3 < mb_strlen($array['reg_password1'], 'utf-8') )
{
$this->OOP_auth->pre_registration($this->ip, $array['reg_login'], $array['reg_password']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы уже зарегистрированны");
return json_encode($answer);
}
else
{
return json_encode(array('status' => false, 'message' => 'Логин или пароль не введены или введены неправильно'));
}
}
public function check_reg($array)
{
$this->OOP_auth->check_reg($this->ip) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы еще не зашли на сервер");
return json_encode($answer);
}
public function in_login($array)
{
$this->OOP_auth->loginIP($this->ip) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при входе");
return json_encode($answer);
}
public function unlogin($array)
{
$this->OOP_auth->unlogin($_SESSION['auth']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при выходе");
if ($answer['status'])
{
SetCookie("login", "", time() - 3600,'/');
SetCookie("password","", time() - 3600,'/');
}
return json_encode($answer);
}
public function change_country($array)
{
$DATA = $this->OOP_mix->free_servers("sity", $array['add_mix_country']);
$option = "";
if (isset($DATA['mix_sity']))
{
foreach ($DATA['mix_sity'] as $key => $value)
{
$option .= "<option value=\"" . $DATA['mix_sity'][$key]['name'] . "\">" . $DATA['mix_sity'][$key]['name'] . "</option>";
}
}
return $option;
}
public function create_mix($array)
{
if ( isset($array['name']) && isset($array['country']) && isset($array['sity']) && isset($array['map']) && 3 < mb_strlen($array['name'], 'utf-8') && 40 > mb_strlen($array['name'], 'utf-8'))
{
$this->OOP_mix->create_mix_server($_POST['name'], $_POST['country'], $_POST['sity'], $_POST['map']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при создании микса");
}
else
{
$answer = array("status" => false, "message" => "Ошибка при вводе данных");
}
return json_encode($answer);
}
public function ajax_mixs_free()
{
if (isset($_SESSION['auth']))
{
$answer['message'] = $this->OOP_mix->get_info_all_servers();
}
return $answer['message']['free_servers'];
}
public function join_team($array)
{
if ( isset($_SESSION['auth']) && (int) $array['team'] > 0 && (int) $array['team'] < 3)
{
if ($this->OOP_mix->check_player())
{
$this->OOP_mix->join_team((int) $array['team']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Все слоты заняты");
}
else
{
$answer = array("status" => false, "message" => "Вы не на миксе");
}
}
else
{
$answer = array("status" => false, "message" => "Ошибка при выборе команды");
}
return json_encode($answer);
}
public function message_mix($array)
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->messeges_send($array['text']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Проблемы с текстом");
}
else
{
$answer = array("status" => false, "message" => "Авторизируйтес на сайте");
}
return json_encode($answer);
}
public function update_chat($array)
{
if (isset($_SESSION['auth']) && isset($array['id']))
{
if ($answer = $this->OOP_mix->messeges_get($array['id'])) $answer['status'] = true;
}
else
{
$answer = array("status" => false, "message" => "Авторизируйтес на сайте");
}
return json_encode($answer);
}
public function exit_mix()
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->exit_on_server() ? $answer['status'] = true : $answer = array("status" => false, "message" => "Этого не может быть");
}
return json_encode($answer);
}
public function select_mix($array)
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->set_on_mix($array['val']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Не правильный id");
}
else
{
$answer = array("status" => false, "message" => "Авторизация закончилась");
}
return json_encode($answer);
}
public function back_to_mixs()
{
if (isset($_SESSION['auth']))
{
if ($this->OOP_mix->check_player())
{
$this->OOP_mix->back_to_mixs() ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы не можете выйти так как являетесь игроком сервера");
}
else
{
$answer = array("status" => true, "message" => "Все ваши игры завершены");
}
}
else
{
$answer = array("status" => false, "message" => "Авторизация закончилась");
}
return json_encode($answer);
}
}
if ( isset($_POST['url']) && $_POST['url'] != '' )
{
$OOPajax = new ajax();
if(isset($_SERVER['HTTP_CF_CONNECTING_IP']))
{
$OOPajax->ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
else
{
$OOPajax->ip = $_SERVER['REMOTE_ADDR'];
}
if ( method_exists($OOPajax, $_POST['url']) )
{
$answer = $OOPajax->$_POST['url']($_POST);
}
else
{
$answer = json_encode(array("status" => false, "message" => "Не наебешь"));
}
}
else
{
$answer = json_encode(array("status" => false, "message" => "Пошел на хуй"));
}
echo $answer;
/*
// Выход с сайта - обнуление кукки
if ( isset($_POST['set']) && ($_POST['set'] == 'unlogin') )
{
SetCookie("login", "", time() - 3600,'/');
SetCookie("password","", time() - 3600,'/');
}
// Авторизация
if (isset($_POST['set']) && ($_POST['set'] == 'login') && isset($_POST['Username']) && isset($_POST['psw']))
{
// авторизация
if ( isset($_POST['remembe']) && ($_POST['remembe'] == "true") )
{
SetCookie("remember",'1',time()+604800,'/');
SetCookie("login", $_POST['Username'],time()+604800,'/');
SetCookie("password",md5($_POST['psw']),time()+604800,'/');
}
else
{
SetCookie("remember",'0',time()+604800,'/');
}
if ($authorization->login($_POST['Username'], $_POST['psw'])) echo 'true';
}
// Регистрация
if ( isset($_POST['reg_login']) && isset($_POST['reg_password']) && isset($_POST['reg_password1']) && ( $_POST['reg_password'] === $_POST['reg_password1'] ) )
{
if ( $authorization->pre_registration($ip, $_POST['reg_login'], $_POST['reg_password']) ) echo 'true';
}
// Выход с сайта
if ( isset($_POST['set']) && ($_POST['set'] == 'unlogin') )
{
if ( $authorization->unlogin($_SESSION['auth']) ) echo 'true';
}
// обновление микса
if ( isset($_POST['set']) && ($_POST['set'] == 'info_mix') )
{
echo $servers->info_mix_server();
}
// обновление списка миксов
if ( isset($_POST['set']) && ($_POST['set'] == 'info_mixs') )
{
echo $servers->info_mix_servers();
}
// Получение списка городов в стране
if ( isset($_POST['add_mix_country']) && ($_POST['add_mix_country'] != '') )
{
$DATA = $servers->free_servers("sity", $_POST['add_mix_country']);
foreach ($DATA['mix_sity'] as $key => $value)
{
echo "<option value=\"" . $DATA['mix_sity'][$key]['name'] . "\">" . $DATA['mix_sity'][$key]['name'] . "</option>";
}
}
// Создание микса
if ( isset($_POST['set']) && ($_POST['set'] == 'create_mix') && isset($_POST['name']) && isset($_POST['country']) && isset($_POST['sity']) && isset($_POST['map']) && isset($_POST['password']))
{
if ($servers->create_mix_server($_POST['name'], $_POST['country'], $_POST['sity'], $_POST['map'], $_POST['password'])) echo "true";
}
// Вход на микс
if ( isset($_POST['set']) && ($_POST['set'] == 'select_mix') && isset($_POST['val']) && isset($_POST['pass']))
{
if($servers->set_on_mix($_POST['val'], $_POST['pass'])) echo "true";
}
// Вход на сервер
if ( isset($_POST['set']) && ($_POST['set'] == 'select_server') && isset($_POST['val']))
{
if($servers->set_on_server($_POST['val'])) echo "true";
}
// Выход с микса
if ( isset($_POST['set']) && ($_POST['set'] == 'exit_mix') )
{
if ($servers->exit_on_server()) echo "true";
}
*/
?>
PHP 7 introduced some backward incompatible changes, including the evaluation of indirect expressions. You need to change the line:
$answer = $OOPajax->$_POST['url']($_POST);
to this:
$answer = $OOPajax->{$_POST['url']}($_POST);
to get the old PHP 5 behaviour.
The manual lists other expressions that were affected by this change here: http://php.net/manual/en/migration70.incompatible.php (see the "Changes to variable handling" section).
I have used dropzone js to upload multiple image.
My code looks like below.
var s_currency = $('select[name="currency"]');
Dropzone.autoDiscover = false;
if($('#dropzoneDragArea').length > 0){
var expenseDropzone = new Dropzone("#expense-form", {
autoProcessQueue: false,
clickable: '#dropzoneDragArea',
acceptedFiles:allowed_files,
previewsContainer: '.dropzone-previews',
addRemoveLinks: true,
//maxFiles: 1,
//parallelUploads: 1,
uploadMultiple: true,
dictDefaultMessage:drop_files_here_to_upload,
dictFallbackMessage:browser_not_support_drag_and_drop,
dictRemoveFile:remove_file,
dictMaxFilesExceeded:you_can_not_upload_any_more_files,
error:function(file,response){
alert_float('danger',response);
},
success:function(file,response){
response = $.parseJSON(response);
this.options.autoProcessQueue = true;
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
window.location.assign(response.url);
}
},
});
}
$(document).ready(function(){
_validate_form($('form'),{category:'required',date:'required',amount:'required',currency:'required'},expenseSubmitHandler);
$('input[name="billable"]').on('change',function(){
do_billable_checkbox();
});
});
function expenseSubmitHandler(form){
s_currency.removeAttr('disabled');
$('input[name="billable"]').prop('disabled',false);
$.post(form.action, $(form).serialize()).success(function(response) {
response = $.parseJSON(response);
if (response.expenseid) {
if(typeof(expenseDropzone) !== 'undefined'){
//console.log(expenseDropzone.getQueuedFiles().length);return;
if (expenseDropzone.getQueuedFiles().length > 0) {
expenseDropzone.options.url = admin_url + 'expenses/add_expense_attachment/' + response.expenseid;
expenseDropzone.processQueue();
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
});
return false;
}
<form action="http://127.0.0.1/perfex_crm_aug_25/admin/expenses/expense" id="expense-form" class="dropzone dropzone-manual" enctype="multipart/form-data" method="post" accept-charset="utf-8" novalidate="novalidate">
<div id="dropzoneDragArea" class="dz-default dz-message">
<span>Attach file here</span>
</div>
<div class="dropzone-previews"></div>
<button type="submit" class="btn btn-info pull-right mtop15">Submit</button>
</form>
My controler looks like this :
public function expense($id = '')
{
if (!has_permission('expenses', '', 'view')) {
access_denied('expenses');
}
if ($this->input->post()) {
if ($id == '') {
if (!has_permission('expenses', '', 'create')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
}
$id = $this->expenses_model->add($this->input->post());
if ($id) {
set_alert('success', _l('added_successfuly', _l('expense')));
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
} else {
if (!has_permission('expenses', '', 'edit')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense/' . $id)
));
die;
}
$success = $this->expenses_model->update($this->input->post(), $id);
if ($success) {
set_alert('success', _l('updated_successfuly', _l('expense')));
}
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
}
if ($id == '') {
$title = _l('add_new', _l('expense_lowercase'));
} else {
$data['expense'] = $this->expenses_model->get($id);
$title = _l('edit', _l('expense_lowercase'));
//echo "<pre>";
//print_r($data['expense']);
}
if($this->input->get('customer_id')){
$data['customer_id'] = $this->input->get('customer_id');
$data['do_not_auto_toggle'] = true;
}
$this->load->model('taxes_model');
$this->load->model('payment_modes_model');
$this->load->model('currencies_model');
$this->load->model('projects_model');
$data['customers'] = $this->clients_model->get();
$data['taxes'] = $this->taxes_model->get();
$data['categories'] = $this->expenses_model->get_category();
$data['supplier'] = $this->expenses_model->get_supplier();
//print_r($data['supplier']);
$data['payment_modes'] = $this->payment_modes_model->get();
$data['currencies'] = $this->currencies_model->get();
$data['title'] = $title;
$this->load->view('admin/expenses/expense', $data);
}
I have also created helper for uploading image. That function looks like below :
function handle_lead_attachments($leadid)
{
if(isset($_FILES['file']) && _perfex_upload_error($_FILES['file']['error'])){
header('HTTP/1.0 400 Bad error');
echo _perfex_upload_error($_FILES['file']['error']);
die;
}
$CI =& get_instance();
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
do_action('before_upload_lead_attachment',$leadid);
$path = LEAD_ATTACHMENTS_FOLDER . $leadid . '/';
// Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'];
// Make sure we have a filepath
if (!empty($tmpFilePath) && $tmpFilePath != '') {
// Setup our new file path
if (!file_exists($path)) {
mkdir($path);
fopen($path . 'index.html', 'w');
}
$filename = unique_filename($path, $_FILES["file"]["name"]);
$newFilePath = $path . $filename;
// Upload the file into the company uploads dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$CI->db->insert('tblleadattachments', array(
'leadid' => $leadid,
'file_name' => $filename,
'filetype' => $_FILES["file"]["type"],
'addedfrom' => get_staff_user_id(),
'dateadded' => date('Y-m-d H:i:s')
));
$CI->load->model('leads_model');
$CI->leads_model->log_lead_activity($leadid, 'not_lead_activity_added_attachment');
return true;
}
}
}
return false;
}
Here, when I have upload one image than its working fine.But when I have tried to upload multiple image than it store other data image column has pass null value.
So what should I have to change in My code to upload multiple image. I have used perfex-crm project. I have to modify its expence module.
i´m not getting run my application, i select the city then i need that the dropdown show the NEIGHBORHOODS associated with the city....
this is my getNeighborhoods:
public function pegarBairros ($cidades = null) {
$this->layout = 'json';
$result = array();
debug($_REQUEST['cidade']);
if (in_array($_REQUEST['cidade'], array_keys($this->cidades))) {
$bairros = $this->Cep->find('list', array('fields' => array('id', 'bairro'), 'conditions' => array('uf_sigla' => 'sp', 'cidade' => $this->cidades[$_REQUEST['cidade']]), 'order' => 'bairro', 'group' => 'bairro'));
sort($bairros);
foreach ($bairros as $id => $bairro)
if (!empty($bairro)) $result[$id] = $bairro;
} else $result[] = 'error';
$this->set('data', $result);
}
and this is my ajax:
$('#ImovelCidade').change(function(e) {
$('#ImovelBairro').html($('<option />').val('').text('Carregando...'));
$.getJSON(
"<?php echo Router::url(array('controller' => 'pages', 'action' => 'pegarBairros')) ?>",
{ "cidade" : $(this).val() },
function (data) {
$('#ImovelBairro').html($('<option />').val('').text('Selecione'));
$.each(data, function (chave, valor) {
$('#ImovelBairro').append($('<option />').val(chave).text(valor));
} );
}
);
});
this ajax call the function getNeigh...
this is my select city:
echo $this->Form->input('cidade', array('label' => 'Cidade', 'empty' => 'Selecione uma cidade', 'options' => $Cidades));
my before filter that received city:
public function beforeFilter() {
$this->loadModel('Cidade');
$this->cidade = $this->Cidade->find('list', array ('fields' => array('id','nome')));
$this->set('Cidades',$this->cidade);
<?php
// Edit this ->
define( 'MQ_SERVER_ADDR', 'XX.XXX.XXX.XXX' );
define( 'MQ_SERVER_PORT', 25565 );
define( 'MQ_TIMEOUT', 1 );
// Edit this <-
// Display everything in browser, because some people can't look in logs for errors
Error_Reporting( E_ALL | E_STRICT );
Ini_Set( 'display_errors', true );
require __DIR__ . '/status/MinecraftQuery.class.php';
$Timer = MicroTime( true );
$Query = new MinecraftQuery( );
try
{
$Query->Connect( MQ_SERVER_ADDR, MQ_SERVER_PORT, MQ_TIMEOUT );
}
catch( MinecraftQueryException $e )
{
$Exception = $e;
}
$Timer = Number_Format( MicroTime( true ) - $Timer, 4, '.', '' );
?>
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<div class="spanx"><p>
<h1>Login</h1>
Username:<br />
<input type="text" name="username" style="height: 30px; style="width: 220px; value="" />
<br/>
<button>Submit</button>
<?php // Example from PHP.net
$string = '<?php if( ( $Players = $Query->GetPlayers( ) ) !== false ): ?>
<?php foreach( $Players as $Player ): ?>';
if(stristr($string, 'Thisshouldbethestringfromthetextbox') === FALSE) {
echo 'Player is not online';
}
?>
Is my code. Basically what I am trying to do is query my Minecraft server. Check if a player is online by the text form on button click, and if not, deliver a message that says the player is not online, otherwise, keep the person logged in as they browse the site (dunno how to do this either...)
The external query file is:
<?php
class MinecraftQueryException extends Exception
{
// Exception thrown by MinecraftQuery class
}
class MinecraftQuery
{
/*
* Class written by xPaw
*
* Website: http://xpaw.ru
* GitHub: https://github.com/xPaw/PHP-Minecraft-Query
*/
const STATISTIC = 0x00;
const HANDSHAKE = 0x09;
private $Socket;
private $Players;
private $Info;
public function Connect( $Ip, $Port = 25565, $Timeout = 3 )
{
if( !is_int( $Timeout ) || $Timeout < 0 )
{
throw new InvalidArgumentException( 'Timeout must be an integer.' );
}
$this->Socket = #FSockOpen( 'udp://' . $Ip, (int)$Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $this->Socket === false )
{
throw new MinecraftQueryException( 'Could not create socket: ' . $ErrStr );
}
Stream_Set_Timeout( $this->Socket, $Timeout );
Stream_Set_Blocking( $this->Socket, true );
try
{
$Challenge = $this->GetChallenge( );
$this->GetStatus( $Challenge );
}
// We catch this because we want to close the socket, not very elegant
catch( MinecraftQueryException $e )
{
FClose( $this->Socket );
throw new MinecraftQueryException( $e->getMessage( ) );
}
FClose( $this->Socket );
}
public function GetInfo( )
{
return isset( $this->Info ) ? $this->Info : false;
}
public function GetPlayers( )
{
return isset( $this->Players ) ? $this->Players : false;
}
private function GetChallenge( )
{
$Data = $this->WriteData( self :: HANDSHAKE );
if( $Data === false )
{
throw new MinecraftQueryException( 'Offline' );
}
return Pack( 'N', $Data );
}
private function GetStatus( $Challenge )
{
$Data = $this->WriteData( self :: STATISTIC, $Challenge . Pack( 'c*', 0x00, 0x00, 0x00, 0x00 ) );
if( !$Data )
{
throw new MinecraftQueryException( 'Failed to receive status.' );
}
$Last = '';
$Info = Array( );
$Data = SubStr( $Data, 11 ); // splitnum + 2 int
$Data = Explode( "\x00\x00\x01player_\x00\x00", $Data );
if( Count( $Data ) !== 2 )
{
throw new MinecraftQueryException( 'Failed to parse server\'s response.' );
}
$Players = SubStr( $Data[ 1 ], 0, -2 );
$Data = Explode( "\x00", $Data[ 0 ] );
// Array with known keys in order to validate the result
// It can happen that server sends custom strings containing bad things (who can know!)
$Keys = Array(
'hostname' => 'HostName',
'gametype' => 'GameType',
'version' => 'Version',
'plugins' => 'Plugins',
'map' => 'Map',
'numplayers' => 'Players',
'maxplayers' => 'MaxPlayers',
'hostport' => 'HostPort',
'hostip' => 'HostIp'
);
foreach( $Data as $Key => $Value )
{
if( ~$Key & 1 )
{
if( !Array_Key_Exists( $Value, $Keys ) )
{
$Last = false;
continue;
}
$Last = $Keys[ $Value ];
$Info[ $Last ] = '';
}
else if( $Last != false )
{
$Info[ $Last ] = $Value;
}
}
// Ints
$Info[ 'Players' ] = IntVal( $Info[ 'Players' ] );
$Info[ 'MaxPlayers' ] = IntVal( $Info[ 'MaxPlayers' ] );
$Info[ 'HostPort' ] = IntVal( $Info[ 'HostPort' ] );
// Parse "plugins", if any
if( $Info[ 'Plugins' ] )
{
$Data = Explode( ": ", $Info[ 'Plugins' ], 2 );
$Info[ 'RawPlugins' ] = $Info[ 'Plugins' ];
$Info[ 'Software' ] = $Data[ 0 ];
if( Count( $Data ) == 2 )
{
$Info[ 'Plugins' ] = Explode( "; ", $Data[ 1 ] );
}
}
else
{
$Info[ 'Software' ] = 'Vanilla';
}
$this->Info = $Info;
if( $Players )
{
$this->Players = Explode( "\x00", $Players );
}
}
private function WriteData( $Command, $Append = "" )
{
$Command = Pack( 'c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04 ) . $Append;
$Length = StrLen( $Command );
if( $Length !== FWrite( $this->Socket, $Command, $Length ) )
{
throw new MinecraftQueryException( "Failed to write on socket." );
}
$Data = FRead( $this->Socket, 2048 );
if( $Data === false )
{
throw new MinecraftQueryException( "Failed to read from socket." );
}
if( StrLen( $Data ) < 5 || $Data[ 0 ] != $Command[ 2 ] )
{
return false;
}
return SubStr( $Data, 5 );
}
}
I would like to solve this in any way that I can. Thanks in advance and ask any questions you need :D.
You can create a form pointing to the same URL to accomplish that.
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
Username: <input type="text" name="username" />
<button type="submit">Send</button>
</form>
When the form is sent, you can access your input content by accessing $_POST['username']
if (isset($_POST['username'])) {
// your code here
echo 'Username: ' . $_POST['username'];
}