PHP and Wordpress - Submit URL using wp_http - php

I have a URL that is generated by php and ends up as a string called $myurl and looks like this...
http://www.mydomain.com/submit.php?favcol=blue&favfood=crisps&favday=Tuesday
I am trying to use the following snippet to submit this url
$request = new WP_Http();
$response = $request->post($myurl, array());
It is not working, although if I submit the URL manually then it does work.
What am I doing wrong?

I might be wrong, but it seems to me that you are not posting anything actually, but use the url so the page can handle the GET paramaters from the url? Try this:
$url = 'http://www.mydomain.com/submit.php?favcol=blue&favfood=crisps&favday=Tuesday';
$request = new WP_Http;
$result = $request->request( $url );

Edit I've just checked the class-http.php file and I'm wrong, there is a post method defined.
function post($url, $args = array()) {
$defaults = array('method' => 'POST');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
}
Which is still just a function created specifically to do:
$request->request($myurl, array('method'=>'post', 'data' => 'whatever'));
Alternatively, you can just use the wrapper that was created explicitly for this.
wp_remote_post($url, array());

Related

All validation errors displaying in CMS (pulling data from api call into CMS)

I'm trying to pull data from an API and when the information is pulled into the fieldsets within my CMS, I want to ensure that whatever has been pulled from the API is validated properly with the rules I currently have set up within my CMS (eg. an image can be no bigger that 1920x1080 in dimensions).
Here is my code:
use App\Utilities\BardUtil;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Http;
use Statamic\Eloquent\Entries\EntryModel;
use Statamic\Events\EntrySaved;
use Statamic\Facades\Entry;
public function handle(EntrySaved $event): void
{
$entry = $event->entry->model();
if ($entry->collection != 'companies') {
return;
}
$data = collect($entry->data);
if (!isset($data['tickers'][0])) {
return;
}
$tickerId = $data['tickers'][0];
$ticker = EntryModel::find($tickerId);
if ($ticker && $ticker->title) {
$tickerTitle = $ticker->title;
$response = Http::get('apicallurlexample');
$fields = $event->entry->blueprint()->fields();
$items = $response->json('results.0');
$items['companyName'] = $items['exchangeName'];
$data = $data->merge($items);
$data['slug'] = $entry->slug;
$data['date'] = $entry->date;
$fields = $fields->addValues($data->toArray());
$collection = $event->entry->collection();
$site = $event->entry->site();
$rules = Entry::updateRules($collection, $site);
$replacements = [
'id' => $entry->id,
'collection' => $collection,
'site' => $site,
];
$fields
->validator()
->withRules($rules)
->withReplacements($replacements)
->validate();
$event->entry->data($fields->values()->all());
$event->entry->saveQuietly();
}
}
I think the issue lies within the following code:
$fields
->validator()
->withRules($rules)
->withReplacements($replacements)
->validate();
What's happening when I save the company details is that it displays all the validation errors, even if the data hasn't went against any of the rules. Any help would be appreciated and thanks in advance.
Sorry for the rather late reply but thought I'd update this thread anyways for others who find this later.
Statamic only uses the validation rules you define in your blueprint/fieldset when saving entries/terms/etc in the Control Panel.
When you save data manually (eg. via PHP or directly editing the Markdown files), no validation checks are ran on it. You'll need to manually do any kind of validation in your code, before the entry is created in Statamic.

magento : how to add parameter with soap request

I am new to Magento I tried calling a category level using the Magento SOAP API with parent category id. I used the following code:
<?php
$proxy = new SoapClient('http://domain/index.php/api/soap/?wsdl');
$session = $proxy->login('user', 'password');
$result = $proxy->call($session,'catalog_category.level');
echo json_encode($result);
?>
For the above code "Default Category" details are coming, I tried to call some other category by using the following code:
$result = $proxy->call($session,'catalog_category.level',12);
This is not working:
$arguments = array( 'parentCategory' => 12);
$result = $proxy->call($session,'catalog_category.level',$arguments);
This is also not working:
Then I tried calling category tree using following code:
<?php
$proxy = new SoapClient('http://domain/index.php/api/soap/?wsdl');
$session = $proxy->login('user', 'password');
$result = $proxy->call($session,'catalog_category.tree');
echo json_encode($result);
?>
It shows the entire category tree so it means API is working but whenever I try to pass an argument it shows server not found error.
Can anyone please tell me how to pass arguments with the request.
You will need to call it like
$proxy->call($sessionId, 'category.level', array(null, null, 12));
For more information about the function check class
Mage_Catalog_Model_Category_Api
function level($website = null, $store = null, $categoryId = null)
If you want to pass particular website and store you can pass it instead of null parameter.
i manage to get output using soapv2. but it is slow compare to soapv1 but it is giving the required out put. the code i use to pass parameter is given as below.
<?php
$proxy = new SoapClient('http://domain/index.php/api/v2_soap/?wsdl=1');
$session = $proxy->login((object)array('username' => 'user', 'apiKey' => 'password'));
$result = $proxy->catalogCategoryTree((object)array('sessionId' => $session->result, 'parentId' => '12'));
echo json_encode($result);
?>

Slim Framework $_GET 404 error

