Home > Software design >  I have having an issue with posting to a URL using cURL init
I have having an issue with posting to a URL using cURL init

Time:10-01

I am working on a small project and have run into a snag. I am attempting to post information to a URL using cURL specifically curl_init. I can make the code work fine when I am placing the full URL into the code, the problem occurs when I try to change an aspect of the URL. For example

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://test.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pdata);

The above code works fine, however if I do something like below the code will error out.

$mode = "one";
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://' . $mode . '.test.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $pdata);

Am I doing something particularly wrong or is this type of URL manipulation not accepted by the function?

Thanks all!

CodePudding user response:

This is a simple string quotation error and has nothing to do with cURL or URLs really - although in this case it's causing you to have formed an incorrect URL. This is the URL your code produces -

https://' . one . '.test.com

Demo: http://sandbox.onlinephpfunctions.com/code/e2a878e59681f9c731140d5005043eb7bb2ab91a

Whereas clearly what you wanted was

https://one.test.com

You can fix this in two ways - one using string concatention properly (by ending the first string with " instead of ' and starting the second one similarly), and the other using PHP's interpolation functionality to simply place the variable within a single string.

Method 1:

$mode = "one";
curl_setopt($ch, CURLOPT_URL, "https://".$mode.".test.com");

Method 2:

$mode = "one";
curl_setopt($ch, CURLOPT_URL, "https://$mode.test.com");

You'd have the same sort of problem with any string - you can't start a string with " and then finish it with ' and expect it to produce valid output. The delimiter needs to be the same at both ends.

In this specific case you've actually just ended up with one long string, so you don't have a syntax error, but it results in a string which doesn't contain what you expected it to, causing the cURL request to fail because the URL is wrong.

CodePudding user response:

I think is because your are closing with single and double try with: "https://" . $mode . ".test.com"

  •  Tags:  
  • php
  • Related