Multipart/form-data showing 500 error in console in live server

Please take a note that the form works well in live server,

This is my image upload controller:

function uploadPhoto()
{
    $this->load->helper('url');
    $this->load->model('photo_model', 'picManager');
    $this->load->model('user_model', 'userManager');

    $result = array();

    $user = $this->userManager->get($this->session->userdata("user_id"))->result_array();
    $user = $user[0];

    $user_id = url_title($this->session->userdata('user_id'));

    if(DEMO_MODE == 1) {
        $result["status"] = 500;
    } else {
        if($user_id == null)
        {
            $result["status"] = 0;
        } else {

            $this->load->model("site_model");
            $settings = $this->site_model->get_website_settings()->result_array();
            $settings = $settings[0];

            $max_upload = $settings["upload_limit"];
            $user_photos = $this->picManager->count_user_photos($this->session->userdata("user_id"));

            if($user_photos >= $max_upload && $max_upload != 0) {
                $result["status"] = 998;
            } else {

                // Check if the directory already exists
                if (!file_exists("./uploads/photos/" . $user_id . "/")) {
                    mkdir("./uploads/photos/" . $user_id . "/");
                    mkdir("./uploads/photos/" . $user_id . "/thumbnails/");
                }

                // Copy the file to the correct directory
                if (!empty($_FILES))
                {
                    $nameFile   = rand(0,999999).time();
                    $tempFile   = $_FILES['upl']['tmp_name'];
                    $fileSize   = $_FILES['upl']['size'];
                    $fileTypes  = array('jpg','jpeg','png', 'JPG', 'JPEG', 'PNG'); // File extensions
                    $fileParts  = pathinfo($_FILES['upl']['name']);
                    $targetPath = "./uploads/photos/" . $user_id . "/";
                    $targetPathThumb = $targetPath . "thumbnails/";
                    $targetPathEcho = "/uploads/photos/" . $user_id . "/";
                    $targetPathEchoThumb = "/uploads/photos/" . $user_id . "/thumbnails/";
                    $targetFile =  str_replace('//','/',$targetPath) . $nameFile . "." . $fileParts["extension"];
                    $targetFileThumb = str_replace('//','/',$targetPathThumb) . $nameFile . "." . $fileParts["extension"];
                    $targetFileEcho = str_replace('//','/',$targetPathEcho) . $nameFile . "." . $fileParts["extension"];
                    $targetFileEchoThumb = str_replace('//','/',$targetPathEchoThumb) . $nameFile . "." . $fileParts["extension"];

                    if($fileSize <= 7000000)
                    {
                        if (in_array($fileParts['extension'],$fileTypes)) {
                            // Send the file
                            $file = $this->compress_image($tempFile, $targetFile, 100);

                            $thumbWidth = 800;

                            // Create the thumbnail
                            $img = imagecreatefromjpeg( $file );
                            $width = imagesx( $img );
                            $height = imagesy( $img );

                            // calculate thumbnail size
                            $new_width = $thumbWidth;
                            $new_height = floor( $height * ( $thumbWidth / $width ) );

                            // create a new temporary image
                            $tmp_img = imagecreatetruecolor( $new_width, $new_height );

                            // copy and resize old image into new image
                            imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

                            // save thumbnail into a file
                            imagejpeg( $tmp_img, $targetFileThumb );

                            if($user["gender"] == 1) {
                                $word_gender = "her";
                            } else {
                                $word_gender = "his";
                            }

                            $this->load->model('action_model', 'actionModel');
                            $this->actionModel->add($this->session->userdata('user_id'), 17, "<a href='" . base_url("user/profile/" . $this->session->userdata('user_id')) . "'>" . $this->session->userdata('user_username') . "</a> uploaded new photos on " . $word_gender . " profile.", base_url("user/profile/" . $this->session->userdata('user_id')), "<i class='fa fa-picture-o'></i>");

                            // Add picture in the DB 
                            $pic_id = $this->picManager->add($targetFileEcho, $targetFileEchoThumb, $this->session->userdata('user_id'));
                            $result["status"]   = 1; 
                            $result["photo"]    = $targetFileEcho;
                            $result["id"]       = $pic_id; 

                            // Count user photos
                            $nb_user_photos = $this->picManager->count_user_photos($this->session->userdata('user_id'));

                            // User has just one photo, set it as the profile picture
                            if($nb_user_photos == 1) {
                                $this->userManager->update_info($this->session->userdata('user_id'), array("main_photo" => $pic_id));

                                $this->session->set_userdata(
                                    array(
                                        "user_avatar"   => $targetFileEchoThumb,
                                    )
                                );
                            }

                        } else {
                            $result["status"] = 0;
                        }
                    }
                } 
            }
        }
    }

    header('Content-type: application/json;');
    echo json_encode($result);
}

