PHP curl_setopt:变量不起作用代替URL字符串

时间:2015-02-12 12:29:11

标签: php curl

我在php中使用CURL,我使用CURL之类的东西

      $url = "http://exampledomain.com";
      $smsURL = $url;

      $curl = curl_init();
      curl_setopt ($curl, CURLOPT_URL, $smsURL);
      curl_exec ($curl);
      curl_close ($curl);

这不起作用,但如果我在curl_setopt()中用“http://exampledomain.com”代替“$ smsURL”;它会工作正常。我的代码在哪里出问题?我错过了什么?

原始代码

          $url = $this->conf['sms_getway_url'];
      $url .= '&recipient=' . $_POST['txt_customer_contact_no'];
      $url .= '&sender=' . strtoupper($saloon_info['saloon_name']);
      $url .= '&is_payor=' . $this->conf['sms_is_payor'];
      $url .= '&pay_amount=' . $this->conf['sms_pay_amount'];
      $url .= '&token=5ce7467e9ec045cbbac448ba5a422a02';
      //$url .= '&customer_num=' . $this->conf['sms_customer_num'] . $saloon_id;
      $url .= '&customer_num=' . $this->conf['sms_customer_num'];
      $appointment_time = date('H:i', strtotime($app_start_time));
      $employee_name = $_POST['hdn_selected_employee_name']; //$value['id_employee'];
      //$sms_msg = "Hey. Recalling that I await tomorrow at. " . $appointment_time . " Regards " . $employee_name . ", " . $saloon_name . ". ";
      $sms_msg = t('msg_sms_book_appointment', array('%emp_name' => $employee_name, '%saloon_name' => $_POST['hdn_selected_saloon_name'], '%time' => $appointment_time));
      $url .= '&sms_msg=' . $sms_msg;

        $smsURL = $url;

        $curl = curl_init();
        curl_setopt ($curl, CURLOPT_URL, $smsURL);
        curl_exec ($curl);
        curl_close ($curl);

由于

1 个答案:

答案 0 :(得分:1)

您可以从片段组成URL,但不能正确编码值。有些字符在网址中具有特殊含义(/?&=%,{{1}还有一些)。当它们出现在查询字符串的值中时,必须对它们进行编码,以保留它们的字面含义。

PHP帮助您实现此目标,函数+可用于在创建查询字符串时单独编码每个值。像这样:

urlencode()

但是,因为这是一项繁琐的工作,它也提供了一种更简单的方法。将所需的所有值放入数组中,使用变量名称作为键,然后将数组传递给函数http_build_query()。无需再拨打$url = $this->conf['sms_getway_url']; $url .= '&recipient=' . urlencode($_POST['txt_customer_contact_no']); $url .= '&sender=' . urlencode(strtoupper($saloon_info['saloon_name'])); ... ; urlencode()负责照顾它。此外,它还在变量和等号(http_build_query())之间添加&符号(&)。

代码是这样的:

=

查看HTTP status codes列表以获取更多详细信息。