Curl with WP

Seema

Curl is  used to transfer data with urls.

        $url = 'https://abc.co';
        $username= 'username';
        $password = 'password';

      //status active 
        $data = array("query"=>'title:"Curl in wordpress');

        $data_json = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
        curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response  = curl_exec($ch);
        curl_close($ch);

create a new jquery file (file upload using jquery)

jQuery("#submit_btn").submit(function () {
      
        jQuery("#submit_btn")
            .find("input[type='submit']")
            .attr("disabled", "disabled");

//get form field value 
    var Name = jQuery("#Name").val(); 
//get overall form value 
    var form = jQuery('#form_id')[0];
    var data = new FormData(form);
// manually append data
 data.append("action", "md_apply_jobs_local");
 data.append("security", ajax_object.ajax_nonce); // for security purpose

        jQuery.ajax({
            url: ajax_object.ajaxurl,
            type: "post",
            data: data,
            enctype: 'multipart/form-data',
            dataType: "json",
            processData: false,
            contentType: false,
            success: function (response) {

                if (response.status) {

                    var result = JSON.parse(response.result);
                    if(result.ok !== undefined  && result.ok === true) {
                        var message = ""+ response.req_data.name+",  successfully!";
                        jQuery(".message").text(message).addClass("success").removeClass("fail");

                        jQuery("#form_id").hide();
                        jQuery(".message").fadeIn();


                    }
                    else {
                        jQuery(".message").text("something went wrong.please check your data and apply again").addClass("fail").removeClass("success");
                    }
            
                } else {
                    jQuery(".message").text(response.message).addClass("fail").removeClass("success");
                }

            },
            error: function (response) {
                jQuery(".message")
                    .text("There was some issue in process. Please try again later!")
                    .addClass("fail").removeClass("success");
            },
            complete: function () {
                jQuery("#submit_btn")
                    .find("input[type='submit']")
                    .removeAttr("disabled");

            }
        });

        return false;
    });
    
});

Then Create function file (functions.php)

function wpdocs_theme_name_scripts()
 {
 $params = array('ajaxurl' => admin_url('admin-ajax.php'),  
   'ajax_nonce' => wp_create_nonce('FJ_value_here'), ); wp_localize_script('scripts', 'ajax_object', $params);
 }
 add_action('wp_enqueue_scripts', 'wpdocs_theme_name_scripts');
function apply_jobs_local()
 {
     $status = false;
     $ret_message = "Error : Request not sent! Please try again later";
     $response=[];
 if (check_ajax_referer('FJ_value_here', 'security')) {   
       $Name= $_POST["Name"];         
       $file = $_FILES['file'];        
 if(!is_dir("/tempdocs")) {   
     
     mkdir("/tempdocs");   
      } 
         $uploadfile =  "/tempdocs/".rand(1111,9999). $file["name"];         $cFile = null;    
     if(move_uploaded_file($file['tmp_name'], $uploadfile)){ 
       if (function_exists('curl_file_create')) {    
              $cFile = curl_file_create($uploadfile);     
         } else { // 
                 $cFile = '@' . realpath($uploadfile);  
           }       
     }        
$data = ["name" => $Name, "file" =>  $cFile];          $url="https://abc.co/apply"; // API URL    
     $ch = curl_init($url); // Create a new cURL resource         
// Set the content type to application/json       
   $username= 'username';      
   $password = 'password';    
   curl_setopt($ch, CURLOPT_HTTPHEADER,    array('Accept:application/json','Content-Type: multipart/form-data'));          curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);           curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');      
     curl_setopt($ch, CURLOPT_POSTFIELDS,$data);    
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response instead of outputting       
  $result = curl_exec($ch); // Execute the POST request         curl_close($ch);  // Close cURL resource      
    $status = true;     
    $ret_message = "Type Your messages"; } 
$return_data = array("status" => $status, "message" => $ret_message, "result" => $result , "req_data" => $data );
 echo json_encode($return_data, true);
 exit;
 }
add_action('wp_ajax_md_apply_jobs_local', 'apply_jobs_local');
add_action('wp_ajax_nopriv_md_apply_jobs_local', 'apply_jobs_local');