?
Solved

php curl help

Posted on 2012-08-16
9
Medium Priority
?
833 Views
Last Modified: 2012-08-23
<?php
/**
 *
 * A class made for utility methods around Vend's API
 *
 *
 */
class VendApiUtils {

    /**
     * A simple static method to call Vend API urls
     *
     * @param string $url
     * @param string $username
     * @param string $password
     * @param array  $params	<OPTIONAL>
     */
    public static function requestVendApiUrl($url, $username, $password, $params = array())
    {
        // is cURL installed?
        if (!function_exists('curl_init')) {
            throw new Exception('CURL is not installed!');
        }

        // Create a new cURL instance
        $ch = curl_init();
        
        $opts = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
        CURLOPT_TIMEOUT => 120,
        CURLOPT_FAILONERROR => 1,
        CURLOPT_HTTPAUTH => CURLAUTH_ANY, 
        CURLOPT_USERPWD => "$username:$password"         
        );

        // Assign the cURL options
        curl_setopt_array($ch, $opts);
        
        // Get the response
        $response = curl_exec($ch);
        
        // Close cURL
        curl_close($ch);
        
        // Execute the request & get the response
        return $response;
    }
}

Open in new window


i have created test store in vendhq.com
store url is https://mystore.vendhq.com
username : test
password : test123

i changed line 29
CURLOPT_URL => $https://mystore.vendhq.com

error i am getting is
Parse error: syntax error, unexpected ':', expecting ')'

which line i should change to login to store name?
0
Comment
Question by:ammadeyy2020
  • 4
  • 4
9 Comments
 
LVL 1

Expert Comment

by:Shaun_King_23
ID: 38299929
why don't you set $url = "https://mystore.vendhq.com";
before you create your curl options

// Create a new cURL instance
    $url = "https://mystore.vendhq.com";       // declare web address
    $ch = curl_init();

    $opts = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
        CURLOPT_TIMEOUT => 120,
        CURLOPT_FAILONERROR => 1,
        CURLOPT_HTTPAUTH => CURLAUTH_ANY,
        CURLOPT_USERPWD => "$username:$password"        
        );

this should fix your error.
0
 

Author Comment

by:ammadeyy2020
ID: 38299973
its giving blank page

if its successful
i want to display product name, brand_name, count,

below is the link for API documentation
 https://docs.google.com/a/vendhq.com/document/pub?id=13JiV6771UcrkmawFRxzvVl3tf5PGSTBH56RYy0-5cps
0
 
LVL 1

Expert Comment

by:Shaun_King_23
ID: 38300038
also try enabling CURLOPT_VERBOSE => true;
in the $opts array.

incase you have any curl errors.

also if you want:
if its successful
i want to display product name, brand_name, count.

you will need to pass that information in some sort of request.
as this is a call which just talks to vend and send/revieve the json code.

so you will need to create different files for products, customer etc... which will call this script to send it to the correct account.

you will then need to create different set of curl options for products, customers etc... which you could have a main functions file which will hold the different options which you can call for each file you create.

so for Products you will be send a request of

curl -H 'Accept: application/json' -H 'Content-Type: application/json' \

  -u "vender@mydomain.com:mysekretpassword" \ this will have your secretpassword here

  -d ‘{“data”:...}’ \ // this will be the json code generated in you code or a file

https://myvenddomain.vendhq.com/api/products // link you will be posting to $url

so this will get a full list of all your products.

hope this helps.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:ammadeyy2020
ID: 38300054
<?php
/**
 *
 * A class made for utility methods around Vend's API
 *
 *
 */
class VendApiUtils {

    /**
     * A simple static method to call Vend API urls
     *
     * @param string $url
     * @param string $username
     * @param string $password
     * @param array  $params	<OPTIONAL>
     */
    public static function requestVendApiUrl($url, $username, $password, $params = array())
    {
        // is cURL installed?
        if (!function_exists('curl_init')) {
            throw new Exception('CURL is not installed!');
        }

        // Create a new cURL instance
		$url = "https://test.vendhq.com";       // declare web address 
		curl_setopt($session, CURLOPT_VERBOSE, true); // Display communication with server
        $ch = curl_init();
        
        $opts = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
        CURLOPT_TIMEOUT => 120,
        CURLOPT_FAILONERROR => 1,
        CURLOPT_HTTPAUTH => CURLAUTH_ANY, 
        CURLOPT_USERPWD => "$username:$password"         
        );

