Jump to content

Kirasiris

Members
  • Content count

    10
  • Joined

  • Last visited

Community Reputation

0 Neutral

About Kirasiris

  • Rank
    Member
  1. Kirasiris

    Help on Facebook Friendship System in CodeIgniter

    Yes, that's the actual problem. I'm trying to create a system in which both users should acknowledge the friendship between them but so far I can not figure out the proper way to implement it. I know it may be a bit complex but should it not be possible by just making a X user update an specific row without having to create another relationship? I mean your suggested task (the second one; "set the follow request from User B -> User A as accepted") requires me to create a function to set the request from User B to accepted and that should work as I want.... but it is not what I just tried to create with the code in my post? I mean it verifies if there's a relationship coming from you or X user and it should update it!. according to the function...
  2. I'm working with a relationship table: id (AI), user_id, friend_id, status, type. The current behavior is that the Logged In user can send friendship requests to X user but if there is already a friendship request coming from the X user to the Logged In user; the logged in user instead of sending a new request to X user, he/she should accept the one that is already in the database(which is coming from the X-user). Here is an image of what I'm talking about(in the image, the status column displays 'accepted' but try to imagine it as it was 'pending', please) : So I currently have a function for adding friends for the current Logged-In user and it goes like this: public function follow($username){ // Check Login if(!$this->session->userdata('user_id')){ // Redirect to page redirect('users/login'); } // Get item $item = $this->User_model->get_username($username); // Already friends? $friendship = $this->User_model->the_relationship($item->id); if ($friendship->status == 'accepted' || $friendship->status == 'pending') { // Create Message $this->session->set_flashdata('error', 'You are already following this user.'); // Redirect to pages redirect('users/profile/'.$item->username); // BEGINNING OF - HERE IS WHERE THE PROBLEM IS } elseif($friendship->status == 'pending'){ // Get item $item = $this->User_model->get_username($username); // Page Data $data = array( 'user_id' => $item->id, 'friend_id' => $this->session->userdata('user_id'), 'status' => 'accepted', ); $this->User_model->updateFriendship($item->id, $data); /// END OF - HERE IS WHERE THE PROBLEM IS } else { // Get item $item = $this->User_model->get_username($username); // Page Data $data = array( 'user_id' => $this->session->userdata('user_id'), 'friend_id' => $item->id, 'status' => 'pending', 'type' => 'friendship', ); $this->Relationship_model->add($data); // Activity Array $data = array( 'resource_id' => $this->db->insert_id(), 'type' => 'friendship', 'action' => 'sent', 'user_id' => $this->session->userdata('user_id'), 'message' => '(' . $this->session->userdata('username') . ') sent a friend request to ('.$item->username.') ', ); // Insert Activity $this->Activity_model->add($data); // Set Message $this->session->set_flashdata('success', 'Friend request has been sent'); // Redirect redirect('users/profile/'.$item->username); } } and here are the two functions in the model which check the current status of the relationship between the current logged in user and the X user; the second function should update the status of the friendship if there is already one: LEGEND: $this->relationship: ci_relationship table $this->type: friendship type // Relationship for single public function the_relationship($id){ $this->db->select('*'); $this->db->from($this->relationship); $this->db->where('user_id', $this->session->userdata('user_id')); $this->db->where('friend_id', $id); $this->db->where('type', $this->type); $query = $this->db->get(); if($query->num_rows() >= 1){ return $query->row(); } else { return false; } } // Update Friendship Status public function updateFriendship($id, $data){ $this->db->where('user_id', $id); $this->db->where('friend_id', $this->session->userdata('user_id')); //$this->db->where('status', 'pending'); $this->db->where('type', $this->type); $this->db->update($this->relationship, $data); } I hope I could make myself clear. Thanks in advance.
  3. FIRST OF ALL , THIS POST IS GOING TO BE LONG. Thanks for helping. Hello I'm trying to build an "really" advanced search page for my WordPress template. So far I have created the my page with the following code: <?php /* Template Name: Direcotorio Template Post Type: page */ ?> <?php get_header(); ?> <div class="container"> <div class="row"> <div id="my-adv-search"> <!-- Post Type --> <div class="col-md-3"> <div class="form-group"> <label for="q_post_type">Tipo</label> <select class="form-control" id="q_post_type"> <option selected>Selecciona una opcion</option> <?php $args = array( 'public' => true, '_builtin' => false, ); $post_types = get_post_types($args); foreach( $post_types as $post_type ) { echo '<option>' . $post_type . '</option>' ; } ?> </select> </div> </div> <!-- Genero --> <div class="col-md-3"> <div class="form-group"> <label for="q_taxonomy">Genero</label> <select class="form-control" multiple id="q_taxonomy"> <option value="any" selected>Selecciona una opcion</option> <?php $args = array( 'public' => true, '_builtin' => false ); $output = 'names'; // or objects $operator = 'and'; // 'and' or 'or' $taxonomies = get_taxonomies( $args, $output, $operator ); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { echo '<option>' . $taxonomy . '</option>'; } } ?> </select> </div> </div> <!-- Estado --> <div class="col-md-3"> <div class="form-group"> <label for="q_orderby">Estado</label> <select class="form-control" id="q_orderby"> <option value="any" selected>Selecciona una opcion</option> <?php foreach ( [ // 'author' => 'Author', // 'comment_count' => 'Popularity (# of Comments)', // 'year' => 'Year', 'en_emision' => 'Emision', 'en_final' => 'Finalizado', //'order' => 'ASC ? DESC', ] as $value => $label ) { printf( '<option value="%s">%s</option>', esc_attr( $value ), esc_html( $label ) ); } ?> </select> </div> </div> <!-- Year --> <div class="col-md-3"> <div class="form-group"> <label for="q_year">Año</label> <select class="form-control" id="q_year"> <option value="any" selected>Selecciona una opcion</option> <?php $args = array( 'public' => true, '_builtin' => false, 'type' => 'yearly', 'format' => 'option', ); wp_get_archives($args); ?> </select> </div> </div> <!-- Nonce field. --> <?php wp_nonce_field( 'my-adv-search', 'q_nonce' ); ?> <!-- Search Button --> <div class="col-md-12"> <input type="submit" class="btn btn-success" id="buscar_btn" value="Search"> <br><br> <noscript><b>Tu buscador no soporta Javascript, haciendo imposible mostrar los posts.</b></noscript> <div id="resultados"><div class="cargando_medio"></div></div> </div> </div><!-- End #my-adv-search --> </div> </div> <?php get_footer(); ?> <script type="text/javascript"> jQuery( function( $ ){ var ajaxurl = '/wptests/wp-admin/admin-ajax.php'; function searchPosts( btn ) { var _btn_text = btn.value;//, q_order; btn.disabled = true; btn.value = 'Searching..'; // q_order = $( '#q_order-asc' ).is( ':checked' ) ? // 'ASC' : 'DESC'; return $.post( ajaxurl, { action: 'my_adv_search', q_nonce: $( '#q_nonce' ).val(), q_post_type: $( '#q_post_type' ).val(), q_taxonomy: $( '#q_taxonomy' ).val(), q_year: $( '#q_year' ).val(), q_orderby: $( '#q_orderby' ).val(), // q_order: q_order, } ).done( function( s ){ if ( 'session_expired' === s ) { location.reload(); return; } $( '#resultados' ).html( s ); } ).always( function(){ btn.value = _btn_text; btn.disabled = false; } ); } $( '#buscar_btn', '#my-adv-search' ).on( 'click', function( e ){ e.preventDefault(); // Run AJAX search. searchPosts( this ); // Remove button focus. this.blur(); } ); } ); </script> Now I already have a function that works pretty well. I only need to make some changes on it but I have been unable to figure out why isn't working(as you will see there are few comments which I have made on it). I'm trying to display the posts by two meta values that comes from a custom field called "estado_de_video" and the two meta values from it are "en_emision and en_final". I pretty much I have everything done but I just don't know why is not working. Can somebody help me, please? Thanks in advanced. add_action( 'wp_ajax_my_adv_search', 'ajax_my_adv_search' ); add_action( 'wp_ajax_nopriv_my_adv_search', 'ajax_my_adv_search' ); function ajax_my_adv_search() { if ( ! check_ajax_referer( 'my-adv-search', 'q_nonce', false ) ) { echo 'session_expired'; wp_die(); } $post_type = isset( $_POST['q_post_type'] ) ? $_POST['q_post_type'] : ''; $taxonomy = isset( $_POST['q_taxonomy'] ) ? $_POST['q_taxonomy'] : []; $year = isset( $_POST['q_year'] ) ? $_POST['q_year'] : ''; $orderby = isset( $_POST['q_orderby'] ) ? $_POST['q_orderby'] : []; $order = isset( $_POST['q_order'] ) ? $_POST['q_order'] : ''; // Note that if $post_type is 'any', all post statuses will be included. In // that case, you may want to set specific post statuses below. $post_status = 'publish'; // by Taxonomy $taxonomy = array_filter( (array) $taxonomy ); if ( ! in_array( 'any', $taxonomy ) ) { $taxonomy = array_unique( array_map( 'trim', $taxonomy ) ); add_filter( 'posts_join', function( $c ) use ( $taxonomy ) { if ( ! empty( $taxonomy ) ) { global $wpdb; // 1 below is one/number and not the lowercase of L $c .= " INNER JOIN {$wpdb->term_relationships} AS ctr1 ON ctr1.object_id = {$wpdb->posts}.ID" . " INNER JOIN {$wpdb->term_taxonomy} AS ctt1 ON ctt1.term_taxonomy_id = ctr1.term_taxonomy_id"; } return $c; } ); add_filter( 'posts_where', function( $c ) use ( $taxonomy ) { if ( ! empty( $taxonomy ) ) { $tax_list = array_map( 'esc_sql', $taxonomy ); $tax_list = "'" . implode( "', '", $tax_list ) . "'"; // 1 below is one/number and not the lowercase of L $c .= " AND ( ctt1.taxonomy IN ($tax_list) )"; } return $c; } ); } // by Custom Field Value - Metadata $orderby = array_filter( (array) $orderby ); if ( in_array( 'any', $orderby ) ) { // Don't sort by post date. $orderby2 = false; } else { $orderby = array_unique( array_map( 'trim', $orderby ) ); // TRUE if we're sorting by year. $ob_year = false; foreach ( $orderby as $i => $s ) { // Sort posts by year. if ( 'year' === $s ) { $ob_year = true; unset( $orderby[ $i ] ); } //// HERE BEGINS // Sort posts by meta value en_emision from meta key estado_de_video. Note that this would only return // posts that have the custom field 'en_emision'. if ( 'en_emision' === $s ) { $meta_key = 'en_emision'; $orderby2 = 'meta_value'; unset( $orderby[ $i ] ); } // Sort posts by meta value en_final from meta key estado_de_video. Note that this would only return // posts that have the custom field 'en_final'. if ( 'en_final' === $s ) { $meta_key = 'en_final'; $orderby2 = 'meta_value'; unset( $orderby[ $i ] ); } //// HERE ENDS } add_filter( 'posts_orderby', function( $c, $q ) use ( $ob_year ) { if ( $ob_year ) { global $wpdb; // Use the value parsed by WP_Query. $order = $q->get( 'order' ); $c .= $c ? ', ' : ''; $c .= "YEAR({$wpdb->posts}.post_date) $order"; } return $c; }, 10, 2 ); $ok = isset( $orderby2 ); if ( ! $ok && empty( $orderby ) ) { // Don't sort by post date. $orderby2 = false; } elseif ( ! $ok ) { // Pass to WP_Query as a string. $orderby2 = implode( ' ', $orderby ); } } // by Year if ( ! is_numeric( $year ) ) { $year = ''; } $q = new WP_Query( [ 'post_status' => $post_status, 'post_type' => array($post_type), 'posts_per_page' => -1, 'post_parent' => 0, 'year' => $year, 'meta_key' => isset( $meta_key ) ? $meta_key : '', 'orderby' => $orderby2, 'order' => $order, ] ); if ( $q->have_posts() ) { echo '<ul>'; while ( $q->have_posts() ) { $q->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></li> <?php } echo '</ul>'; } else { echo '<div class="alert alert-danger">Ningun Resultado</div>'; } wp_die(); } vvv
  4. I'm sorry if did not explain myself clearly enough. What I want is to find a correct way to create a many-to-many relationship table as I'm building a CMS similar to WordPress(in fact I have those three tables exactly as the ones WordPress uses). I'm trying to build a simple blog system in which I need to display all the categories related to any single post and when clicking on them(on the categories) being able to redirect the user to a page displaying all the post which contain that specific category(the "clicked" one).. I don't know if I explained it better but in few words I'm just building a blog system exactly like WordPress. I already tried looking for tutorials, I tried doing pure php(obviously with my own data): $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); I just don't find a right answer for it. I mean I could easily do a one-to-many relationship table but that;s not exactly what I want... if you sir have a good idea about what I can do, I will greatly appreciate it. Thanks in advance.
  5. So I've been struggling with this for quite a while now and is already my last step to get done with my project(finally). The main problem is that I'm trying to create a many-to-many relationship between three tables that I have on my database. I'm attaching the table that I'm using on this post (ci_terms, ci_terms_taxonomy, ci_terms_relationship). So far the main code works great(the one for adding the post, which I will post the whole code after explaining what I'm trying to do). When adding a post everything works as I want except when I try to select the categories(not the selection itself); instead of submiting ONLY the SELECTED values, all values are being submitted even those which are not selected. Here are some pictures to clarify what I mean: then in the post appear all three(or more depending on the number of categories that I have created). I hope I could make myself clear. Thanks in advance. Here is the code that I'm using for the many-to-many relationship tables: <?php // Create many-to-many relationship ///////////////////////////// $taxonomy_list = $this->Terms_model->get_list(); foreach ( $taxonomy_list as $cat ){ //do insert here $data = array( 'term_taxonomy_id' => $this->db->insert_id(), 'term_id' => $cat->term_id, 'type' => 'category', ); } $this->Taxonomy_model->add($data); $data = array(); $relationship_list = $this->Taxonomy_model->get_list(); foreach ( $relationship_list as $rel ){ // Insert selected values $data[] = array( 'post_id' => $last_post_id, 'term_taxonomy_id' => $rel->term_taxonomy_id, 'term_order' => 0, ); } $this->db->insert_batch('ci_terms_relationship', $data); ?> and here is the full code I'm using for the addition of new posts(with the code above also): <?php public function add() { // Field Rules $this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]'); $this->form_validation->set_rules('body', 'Body', 'trim|required'); $this->form_validation->set_rules('status', 'Status', 'required'); $this->form_validation->set_rules('is_featured', 'Feature', 'required'); $this->form_validation->set_rules('is_commented', 'Comments', 'required'); $this->form_validation->set_rules('order', 'Order', 'integer'); if ($this->form_validation->run() == FALSE) { // Select Categories $categories_options = array(); $categories_options[0] = 'Select Categories'; $categories_list = $this->Terms_model->get_list(); foreach($categories_list as $cat){ $categories_options[$cat->term_id] = $cat->title; } $data['categories_options'] = $categories_options; // Select Post Author ID and Name $user_options = array(); $user_options[0] = 'Select Username ID'; $user_list = $this->User_model->get_list(); foreach($user_list as $username){ $user_options[$username->id] = $username->username; } $data['user_options'] = $user_options; // Load template $this->template->load('admin', 'default', 'posts/add', $data); } else { $slug = str_replace(' ', '-', $this->input->post('title')); $slug = strtolower($slug); // Upload Image $config['upload_path'] = 'assets/img/posts/'; $config['allowed_types'] = 'gif|jpg|png'; $config['encrypt_name'] = TRUE; $config['max_size'] = '2048'; $config['max_width'] = '2000'; $config['max_height'] = '2000'; $this->load->library('upload', $config); $this->upload->initialize($config); $file_name = 'post_image'; if(!$this->upload->do_upload($file_name)){ varDebug($this->upload->display_errors()); $file_name = 'assets/img/noimage.jpg'; } else { $post_image = $this->upload->data('file_name'); } // Page Data $data = array( 'user_id' => $this->input->post('user_id'), 'slug' => $slug, 'title' => $this->input->post('title'), 'post_image' => $post_image, 'body' => $this->input->post('body'), 'status' => $this->input->post('status'), 'is_featured' => $this->input->post('is_featured'), 'is_commented' => $this->input->post('is_commented'), 'order' => $this->input->post('order'), 'type' => 'post', ); $this->Post_model->add($data); // Get last post id for inserting of categories data $last_post_id = $this->db->insert_id(); // Get title for activity data $activity_title = $data['title']; // Create many-to-many relationship ///////////////////////////// $taxonomy_list = $this->Terms_model->get_list(); foreach ( $taxonomy_list as $cat ){ //do insert here $data = array( 'term_taxonomy_id' => $this->db->insert_id(), 'term_id' => $cat->term_id, 'type' => 'category', ); } $this->Taxonomy_model->add($data); $data = array(); $relationship_list = $this->Taxonomy_model->get_list(); foreach ( $relationship_list as $rel ){ // Insert selected values $data[] = array( 'post_id' => $last_post_id, 'term_taxonomy_id' => $rel->term_taxonomy_id, 'term_order' => 0, ); } $this->db->insert_batch('ci_terms_relationship', $data); /////////////////////////////////////////// // Activity Array $data = array( 'resource_id' => $last_post_id, 'type' => 'post', 'action' => 'added', 'user_id' => $this->session->userdata('user_id'), 'message' => 'A new post was added (' . $activity_title . ')' ); // Insert Activity $this->Activity_model->add($data); // Set Message $this->session->set_flashdata('success', 'Post has been added'); // Redirect redirect('admin/posts'); } } ?> Again, thanks, I really need help with this.
  6. Hello, so I've been trying to use Select 2 in the AdminLTE template with a function in javascript to add dynamic data. Here is my view in which I'm using a form_input with a class of select2.: <div class="form-group"> <?php echo form_label('Skills', 'skills'); ?> <div class="input-group date"><div class="input-group-addon"><i class="fa fa-star" aria-hidden="true"></i></div> <?php $data = array( 'name' => 'skills', 'id' => 'skills', 'class' => 'form-control select2', 'style' => 'width:100%', 'value' => $item->skills ); ?> <?php echo form_input($data); ?> </div> </div> and here is the script which should allow me to add the skills: $(".select2").select2({ tags: true, tokenSeparators: [',', ' '] }) Is it supposed to set the tags equal to TRUE allow me to add data? Because what I know the input when adding a new content should turn into a blue color, right?. It is not doing it. SECOND PART Now can somebody help me in how to correctly implode(separate by comma) the skills into my database?. I actually though that in was by just doing something like: $user_skill = implode(' , ' , $this->input->post('skills')) and then passing the data to the database users with: 'skills' => $user_skills, but it is not working and I really don't know why(it's sending nothing to the database). It does not update my users.id; here is a pic: public function edit($id){ // Check Login if (!$this->session->userdata('is_member')) { redirect('dashboard/login'); } // Field Rules $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|min_length[2]'); $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|min_length[2]'); $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]'); $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email'); if ($this->form_validation->run() == FALSE) { // Get Current Subject $data['item'] = $this->User_model->get($id); //Load View Into Template $this->template->load('public', 'default', 'users/edit', $data); } else { $slug = str_replace(' ', '-', $this->input->post('username')); $slug = strtolower($slug); $user_skills = implode(',', $this->input->post('skills')); // Create User Data Array $data = array( 'first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'email' => $this->input->post('email'), 'username' => $this->input->post('username'), 'slug' => $slug, 'avatar_img' => $this->input->post('avatar_img'), 'cover_img' => $this->input->post('cover_img'), 'genre' => $this->input->post('genre'), 'company' => $this->input->post('company'), 'phone' => $this->input->post('phone'), 'address' => $this->input->post('address'), 'occupation' => $this->input->post('occupation'), 'biography' => $this->input->post('biography'), 'website' => $this->input->post('website'), 'birthdate' => $this->input->post('birthdate'), 'interested_in' => $this->input->post('interested_in'), 'college' => $this->input->post('college'), 'highschool' => $this->input->post('highschool'), 'skills' => $user_skills, ); // Update User $this->User_model->update($id, $data); // Activity Array $data = array( 'resource_id' => $this->db->insert_id(), 'type' => 'user', 'action' => 'updated', 'user_id' => $this->session->userdata('user_id'), 'message' => '(' . $data["username"] . ') Updated his/her information' ); // Add Activity $this->Activity_model->add($data); // User Skills Array $data = array( 'id' => $this->db->insert_id(), 'skills' => $user_skills, ); // Add User Skill $this->Skills_model->add($data); //Create Message $this->session->set_flashdata('success', "You're account has been updated"); //Redirect to Users redirect('dashboard/profile'); } } Fetching the skills in the view would be something like this or do I need to do a different approach. <?php echo $this->session->skills; ?> THIRD PART Also I would like to know if somebody knows how to add skills to a database table depending on the skills added by the user on his account? As you can see in the controller I created something like: // User Skills Array $data = array( 'id' => $this->db->insert_id(), 'skills' => $user_skills, ); // Add User Skill $this->Skills_model->add($data); How can I make sure that all the data inside the variable $user_skill fits into my user_skills table. I mean the table should be increasing its rows according to the number of skills added by the users. I hope somebody can helps and understand what I mean. Thanks.
  7. Hello, I've been working on a login system in which the function will check if three values on my database are equal to TRUE(1) or FALSE(0). So far I have an user account with the three values set to true so it should allow me to log in and redirect to the admin page but it does not. Can somebody help me with this, is there an error that I may be missing? public function admin_login(){ //Check if logged in $this->User_model->session_comprobate_admin(); //Set rules $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]'); if ($this->form_validation->run() == FALSE) { //Load View Into Template $this->template->load('admin', 'login', 'users/login'); } else { // Get Post Data $username = $this->input->post('username'); $password = $this->input->post('password'); $enc_password = md5($password); $data_user = $this->User_model->login($username, $enc_password); // Verify variables if($data_user){ $user_id = $this->User_model->get_username($username); $users = $this->User_model->get_userid($user_id); //Check if active or banned if($users->active == 0){ // Create Error $this->session->set_flashdata('error', 'This account is banned or inactive.'); // Redirect to pages redirect('admin/login'); } //Check if is admin if($users->is_admin == 0){ // Create Error $this->session->set_flashdata('error' , 'Sorry, you can not access to this page.'); // Redirect redirect('admin/login'); } //Check if is member if($users->is_member == 0){ // Create Error $this->session->set_flashdata('error' , 'This account does not exists. Please try again.'); } else { //Check if variables are true $user_data = array( 'user_id' => $user_id, 'username' => $username, 'is_admin' => true, 'active' => true, 'is_member' => true, ); // Set Session Data $this->session->set_userdata( 'is_admin',$user_data); $this->UserModel->is_admin($user_id); // Create Message $this->session->set_flashdata('success', 'You are logged in'); // Redirect to pages redirect('admin'); } } else { // Create Error $this->session->set_flashdata('error', 'Invalid Login'); // Redirect to pages redirect('admin/login'); } } } This is my user_model info: //I need to work on these two public function get_username($users) { $this->db->select('id'); $this->db->from('users'); $this->db->where('username', $users); return $this->db->get()->row('id'); } public function get_userid($user_id) { $this->db->select('id'); $this->db->from('users'); $this->db->where('id', $user_id); return $this->db->get()->row(); } /// //Check if admin public function is_admin($id) { $this->db->select('is_admin'); $this->db->from('users'); $this->db->where('id', $id); $is_admin = $this->db->get()->row('is_admin'); if ($is_admin == 0) { redirect('/'); } else { redirect('admin'); } } //Check if member public function is_member($id) { $this->db->select('is_member'); $this->db->from('users'); $this->db->where('id', $id); $is_member = $this->db->get()->row('is_member'); if ($is_member == 0) { redirect('/'); } else { redirect('dashboard/login'); } } //Check if active public function is_active($id) { $this->db->select('active'); $this->db->from('users'); $this->db->where('id', $id); $is_active = $this->db->get()->row('active'); if ($is_active == 0) { redirect('/'); } else { redirect('dashboard/login'); } } //Verify if username and email is already registered public function existent_username($username) { $query = $this->db->get_where('users', array('username' => $username)); return $query->row_array(); } public function existent_email($email) { $query = $this->db->get_where('users', array('email' => $email)); return $query->row_array(); } // public function session_comprobate_member() { if ($this->session->userdata('is_member') != NULL) { redirect('dashboard'); } } public function session_comprobate_admin() { if ($this->session->userdata('is_admin') != NULL) { redirect('admin'); } } It was working well but I just added the is_admin and is_member checks and it stop working..
  8. Kirasiris

    CodeIgniter - Blocking access to admin pages

    Hey, sorry for the late answer, but I already fixed it, I just created controller/models for my user database table, and I gave permissions to users according to the status of their account. Example 1:regular user 2:moderator 3:author 4:admin I did something like that, but thanks for trying to help me .
  9. The thing is that I never created a login page, or anything like that. So my website is completely done, is finally ready to be published, but the only thing that I need now, is the blocking of the admin pages to the public. I have a controller called Admin in which I have all the function and pages of "admin" , here is my controller.(all ths needs to be blocked) <?php class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('about_model'); $this->load->model('blog_model'); $this->load->model('categorias_model'); $this->load->model('cookies_model'); $this->load->model('news_model'); $this->load->model('portfolio_model'); $this->load->model('privacy_model'); $this->load->model('terms_model'); $this->load->model('skills_model'); $this->load->model('profesion_model'); $this->load->model('slider_model'); $this->load->library('pagination'); } public function index(){ $data['title'] = 'Admin Panel'; // Siempre poner minusculas al poner nombre de un model // $data['blog'] = $this->blog_model->get_blog(); $data['portfolio'] = $this->portfolio_model->get_portfolio(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/dashboard',$data); $this->load->view('templates/footer', $data); } //// Paginas de administracion /// public function sliders(){ $data['title'] = 'Sliders'; $data['slider'] = $this->slider_model->get_slider(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/sliders',$data); $this->load->view('templates/footer', $data); } public function posts(){ $data['title'] = 'Posts'; $data['blog'] = $this->blog_model->get_blog(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/posts',$data); $this->load->view('templates/footer', $data); } public function portfolio(){ $data['title'] = 'Portfolio'; // Siempre poner minusculas al poner nombre de un model // $data['portfolio'] = $this->portfolio_model->get_portfolio(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/portfolio',$data); $this->load->view('templates/footer', $data); } ///// Estas paginas requieren de la funcion __construc que etsa localizada abajo, si se llegase a borrar, estas, dejaran de funcionar y/o mostrar informacion de la database public function categorias(){ $data['title'] = 'Categorias'; // Siempre poner minusculas al poner nombre de un model // $data['categorias'] = $this->categorias_model->get_categorias(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/categorias',$data); $this->load->view('templates/footer', $data); } public function paginas(){ $data['title'] = 'Paginas'; // Siempre poner minusculas al poner nombre de un model // $data['about'] = $this->about_model->get_about(); $data['cookies'] = $this->cookies_model->get_cookies(); $data['home'] = $this->news_model->get_home(); $data['privacy'] = $this->privacy_model->get_privacy(); $data['terms'] = $this->terms_model->get_terms(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/paginas',$data); $this->load->view('templates/footer', $data); } public function skills(){ $data['title'] = 'Skills'; // Siempre poner minusculas al poner nombre de un model // $data['skills'] = $this->skills_model->get_skills(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/skills',$data); $this->load->view('templates/footer', $data); } public function profesion(){ $data['title'] = 'Profesion'; // Siempre poner minusculas al poner nombre de un model // $data['profesionalismo'] = $this->profesion_model->get_profesion(); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/profesion',$data); $this->load->view('templates/footer', $data); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// Slider /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear slider /// public function crearslider(){ $data['title'] = 'Crear Slider'; $this->form_validation->set_rules('titulo','Titulo', 'required'); $this->form_validation->set_rules('imagen','Imagen', 'required'); $this->form_validation->set_rules('descripcion','Descripcion', 'required'); $this->form_validation->set_rules('link','link', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearslider',$data); $this->load->view('templates/footer', $data); } else{ $this->slider_model->crearslider(); redirect('admin/sliders'); } } // Borrar slider // public function borrarslider($id){ $this->slider_model->borrarslider($id); redirect('admin/sliders'); } // Editar slider // public function editarslider($slug){ $data['slider']=$this->slider_model->get_slider($slug); if(empty($data['slider'])){ show_404(); } $data['title']='Editar slider'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarslider',$data); $this->load->view('templates/footer', $data); } // Actualizar slider // public function actualizarslider(){ $this->slider_model->actualizarslider(); redirect('admin/sliders'); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// BLOG ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear Post /// public function crearpost(){ $data['title'] = 'Crear Post'; $data['categorias'] = $this->categorias_model->get_categorias(); $this->form_validation->set_rules('titulo','Titulo', 'required'); $this->form_validation->set_rules('fecha','Fecha', 'required'); $this->form_validation->set_rules('imagen','Imagen', 'required'); $this->form_validation->set_rules('categoria_id','Categoria', 'required'); $this->form_validation->set_rules('contenido','Contenido', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearpost',$data); $this->load->view('templates/footer', $data); } else{ $this->blog_model->crear_post(); redirect('admin/posts'); } } // Borrar post // public function borrar($id){ $this->blog_model->delete_post($id); redirect('admin/posts'); } // Editar Post // public function editarpost($slug){ $data['blog']=$this->blog_model->get_blog($slug); $data['categorias'] = $this->categorias_model->get_categorias(); if(empty($data['blog'])){ show_404(); } $data['title']='Editar Post'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarpost',$data); $this->load->view('templates/footer', $data); } // Actualizar Post // public function actualizarpost(){ $this->blog_model->update_post(); redirect('admin/posts'); } ////////////////////////////////////////////////////////////////////////// Portfolio /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear Portfolio /// public function crearportfolio(){ $data['title'] = 'Crear Portfolio'; $this->form_validation->set_rules('titulo','Titulo', 'required'); $this->form_validation->set_rules('fecha','Fecha', 'required'); $this->form_validation->set_rules('imagen','Imagen', 'required'); $this->form_validation->set_rules('thumbnail','Thumbnail', 'required'); $this->form_validation->set_rules('categoria_id','Categoria', 'required'); $this->form_validation->set_rules('descripcion','Descripcion', 'required'); $this->form_validation->set_rules('contenido','Contenido', 'required'); $this->form_validation->set_rules('changelog','Changelog'); $this->form_validation->set_rules('precio','Precio', 'required'); $this->form_validation->set_rules('preview','Preview', 'required'); $this->form_validation->set_rules('download','Download', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearportfolio',$data); $this->load->view('templates/footer', $data); } else{ $this->portfolio_model->crear_post(); redirect('admin/portfolio'); } } // Borrar portfolio // public function delete($id){ $this->portfolio_model->delete_post($id); redirect('admin/portfolio'); } // Editar Portfolio // public function editarportfolio($slug){ $data['portfolio']=$this->portfolio_model->get_portfolio($slug); if(empty($data['portfolio'])){ show_404(); } $data['title']='Editar Portfolio'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarportfolio',$data); $this->load->view('templates/footer', $data); } // Actualizar Portfolio // public function actualizarportfolio(){ $this->portfolio_model->update_post(); redirect('admin/portfolio'); } /////////////////////////////////////////////////////////////////////////////////// Categorias ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear categorias /// public function crearcategory(){ $data['title'] = 'Crear Categoria'; $data['categorias'] = $this->categorias_model->get_categorias(); $this->form_validation->set_rules('nombre','Titulo', 'required'); $this->form_validation->set_rules('creado_en','Fecha', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearcategory',$data); $this->load->view('templates/footer', $data); } else{ $this->categorias_model->crear_post(); redirect('admin/categorias'); } } // Borrar categorias // public function erase($id){ $this->categorias_model->delete_post($id); redirect('admin/categorias'); } // Editar categoria // public function editarcategoria($slug){ $data['categorias'] = $this->categorias_model->get_categorias($slug); if(empty($data['categorias'])){ show_404(); } $data['title']='Editar Categoria'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarcategoria',$data); $this->load->view('templates/footer', $data); } // Actualizar categoria // public function actualizarcategory(){ $this->categorias_model->update_post(); redirect('admin/categorias'); } //////////////////////////////////////////////////////////////// Skills //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear skill /// public function crearskill(){ $data['title'] = 'Crear Skill'; $data['skills'] = $this->skills_model->get_skills(); $this->form_validation->set_rules('titulo','Titulo', 'required'); $this->form_validation->set_rules('porcentaje','Porcentaje', 'required'); $this->form_validation->set_rules('color_1','Color Primario', 'required'); $this->form_validation->set_rules('color_2','Color Secundario', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearskill',$data); $this->load->view('templates/footer', $data); } else{ $this->skills_model->crearskill(); redirect('admin/skills'); } } // Borrar skill // public function erase_skill($id){ $this->skills_model->erase_skill($id); redirect('admin/skills'); } // Editar skill // public function editarskill($slug){ $data['skills'] = $this->skills_model->get_skills($slug); if(empty($data['skills'])){ show_404(); } $data['title']='Editar Skill'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarskill',$data); $this->load->view('templates/footer', $data); } // Actualizar skill // public function actualizarskills(){ $this->skills_model->update_post(); redirect('admin/skills'); } //////////////////////////////////////////////////////////////// Profesionalismo //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Crear profesion /// public function crearprofesion(){ $data['title'] = 'Crear Skill'; $data['profesionalismo'] = $this->profesion_model->get_profesion(); $this->form_validation->set_rules('titulo','Titulo', 'required'); $this->form_validation->set_rules('numero','Numero', 'required'); if($this->form_validation->run()===FALSE){ $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/crearprofesion',$data); $this->load->view('templates/footer', $data); } else{ $this->profesion_model->crearprofesion(); redirect('admin/profesion'); } } // Borrar profesion // public function erase_profesion($id){ $this->profesion_model->erase_profesion($id); redirect('admin/profesion'); } // Editar profesion // public function editarprofesion($slug){ $data['profesionalismo'] = $this->profesion_model->get_profesion($slug); if(empty($data['profesionalismo'])){ show_404(); } $data['title']='Editar Profesion'; $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarprofesion',$data); $this->load->view('templates/footer', $data); } // Actualizar profesion // public function actualizarprofesion(){ $this->profesion_model->update_post(); redirect('admin/profesion'); } //////////////////////////////////////////////////////////////// Editar paginas globales /////////////////////////////////////////////////////////////////////////////////////////////////////// /// Pagina Global About public function editarpagina_about($slug){ $data['title']='Editar Pagina About'; $data['about'] = $this->about_model->get_about($slug); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarpagina_about',$data); $this->load->view('templates/footer', $data); } /// Actualizar pagina global about /// public function actualizarpagina_about(){ $this->about_model->update_about(); redirect('admin/paginas'); } /// Pagina Global Cookies public function editarpagina_cookies($slug){ $data['title']='Editar Pagina cookies'; $data['cookies'] = $this->cookies_model->get_cookies($slug); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarpagina_cookies',$data); $this->load->view('templates/footer', $data); } /// Actualizar pagina global cookies /// public function actualizarpagina_cookies(){ $this->cookies_model->update_cookies(); redirect('admin/paginas'); } /// Pagina Global Privacy public function editarpagina_privacy($slug){ $data['title']='Editar Pagina Privacy'; $data['privacy'] = $this->privacy_model->get_privacy($slug); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarpagina_privacy',$data); $this->load->view('templates/footer', $data); } /// Actualizar pagina global Privacy /// public function actualizarpagina_privacy(){ $this->privacy_model->update_privacy(); redirect('admin/paginas'); } /// Pagina Global Terms public function editarpagina_terms($slug){ $data['title']='Editar Pagina Terms'; $data['terms'] = $this->terms_model->get_terms($slug); $this->load->view('templates/head', $data); $this->load->view('templates/navbar', $data); $this->load->view('admin/editarpagina_terms',$data); $this->load->view('templates/footer', $data); } /// Actualizar pagina global terms /// public function actualizarpagina_terms(){ $this->terms_model->update_terms(); redirect('admin/paginas'); } } ?> I tried to put this on my function __construct , but it still not working :/ . public function __construct() { parent::__construct(); $this->load->model('about_model'); $this->load->model('blog_model'); $this->load->model('categorias_model'); $this->load->model('cookies_model'); $this->load->model('news_model'); $this->load->model('portfolio_model'); $this->load->model('privacy_model'); $this->load->model('terms_model'); $this->load->model('skills_model'); $this->load->model('profesion_model'); $this->load->model('slider_model'); $this->load->library('pagination'); //// Block access to admin pages //// //Here you check ip allowed or not if (!in_array($this->input->ip_address(), array('107.208.103.39'))) { // Either show 404 show_404(); // OR redirect somewhere else redirect('news/home'); } } is there a way to block them to the public at least with HTACCESS ?
  10. Hello I've been trying to fix this problem for around 3 weeks; so what I want is to be able to send a picture and being able to display it in another page. It send it to the server, but still it doesn't show it. Here is my code: <?php require_once('../Connections/connection.php'); ?> <?php $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "add_post")) { $tiempocotejo= time(); $insertSQL = sprintf("INSERT INTO posts (titulo, categoria, tag, imagen, contenido, descripcion, estatus, plantilla,link, price, autor) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['titulo'], "text"), GetSQLValueString($_POST['categoria'], "text"), GetSQLValueString($_POST['tag'], "text"), GetSQLValueString($_POST['imagen'], "text"), GetSQLValueString($_POST['contenido'], "text"), GetSQLValueString($_POST['descripcion'], "text"), GetSQLValueString($_POST['estatus'], "int"), GetSQLValueString($_POST['plantilla'], "int"), GetSQLValueString($_POST['link'], "text"), GetSQLValueString($_POST['price'], "text"), GetSQLValueString($_SESSION['MM_Id'], "int")); mysql_select_db($database_connection, $connection); $Result1 = mysql_query($insertSQL, $connection) or die(mysql_error()); mysql_select_db($database_connection, $connection); $query_SacarIdPost = sprintf("SELECT posts.id FROM posts WHERE time=%s",$tiempocotejo,"int"); $SacarIdPost = mysql_query($query_SacarIdPost, $connection) or die(mysql_error()); $row_SacarIdPost = mysql_fetch_assoc($SacarIdPost); $totalRows_SacarIdPost = mysql_num_rows($SacarIdPost); mysql_free_result($SacarIdPost); $updateSQL = sprintf("UPDATE posts SET urlamigable= %s WHERE id=%s", GetSQLValueString(limpia_espacios($_POST['titulo'],$row_SacarIdPost['id']), "text"), GetSQLValueString($row_SacarIdPost['id'], "int")); mysql_select_db($database_connection, $connection); $Result1 = mysql_query($updateSQL, $connection) or die(mysql_error()); $insertGoTo = "publishedpost" . UrlAmigablesInvertida($row_SacarIdPost['id']).".php"; header(sprintf("Location: %s", $insertGoTo)); } ?> <style> #select{ padding-left:0px; } #select2{ padding-right:0px; } </style> <!DOCTYPE html> <html lang="en"> <?php include("includes/head.php"); ?> <!-- Preloader --> <div id="preloader"> <div id="status"> </div> </div> <body> <div id="sb-site"> <!-- header-full --> <div class="boxed"> <?php include ("../includes/header.php");?> <?php include("../includes/menu.php");?> </div> <!-- header-full --> <header class="main-header" style="background-color:#f1f1f1;"></header> <!-- container --> <div class="container"> <div class="row"> <!-- Sidebard menu --> <?php include ("../includes/adminsidebar.php"); ?> <!-- Sidebar menu --> <!--Container --> <div class="col-md-9"> <form role="form" action="<?php echo $editFormAction; ?>" name="add_post" method="POST"> <!-- Title --> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="titulo" placeholder="Enter title"> </div> <!-- Title --> <!-- upload image --> <div class="form-group"> <input class='file' type="file" class="form-control" name="imagen" onClick="gestionimagen.php" id="images" placeholder="Please choose your image"> </div> <!-- Upload Image --> <div class="form-group"> <label> Description </label><br> <textarea class="" name="descripcion" style="width:100%"></textarea> </div> <!-- Text editors --> <div class="form-group"> <label> Contenido </label> <textarea class="ckeditor" name="contenido"></textarea> </div> <!-- Text editor --> <!-- Category --> <div class="form-group"> <label>Categoria</label> <input type="text" class="form-control" name="categoria" placeholder="Enter categoria"> </div> <div class="form-group"> <label>Tag</label> <input type="text" class="form-control" name="tag" placeholder="Enter tag"> </div> <!-- Category --> <!-- Visibilidad --> <div class="col-md-6" id="select"> <div class="form-group"> <label for="select">Visible</label> <select class="form-control" id="estatus" name="estatus"> <option value="1">Si</option> <option value="0">No</option> </select> </div> </div> <!-- Visibilidad --> <!-- Tiplo de Plantilla necesito trabajar en esto!!!!! pero ya!!!--> <script> function plantilla(){ var formData = new FormData($("#formUpload")[0]); $.ajax({ type: 'POST', url: 'plantillapost.php', data: formData, contentType: false, processData: false }); } </script> <div class="col-md-6" id="select2"> <div class="form-group"> <label for="select">Plantilla</label> <select class="form-control" id="plantilla" name="plantilla"> <option value="1" <?php if (!(strcmp(1, ""))) {echo "SELECTED";} ?>>Normal</option> <option value="2" onClick="plantilla" <?php if (!(strcmp(2, ""))) {echo "SELECTED";} ?>>Full-Width</option> </select> </div> </div> <!-- Tipo de Plantilla --> <div class="col-md-6" id="select"> <div class="form-group"> <label>Link</label> <input type="text" class="form-control" name="link" placeholder="Enter link"> </div> </div> <div class="col-md-6" id="select2"> <div class="form-group"> <label>Price</label> <input type="text" class="form-control" name="price" placeholder="Enter price"> </div> </div> <button type="submit" class="btn btn-ar btn-primary pull-right">Agregar</button> <input type="hidden" name="MM_insert" value="add_post"> </form> </div> <!-- Container --> </div> </div> <!-- container --> <?php include("../includes/footer.php");?> </div> <!-- boxed --> </div> <!-- sb-site --> <?php include("../includes/menuderecha.php");?> <!-- sb-slidebar sb-right --> <?php include("../includes/back-to-top.php");?> <!-- Scripts --> <!-- Compiled in vendors.js --> <!-- <script src="js/jquery.min.js"></script> <script src="js/jquery.cookie.js"></script> <script src="js/imagesloaded.pkgd.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap-switch.min.js"></script> <script src="js/wow.min.js"></script> <script src="js/slidebars.min.js"></script> <script src="js/jquery.bxslider.min.js"></script> <script src="js/holder.js"></script> <script src="js/buttons.js"></script> <script src="js/jquery.mixitup.min.js"></script> <script src="js/circles.min.js"></script> <script src="js/masonry.pkgd.min.js"></script> <script src="js/jquery.matchHeight-min.js"></script> --> <script src="<?php echo $urlWeb ?>js/vendors.js"></script> <!--<script type="text/javascript" src="js/jquery.themepunch.tools.min.js?rev=5.0"></script> <script type="text/javascript" src="js/jquery.themepunch.revolution.min.js?rev=5.0"></script>--> <!-- Syntaxhighlighter --> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shCore.js"></script> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shBrushXml.js"></script> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shBrushJScript.js"></script> <script src="<?php echo $urlWeb ?>js/DropdownHover.js"></script> <script src="<?php echo $urlWeb ?>js/app.js"></script> <script src="<?php echo $urlWeb ?>js/holder.js"></script> <script src="<?php echo $urlWeb ?>js/home_profile.js"></script> <script src="<?php echo $urlWeb ?>js/efectos.js"></script> </body> </html> But Im still not able to display it, si I tried to do a tutorial that I saw on Internet and it made do another php file, that why I put on the input an action="gestionimagen.php" otherwise I would have never done, here is my code for gestionimagen.php: NOTE: I had to create another table on my server called images, but I would like to be able to do it in my table called posts as I have in the code above. <?php require_once '../Connections/connection.php'; $data = array(); if( isset( $_POST['image_upload'] ) && !empty( $_FILES['imagen'] )){ $image = $_FILES['imagen']; $allowedExts = array("gif", "jpeg", "jpg", "png"); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } //create directory if not exists if (!file_exists('imagen')) { mkdir('imagen', 0777, true); } $image_name = $image['name']; //get image extension $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); //assign unique name to image $name = time().'.'.$ext; //$name = $image_name; //image size calcuation in KB $image_size = $image["size"] / 1024; $image_flag = true; //max image size $max_size = 512; if( in_array($ext, $allowedExts) && $image_size < $max_size ){ $image_flag = true; } else { $image_flag = false; $data['error'] = 'Maybe '.$image_name. ' exceeds max '.$max_size.' KB size or incorrect file extension'; } if( $image["error"] > 0 ){ $image_flag = false; $data['error'] = ''; $data['error'].= '<br/> '.$image_name.' Image contains error - Error Code : '.$image["error"]; } if($image_flag){ move_uploaded_file($image["tmp_name"], "../images/post".$name); $src = "../images/post".$name; $dist = "../images/post/thumbnail_".$name; $data['success'] = $thumbnail = 'thumbnail_'.$name; thumbnail($src, $dist, 200); $sql="INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } } mysqli_close($con); echo json_encode($data); } else { $data[] = 'No Image Selected..'; } ?> So I don't know if did properly explain myself, but thats what I want, send the picture to my server into my table called posts, otherwise can you help me how to properly adapt it to the new table called "images" .
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.