while my form is

 
photo/uploadPhoto" enctype="multipart/form-data" class="clearfix"> lang->line("select_photos_to_upload"); ?> <ul class="wait_list"> <!-- The file uploads will be shown here --> </ul> </form> </div> </div>

and my js is

(document).ready(function() {

$(".btn-save-photos").click(function(e) {
    e.preventDefault();

    var photo_array = [];

    $(".photo_line").each(function() {

        var photo = $(this).find(".photo_url").attr("data-id");
        var title = $(this).find(".title_img").val();
        var tags = $(this).find(".tags_img").val();

        // Create the info_array
        var info_array = {
            photo_id : photo,
            title : title,
        };

        // Add the info_array to the global array
        photo_array.push(info_array);
    });

    $.ajax({ 
        url: base_url + "photo/save_photos_infos",
        type: "POST",
        dataType: "json",
        data: {photo_array: photo_array},
        success: function(data) {
            window.location.href = base_url + "user/settings?action=photos_added";
        }
    });   
});

and

 $('#upload').fileupload({

    // This element will accept file drag/drop uploading
    dropZone: $('#drop'),
    limitMultiFileUploads: 5,
    sequentialUploads: true,

    // This function is called when a file is added to the queue;
    // either via the browse button, or via drag/drop:
    add: function (e, data) {

        if(data.files[0]['type'] != 'image/png' && data.files[0]['type'] != 'image/jpg' && data.files[0]['type'] != 'image/jpeg'){ alert("Whoops! You can only add photos with the .PNG or .JPG extension."); return; }

        var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
            ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

        if(data.files[0].size > 7000000)
        {
            alert(photo_weight_error_str);
            return;
        }

        // Append the file name and file size
        tpl.find('p').text(data.files[0].name)
                     .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

        // Add the HTML to the UL element
        data.context = tpl.appendTo(ul);

        // Initialize the knob plugin
        tpl.find('input').knob();

        // Listen for clicks on the cancel icon
        tpl.find('span').click(function(){

            if(tpl.hasClass('working')){
                jqXHR.abort();
            }

            tpl.fadeOut(function(){
                tpl.remove();
            });

        });

        var t = "";
        // Automatically upload the file once it is added to the queue
        var jqXHR = data.submit().success(function(result, textStatus, jqXHR){

            if(result.status == 1)
            {

                $(".no-photo-yet").hide();

                var nb_photo_line = $(".photo_line").length+1;

                // We create the table of images for the informations (title, tags...)
                var photo_block = "<tr class='photo_line' data-cpt='" + nb_photo_line + "'>";
                photo_block += '<td style="width:35%;"><img class="col-md-12 photo_url" data-id="' + result.id + '" src="' + base_url + result.photo + '" class="img-responsive" /></td>';
                photo_block += '<td class="infos_photo">';
                photo_block += '
'; photo_block += '' + description_str + ' :'; photo_block += ''; photo_block += '
'; photo_block += '</td>'; photo_block += '</tr>'; $(".img_list").append(photo_block); $(".img_list").fadeIn(); $(".buttons_send_photos").fadeIn(); } else if(result.status == 500) { alert(demo_mode_str); } else if(result.status == 998) { alert(upload_limit_reached_str); } }); }, progress: function(e, data){ // Calculate the completion percentage of the upload var progress = parseInt(data.loaded / data.total * 100, 10); // Update the hidden input field and trigger a change // so that the jQuery knob plugin knows to update the dial data.context.find('input').val(progress).change(); if(progress == 100){ data.context.removeClass('working'); } }, fail:function(e, data){ // Something has gone wrong! data.context.addClass('error'); }

I have checked the error console it shows 500 error however nothing shows up in php error log.

The php.ini if fine and is as follows:

file_uploads = On
; cPanel-generated php ini directives, do not edit
; Manual editing of this file may result in unexpected behavior.
; To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
; For more information, read our documentation (https://go.cpanel.net/EA4ModifyINI)

allow_url_fopen = On
allow_url_include = On
asp_tags = Off
display_errors = Off
enable_dl = Off
max_execution_time = 160
max_input_time = -1
max_input_vars = 5000
memory_limit = 512M
post_max_size = 25M
session.gc_maxlifetime = 1440
session.save_path = "/var/cpanel/php/sessions/ea-php56"
upload_max_filesize = 200M
zlib.output_compression = On

It does not look like a code error but I don’t think there is a php.ini defect too, Or am I missing some Multipart/form-data module or something like that if it’s there?

PS: My client is using Codeigniter 3.17 and PHP 5.6 in my live server and PHP 7.2 In development and is not ready to upgrade to 7.2.

Advertisements

Can’t cope with Xdebug + Sublime Text

Environment:
Ubuntu, nginx, Sublime Text 3.

I installed xdebug, XDebug Client for Sublime Text.

php -i

PHP Version => 7.2.3-1+ubuntu16.04.1+deb.sury.org+1
xdebug.remote_enable => On => On
xdebug.remote_port => 9000 => 9000
xdebug.remote_host => localhost => localhost

nginx

server {

    root /var/www/html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

Well, php scripts work. I organized a file

/var/www/html/test.php

<?php 

echo PHP_VERSION;

for($i=0;$i<10;$i++) {
    echo($i); // Breakpoint.
}

?>

If I go go localhost/test.php, the script works fine.

Now I’d like to make the script stop at the breakpoint (in the script I show where I have put the breakpoint).

Tools / Xdebug / Start debugging.

Then I go to localhost/test.php.

Well, the script works to its end without stopping at the breakpoint.

Could you give me a kick here?

Update data in xampp database

I have to update my database in correspondance to email.I am using Android Networking to update data in my database but it only is giving me server timeout. This is my PHP:

<?php
if(isset($_POST['update']))
{    
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "truck_loader";

$connect = mysqli_connect($hostname, $username, $password, $databaseName);

$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];

$query = "UPDATE `users` SET 
`name`='".$name."',`address`='".$address."',`mobile`= $mobile WHERE `email` 
= $email";

$result = mysqli_query($connect, $query);

if(mysqli_query($connect,$query))
{
$response['success'] = '1';
 $response['message']='Updated successfully';
    echo json_encode($response);
    exit;
}
else    
{
    $response['success'] = '0';
    $response['message']='Updation failed';
    echo json_encode($response);
    exit;
}

mysqli_close($connect);

}
?>

This my code in android:

 private void updateProfile() {
    HashMap<String,String> params=new HashMap<>();
    params.put("name",name.getText().toString());
    params.put("email",email.getText().toString());
    params.put("mobile",mobile.getText().toString());
    params.put("address",address.getText().toString());
    AndroidNetworking.post("update.php").addBodyParameter(params).setTag("Profile").setPriority(Priority.LOW).build().getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                if(response.getString("success").equals("1")) {
                    Toast.makeText(FragProfile.this, response.getString("message"), Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(FragProfile.this, response.getString("message"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(ANError anError) {
            Toast.makeText(FragProfile.this, "Server timeout please try again later", Toast.LENGTH_SHORT).show();

        }
    });

}

There is no exception shown the code so i am confused on what the error could be.
EDIT: I am making this for the profile activity in my internship project, therefore, I have not used session in it.

Login depending on role

How can i redierect a user from the login window to the specific page?
I try to make a site for students/teachers and i want students to have a specific homepage with specific options, and the teachers to have a different one. I have tried this code but it only sends me to one of the choices no matter what user i use. In the DB i made a column with Status. A user can be “Profesor(Teacher)” or Student.
What have i done wrong in my code?

  if(mysqli_num_rows($sql)==1) {
     $_SESSION['login_user'] = $username;
     $sql="SELECT * from users WHERE Status = 'Student'";
     $query=mysqli_query($connect,$sql);
     if ($role=mysqli_fetch_array($query))
     {
     header("location: http://site/prob.php");
   }else{
     header("location: http://site/connectafterlogin.php");
   }
  }else {
     $error = "Your Login Name or Password is invalid";
  }

}
?>

Usage of Woocommerce’s template system

I am trying to use Woocommerce’s wc_get_template function to load my own templates, but it dosen’t seem to work (it’s not outputting content from the template files), together with my Woocommerce plugin. Below is what I have tried:

plugindir/templates/testing-template.php:

<h1>Output stuff</h1>

plugindir/pluginname.php:

if(in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option('active_plugins')))) {

    function template_loader(){
      wc_get_template('testing-template.php', array());
    }

    add_action('init', 'template_loader');
}

How to set library_path in config for ImageMagick library which is installed in windows machine

I’m getting the following error while I try to crop an image using ImageMagick
library.

“Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct”.

So the library is installed on my windows machine in program files(x 86) folder.

I have set the config like this:-

$config[‘image_library’] = ‘ImageMagick’;
$config[‘library_path’] = ‘C:\ImageMagick\Program Files (x86)\’;

M’I setting the $config[‘library_path’] wrong and please note that the environment variable is as follows:-
path : — C:\Program Files (x86)\ImageMagick

Thanks in advance.