        // Assign the cURL options
        curl_setopt_array($ch, $opts);
        
        // Get the response
        $response = curl_exec($ch);
        
        // Close cURL
        curl_close($ch);
        
        // Execute the request & get the response
        return $response;
    }
}

Open in new window


attached new code, still blank page
0
 

Author Comment

by:ammadeyy2020
ID: 38300084
i have created a store for testing,
store url is
https://vendstores.vendhq.com/
storeusername is : vendstores@hotmail.com


can someone help to modify the code to successfully login to url using curl
0
 
LVL 1

Expert Comment

by:Shaun_King_23
ID: 38300283
create this page which will call the function.

<?php
include_once 'VendApiUtils.php';

$response = VendApiUtils::requestVendApiUrl('https://vendstores.vendhq.com/api/products','vendstores@hotmail.com:','test123','');

echo $response;
?>

Open in new window


and make sure your username and password are correct.

and comment out

//CURLOPT_POST => 1,
//CURLOPT_POSTFIELDS => array('data' => json_encode($params)),

within the first file.

so the code i provided above should be in it's own file index.php

and the large file you have with the curl optiions should be named VendApiUtils.php

then run index and see what you get
0
 
LVL 1

Expert Comment

by:Shaun_King_23
ID: 38300334
0
 

Author Comment

by:ammadeyy2020
ID: 38300605
<?php
/**
*
* A class made for utility methods around Vend's API
*
*
*/
class VendApiUtils {

/**
* A simple static method to call Vend API urls
*
* @param string $url
* @param string $username
* @param string $password
* @param array $params <OPTIONAL>
*/
public static function requestVendApiUrl($url, $username, $password, $params = array())
{
// is cURL installed?
if (!function_exists('curl_init')) {
throw new Exception('CURL is not installed!');
}

// Create a new cURL instance
$ch = curl_init();

$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
//CURLOPT_POST => 1,
//CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => "$username:$password" ,
CURLOPT_CUSTOMREQUEST, 'GET'
);

// Assign the cURL options
curl_setopt_array($ch, $opts);

// Get the response
$response = curl_exec($ch);

// Close cURL
curl_close($ch);

// Execute the request & get the response
return $response;
}
}

$params = array('key' => 'value');

Open in new window


<?php
include_once 'VendApiUtils.php';

$response = VendApiUtils::requestVendApiUrl('https://vendstores.vendhq.com/api/products', 'testuser', 'test123');

echo $response;
?>

still no results, showing blank page
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 38309722
The "blank page" symptom is often the result of turning off error reporting, then getting an error.  PHP won't tell you about the error, because the error reporting has been suppressed.  That is fairly common in a production environment, but it's fatal in a development environment where you really need to see the error messages.  You may want to add the following at the top of your scripts so you can see if there are any errors:

<?php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

Open in new window

And this code snippet will show you how to get diagnostics if CURL fails for any reason.

<?php // RAY_curl_example.php
error_reporting(E_ALL);


// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl
( $url
, $get_array=array()
, $timeout=3
, $error_report=TRUE
)
{
    // PREPARE THE ARGUMENT STRING IF NEEDED
    $get_string = NULL;
    foreach ($get_array as $key => $val)
    {
        $get_string
        = $get_string
        . $key
        . '='
        . urlencode($val)
        . '&';
    }
    $get_string = rtrim($get_string, '&');
    if (!empty($get_string)) $url .= '?' . $get_string;

    // START CURL
    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE THIS BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  ); // HISTORY
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'  ); // HISTORY
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1'  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );

    // THIS SEEMS TO LET IT WORK WITH HTTPS SITES
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}




// USAGE EXAMPLE - PUT YOUR FAVORITE URL HERE
$url = "http://finance.yahoo.com/d/quotes.csv";

// PUT YOUR ARRAY OF KEY=>VALUE PAIRS HERE
$arg = array
( 's' => 'lulu'
, 'f' => 'snl1c1ohgvt1'
)
;

// MAKE THE CALL
$htm = my_curl($url, $arg, 2, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT WE GOT
echo "<pre>";
var_dump($arg);
echo PHP_EOL . "<b>$url</b>";
echo PHP_EOL . htmlentities($htm);
echo PHP_EOL;

Open in new window

HTH, ~Ray
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month13 days, 14 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question