Добрый день. В корне сайта есть файл, который по задумке должен принимать GET запрос, в котором в качестве параметра указал id товара, и формировать POST запрос на добавления товара в корзину. Код файла: PHP: <?php $product_id = $_GET[product_id]; $url = 'index.php?route=checkout/cart/add'; $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'content' => http_build_query([ 'product_id' => $product_id, ]) ] ]); echo file_get_contents($url, false, $context); ?> Целый день пытаюсь реализовать идею. Подскажите, почему не работает?
Что хотите сделать? Зачем вам промежуточное звено в виде GET-обработчика? Или лишний хвост в виде POST-обработчика?
@miketomlin Затеял это для того что-бы из amp страницы добавить товар в корзину. amp не любят onclick на кнопках. Вот и пришла в голову эта идея. Передать айди товара в файл в виде get а он сформирует post. Вот фрагмент файла, который принимает пост запрос: PHP: public function add() { $this->load->language('checkout/cart'); $json = array(); if (isset($this->request->post['product_id'])) { $product_id = (int)$this->request->post['product_id']; } else { $product_id = 0; } $this->load->model('catalog/product'); $product_info = $this->model_catalog_product->getProduct($product_id); if ($product_info) { if (isset($this->request->post['quantity']) && ((int)$this->request->post['quantity'] >= $product_info['minimum'])) { $quantity = (int)$this->request->post['quantity']; } else { $quantity = $product_info['minimum'] ? $product_info['minimum'] : 1; } if (isset($this->request->post['option'])) { $option = array_filter($this->request->post['option']); } else { $option = array(); } $product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']); foreach ($product_options as $product_option) { if ($product_option['required'] && empty($option[$product_option['product_option_id']])) { $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']); } } if (isset($this->request->post['recurring_id'])) { $recurring_id = $this->request->post['recurring_id']; } else { $recurring_id = 0; } $recurrings = $this->model_catalog_product->getProfiles($product_info['product_id']); if ($recurrings) { $recurring_ids = array(); foreach ($recurrings as $recurring) { $recurring_ids[] = $recurring['recurring_id']; } if (!in_array($recurring_id, $recurring_ids)) { $json['error']['recurring'] = $this->language->get('error_recurring_required'); } } if (!$json) { $this->cart->add($this->request->post['product_id'], $quantity, $option, $recurring_id); $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart')); // Unset all shipping and payment methods unset($this->session->data['shipping_method']); unset($this->session->data['shipping_methods']); unset($this->session->data['payment_method']); unset($this->session->data['payment_methods']); // Totals $this->load->model('extension/extension'); $totals = array(); $taxes = $this->cart->getTaxes(); $total = 0; // Because __call can not keep var references so we put them into an array. $total_data = array( 'totals' => &$totals, 'taxes' => &$taxes, 'total' => &$total ); // Display prices if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) { $sort_order = array(); $results = $this->model_extension_extension->getExtensions('total'); foreach ($results as $key => $value) { $sort_order[$key] = $this->config->get($value['code'] . '_sort_order'); } array_multisort($sort_order, SORT_ASC, $results); foreach ($results as $result) { if ($this->config->get($result['code'] . '_status')) { $this->load->model('extension/total/' . $result['code']); // We have to put the totals in an array so that they pass by reference. $this->{'model_extension_total_' . $result['code']}->getTotal($total_data); } } $sort_order = array(); foreach ($totals as $key => $value) { $sort_order[$key] = $value['sort_order']; } array_multisort($sort_order, SORT_ASC, $totals); } $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency'])); } else { $json['redirect'] = str_replace('&', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id'])); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); }
Обычного GET-обработчика достаточно. Это норма дублировать AJAX и т.п. обычными обработчиками, правда для добавления в корзину чаще используется POST, но вы можете в качестве эксперимента использовать GET, по тому же адресу или по др., как пытаетесь это сделать сейчас. --- Добавлено --- Т.е. тело обработчика будет тем же самым. Вы можете использовать для разделения «алиасы», выполняя отличающиеся действия по условию с именем алиаса, либо из двух разных обработчиков вызывать «основное тело».
Выполняйте аналогичный код и по GET-запросу. Чтобы не дублировать код физически, используйте подпрограммы и т.п. Использовать в данном случае «вложенный» HTTP-запрос – это тот еще костыль. Вынужден это сказать, хотя обычно отношусь к выкладываемому другими коду не столь критично. В общем без обид.