Hello so I have a simple code here which will do an update in a column and redirect to a page based on the GET parameter. My code is here:
In my html:
Move
and in the index.php
$app->get('/user/admin/table/:table_id/move', 'RecycleTable');
function RecycleTable($table_id)
{
$session = new \RKA\Session();
$app = \Slim\Slim::getInstance();
if (!$session->type) {
$app->redirect('/user/login');
}
else {
$sponsorID = $app->request()->get('sponsor');
$db = new db();
$bind = array(
':table_id' => $table_id
);
$update = array(
'status' => '2'
);
$db->update("tables", $update, "tableID = :table_id", $bind);
$db = null;
$app->redirect('/user/admin/table/'.$sponsorID);
}
}
When I try to click Move I get a 404 error. Do I get the parameter sponsor correctly? Or is there something wrong here?
It appears as if your link in the HTML is incorrect. Your route states that the path should be:
Move
not
Move
You are missing the /user/admin/table part which is why you would be receiving a 404. It cannot resolve to the correct route.

Laravel store function changes return data

Quite sure I'm doing something wrong here, just don't know what or where.
I have a Laravel controller that handles an ajax post request and returns the results of a curl request to that ajax call:
public function store()
{
/** Receive long and lat through ajax **/
$long = Input::get('longitude');
$lat = Input::get('latitude');
$location = $lat . "," . $long;
$url = blablable;
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$result = curl_exec($curl);
return $result;
curl_close($curl);
}
This works: the curl returns a JSON array, which gets passed back to the ajax call.
But now I want to save the incoming data to the database:
$location = new Location();
$location->latitude = Input::get('latitude');
$location->longitude = Input::get('longitude');
$location->save();
I add those 4 lines at the top of the function, the data gets saved to the database but the JSON array get's grabbled, somehow <!-- app/models/Location.php --> gets added to the top of the return, making the JSON array invalid.
No clue as to what is causing this so any hints or suggestions are highly appreciated!
-- Edit 1 --
The result of Input::all(); is
array(2) {
["latitude"]=>
string(10) "50.8809794"
["longitude"]=>
string(9) "4.6920714"
}
This is not intended as a solution, but as a way to clean up your code a bit:
You don't need to use curl and can use Request::create() and Route::dispatch() instead.
You should use the protected $fillable attribute in your model, to clean up the new entry.
Your code can become:
public function store()
{
// This is for saving the entry
$location = new Location();
$location->fill(Input::all());
$location->save();
// This is for the cURL
// (assuming this is a GET requst, but other methods are available)
$request = Request::create('/path/to/url/', 'GET');
$response = Route::dispatch($request);
// Do stuff with the $response or just return it
return $response;
}

Is there a Symfony helper for getting the current action URL and changing one or more of the query parameters?

What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?
Thanks!
[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.
Edit:
Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):
url_for('foo',
array_merge($sf_request->getParameterHolder()->getAll(),
array('bar' => 'barz'))
)
If you use this very often I suggest to create your own helper that works like a wrapper for url_for.
Or if you only want a subset of the request parameters, do this:
url_for('foo',
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
(I formated the code this way for better readability)
Original Answer:
I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:
$request->setParameter('key', 'value')
You can obtain the request object by either defining your action this way:
public function executeIndex($request) {
// ...
}
or this
public function executeIndex() {
$request = $this->getRequest();
}
For symfony 1.4 I used:
$current_uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri_params = $sf_request->getParameterHolder()->getAll();
$url = url_for($current_uri.'?'.http_build_query(array_merge($uri_params, array('page' => $page))));
echo link_to($page, $url);
Felix's suggestion is good, however, it'd require you to hard core the "current route"..
You can get the name of the current route by using:
sfRouting::getInstance()->getCurrentRouteName()
and you can plug that directly in url_for, like so:
url_for(sfRouting::getInstance()->getCurrentRouteName(),
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
Hope that helps.
With the same concept than Erq, and thanks to his code, I have made the same with some small changes, since my URL needs to convert some characters. Its generic though and should work with most forms, in order to save the parameters the user has chosen to search for.
public function executeSaveFormQuery(sfWebRequest $request)
{
$sURLServer = "http://";
$sURLInternalUri = "";
$page = "";
$sURLInternalUri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$suri_params = $request->getParameterHolder()->getAll();
$sParams = http_build_query(array_merge($suri_params));
$dpos = strpos($sURLInternalUri, "?");
$sURLConsulta[$dpos] = '/';
$sURL = substr($sURLInternalUri, $dpos);
$dpos = strpos($sURL, "=");
$sURL[$dpos] = '/';
$sURLFinal = $sURLServer . $sURL . '?' . $sParams;
//$this->redirect($this->module_name . '/new');
self::executeNew($request, $sURLFinal);
//echo "var_dump(sURLFinal): ";
//var_dump($sURLFinal);
//echo "<br></br>";
//return sfView::NONE;
}
In executeNew, as easy as:
public function executeNew(sfWebRequest $request, $sURLQuery)
{
//$sURLQuery= "http://";
if ($sURLQuery!= "")
{
$this->form = new sfGuardQueryForm();
//echo "var_dump(sURLQuery)";
//var_dump($sURLQuery);
//echo "<br></br>";
$this->form->setDefault('surl', $sURLQuery);
}
else
{
$this->form = new sfGuardQueryForm();
}
}
echo $sf_context->getRequest()->getUri();

Categories