Yii2 redirecting isn't working. Why? - php

I am newbie in Yii2, and now I build new app manually (using Mark Safronov book).
I tried to redirect my controller to somewhere and it isn't working.
Like this:
return $this->redirect(array('/site/dashboard'));
I think it depends on my settings, do you have any ideas? I'm using niceurls and this is my httaccess file:
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
It is my View code
And I had next config: common/config/bootstrap.php
Yii::setAlias('yii2_book', dirname(dirname(__DIR__)) . '/yii2_book');
Code in my controller:
public function actionAdd()
{
$customer = new CustomerRecord();
$phone = new PhoneRecord();
if($customer->load(Yii::$app->request->post()) && $customer->validate() && $phone->load(Yii::$app->request->post())){
$this->store($this->makeCustomer($customer, $phone));
return $this->redirect(['index']);
}
return $this->render('add',compact('customer','phone'));
Stack trace:
2018-01-05 11:30:03 [::1][-][-][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Unable to verify your data submission. in /Users/sergejandrejkin/PhpstormProjects/yii2_book/vendor/yiisoft/yii2/web/Controller.php:166
Stack trace:
#0 /Users/sergejandrejkin/PhpstormProjects/yii2_book/vendor/yiisoft/yii2/base/Controller.php(155): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 /Users/sergejandrejkin/PhpstormProjects/yii2_book/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('add', Array)
#2 /Users/sergejandrejkin/PhpstormProjects/yii2_book/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('customers/add', Array)
#3 /Users/sergejandrejkin/PhpstormProjects/yii2_book/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#4 /Users/sergejandrejkin/PhpstormProjects/yii2_book/web/index.php(12): yii\base\Application->run()
#5 {main}
2018-01-05 11:30:03 [::1][-][-][info][application] $_POST = [
'_csrf' => 'oUDxUGHONyj8ER3vQc9cvdpMsCJh6DXlPzsnxRCxfu3AArIlA7lYR8tnbN8UuDf_937iFlKnc6tGVhCNQvQKiA=='
'CustomerRecord' => [
'name' => ''
'birth_date' => ''
'notes' => ''
]
'PhoneRecord' => [
'number' => ''
]
]
$_SERVER = [
'REDIRECT_STATUS' => '200'
'HTTP_HOST' => 'localhost:8888'
'HTTP_CONNECTION' => 'keep-alive'
'CONTENT_LENGTH' => '208'
'HTTP_CACHE_CONTROL' => 'max-age=0'
'HTTP_ORIGIN' => 'http://localhost:8888'
'HTTP_UPGRADE_INSECURE_REQUESTS' => '1'
'CONTENT_TYPE' => 'application/x-www-form-urlencoded'
'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
'HTTP_REFERER' => 'http://localhost:8888/web/customers/add'
'HTTP_ACCEPT_ENCODING' => 'gzip, deflate, br'
'HTTP_ACCEPT_LANGUAGE' => 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
'PATH' => '/usr/bin:/bin:/usr/sbin:/sbin'
'SERVER_SIGNATURE' => ''
'SERVER_SOFTWARE' => 'Apache/2.2.31 (Unix) mod_wsgi/3.5 Python/2.7.13 PHP/7.0.15 mod_ssl/2.2.31 OpenSSL/1.0.2j DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.24.0'
'SERVER_NAME' => 'localhost'
'SERVER_ADDR' => '::1'
'SERVER_PORT' => '8888'
'REMOTE_ADDR' => '::1'
'DOCUMENT_ROOT' => '/Users/sergejandrejkin/PhpstormProjects/yii2_book'
'SERVER_ADMIN' => 'you#example.com'
'SCRIPT_FILENAME' => '/Users/sergejandrejkin/PhpstormProjects/yii2_book/web/index.php'
'REMOTE_PORT' => '49253'
'REDIRECT_URL' => '/web/customers/add'
'GATEWAY_INTERFACE' => 'CGI/1.1'
'SERVER_PROTOCOL' => 'HTTP/1.1'
'REQUEST_METHOD' => 'POST'
'QUERY_STRING' => ''
'REQUEST_URI' => '/web/customers/add'
'SCRIPT_NAME' => '/web/index.php'
'PHP_SELF' => '/web/index.php'
'REQUEST_TIME_FLOAT' => 1515148203.45
'REQUEST_TIME' => 1515148203
'argv' => []
'argc' => 0
]

I've had same issue. Considering store(…) method works fine, try to add Yii::$app->end() after redirect. So
return $this->redirect(['index']);
becomes
$this->redirect(['index']);
Yii::$app->end();

The exception says:
yii\web\BadRequestHttpException: Unable to verify your data submission.
This tell you 2 things:
bad request exception (http code 400): Is a server response that is sent when the request done by the browser is invalid. Checking the exception's stacktrace you can see its thrown in the beforeAction of the actionAdd so your redirect isnt the problem, as the exception is before your code.
Yii usually use this exception when the CSRF check is invalid, so you should check this page

check it out , do you have any echo before that ?
if have just clear it by ob_end_clean();
if any echo or header have exist before redirect , it's wont be work !
try :
flush();
or try
ob_start()
if no one works try javascript method :
echo "<script type='text/javascript'> window.location='http://your complete url .. '; </script>";
that will works 100% ,good luck .

Yes please check your config settings.
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
],
]
Also your mod_rewrite module should be enabled.
Hope it helps!

Related

PHP ignores "Content-Type: application/x-www-form-urlencoded"

My executable (C++ compiled with Visual Studio) communicates with the PHP webserver to submit data via POST. It worked as designed for years but suddenly stopped working correctly in January 2023. The only change which may happen is an upgrade of the webserver to PHP-8, and a regular Windows update, which changed WININET.DLL used by executable to send HTTP requests.
I am using the code like this (with my variables appropriately defined):
HINTERNET hSession = InternetOpen( “lpszAgent”, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect( hSession, “server.XXX.com”, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
LPCSTR FAR* rgpszAcceptTypes = { _T("*/*"), NULL };
HINTERNET hRequest = HttpOpenRequest( hConnect, "POST", “path_to_script.php”, NULL, NULL, rgpszAcceptTypes, 0, NULL);
LPCSTR lpszHeaders = "Content-Type: application/x-www-form-urlencoded";
DWORD dwHeadersLength = strlen(lpszHeaders);
LPCSTR pfrmdata = "a=b&etc";//correctly encoded
DWORD dwOptionalLength = strlen(pfrmdata);
bool ok = HttpSendRequest(hRequest, lpszHeaders, dwHeadersLength, (void*)pfrmdata, dwOptionalLength);
Everything works without any errors. However, on the server side, I get an empty POST and the following headers:
SERVER:
array (
'LSPHP_ENABLE_USER_INI' => 'on',
'PATH' => '/usr/local/bin:/usr/bin:/bin',
'TEMP' => '/tmp',
'TMP' => '/tmp',
'TMPDIR' => '/tmp',
'PWD' => '/',
'HTTP_ACCEPT' => '*/*',
'HTTP_CONNECTION' => 'Keep-Alive',
'CONTENT_LENGTH' => '0',
'HTTP_HOST' => ‘Correct ',
'HTTP_USER_AGENT' => 'Correct',
'HTTP_CACHE_CONTROL' => 'no-cache',
'REDIRECT_UNIQUE_ID' => 'Y82i1YUhgzjQfeXqYUTbfQAAAH8',
'REDIRECT_QS_SrvConn' => '70',
'REDIRECT_QS_AllConn' => '75',
'REDIRECT_QS_ConnectionId' => '167442094953986927446367',
'REDIRECT_HTTPS' => 'on',
'REDIRECT_SSL_TLS_SNI' => 'Correct',
'REDIRECT_STATUS' => '200',
'UNIQUE_ID' => 'Y82i1YUhgzjQfeXqYUTbfQAAAH8',
'QS_SrvConn' => '70',
'QS_AllConn' => '75',
'QS_ConnectionId' => '167442094953986927446367',
'HTTPS' => 'on',
'SSL_TLS_SNI' => 'Correct',
'SERVER_SIGNATURE' => '',
'SERVER_SOFTWARE' => 'Apache',
'SERVER_NAME' => 'Correct ',
'SERVER_ADDR' => 'Correct',
'SERVER_PORT' => '443',
'REMOTE_ADDR' => 'Correct',
'DOCUMENT_ROOT' => 'Correct',
'REQUEST_SCHEME' => 'https',
'CONTEXT_PREFIX' => '',
'CONTEXT_DOCUMENT_ROOT' => 'Correct',
'SERVER_ADMIN' => 'Correct',
'SCRIPT_FILENAME' => 'Correct',
'REMOTE_PORT' => '8700',
'REDIRECT_URL' => 'Correct',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'GET',
'QUERY_STRING' => '',
'REQUEST_URI' => 'Correct',
'SCRIPT_NAME' => 'Correct',
'PHP_SELF' => 'Correct',
'REQUEST_TIME_FLOAT' => 1674420950.062037944793701171875,
'REQUEST_TIME' => 1674420950,
'argv' =>
array (
),
'argc' => 0,
)
As you may see CONTENT_LENGTH=0 and CONTENT_TYPE is absent at all, while it should be “application/x-www-form-urlencoded”, and REQUEST_METHOD is GET instead of POST.
I understand that CONTENT_TYPE is essential. If it is not there then POST data is not read, REQUEST_METHOD becomes GET, and CONTENT_LENGTH becomes zero and my data submitted consequently ignored by the server.
So, the problem is that CONTENT_TYPE has disappeared from the request. But why? What is wrong now? Please, recall that it used to all work just fine before January 2023.
I tried to downgrade PHP to 7.4 - it did not help.
I put my script on a different server under a site which uses PHP 7.4 - it started working!
I made a new test site on the other server with the latest PHP 8.2 - it does not work.
Downgraded PHP 8.2 to PHP 7.4 - still did not help.
I installed a new test site on other server and set PHP 7.4 during the installation - it now works!
I upgaded it to PHP 8.2 - stopped working.
I downgraded back to PHP 7.4 - still does not work.
Could this have been more confusing? I beg you to give me some ideas. Thank you!
Update:
Thank you so much for all the comments. Indeed, it must be a redirection of HTTP to HTTPS at fault. The hosting provider (Hostmonster) has recently installed free SSL certificates to all the domains and made all domains use HTTPS. They think they have done a great job and refuse to understand my problem. My executable still works via HTTP, and the redirection breaks it. I am failing to explain to them what I need at the level of support I get from them. They think it all works great and advise me to hire a developer :) They do not seem to provide an option to stop redirection.
I think, I should be able to disable their server-wide redirection from the local .htaccess file. But I am not sure how to do that. I guess, I need to see which method they used to enable it, but I could not figure out how to see the Apache configuration for my domain/location on a shared server.
Could you guess which lines in the local .htaccess would possibly disable the automatic redirection from HTTP to HTTPS?

Amazon Polly AudioStream is always empty

I am trying to get Polly to read something for me, using PHP.
I have created a new project, installed Amazon composer require aws/aws-sdk-php and then created a file with code from SDK documentation example and modified a few minor things such as changing credential from default to value, var_dump to var_export and finally saved the content of the stream to file
<?php
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\Polly\PollyClient;
use Aws\Credentials\Credentials;
// Create a PollyClient
$client = new Aws\Polly\PollyClient([
//'profile' => 'default',
'credentials' => new Credentials('XXXXXXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),
'version' => '2016-06-10',
'region' => 'us-east-2'
]);
try {
$result = $client->synthesizeSpeech([
'Text' => 'Hello',
'OutputFormat' => 'json', //json|mp3|ogg_vorbis|pcm
'VoiceId' => 'Joanna',
]);
var_export($result);
$data = $result->get('AudioStream')->getContents();
echo "\n\n";
var_export($data);
$file = fopen('test.txt','w+');
fwrite($file,$data);
fclose($file);
} catch (AwsException $e) {
echo $e->getMessage() . "\n";
}
The result I'm getting is following
Aws\Result::__set_state(array(
'data' => array (
'AudioStream' => GuzzleHttp\Psr7\Stream::__set_state(array(
'stream' => NULL,
'size' => NULL,
'seekable' => true,
'readable' => true,
'writable' => true,
'uri' => 'php://temp',
'customMetadata' => array (),
)),
'ContentType' => 'application/x-json-stream',
'RequestCharacters' => '5',
'#metadata' => array (
'statusCode' => 200,
'effectiveUri' => 'https://polly.us-east-2.amazonaws.com/v1/speech',
'headers' => array (
'x-amzn-requestid' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
'x-amzn-requestcharacters' => '5',
'content-type' => 'application/x-json-stream',
'transfer-encoding' => 'chunked',
'date' => 'Sat, 18 Sep 2021 05:11:20 GMT',
),
'transferStats' => array (
'http' => array (
0 => array (),
),
),
),
),
'monitoringEvents' => array (),
))
''
As you can see the size of the AudioStream is null (nothing in it) and also the created file is also empty since there is nothing in the stream to read.
If I change a credential to an invalid string, I get errors, and with the valid credential, the status code is 200, which makes me believe that my request is successful.
I changed voiceId to any other valid or invalid id and even changed the region with others with valid values getting status 200 and with invalid ones getting error messages, but I'm still not getting anything out of polly, it doesn't feel like talking!
Note: When I run $arr_voices = $polly->describeVoices();, I can read list of the voices without error.
Note: I had the same issue with .NET SDK too, which makes me think either there is something wrong with my request or some error message is missing from API.
Question
What I'm doing wrong?
You're not doing anything wrong, but it only outputs JSON if you're looking for speech marks. Try switching to an audio output format like MP3 as shown below.
$result = $client->synthesizeSpeech([
'Text' => 'Hello',
'OutputFormat' => 'mp3', //json|mp3|ogg_vorbis|pcm
'VoiceId' => 'Joanna',
]);
If you're looking for speech marks- metadata on the speech that will be synthesized- you need to specify SpeechMarkTypes as shown here https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-polly-2016-06-10.html#synthesizespeech

Bad Request, Missing required parameters Yii2

I have some problem with GET request.
If I send GET request like a /api/v1/users/user-settings?key=model-manual-user-settings in my app,
I get response like this:
{"name":"Bad Request","message":"Missing required parameters: key", "code":0, "status":400, "type":"yii\\web\\BadRequestHttpException"}
Run method in my action
/**
* Получение пользовательских данных по ключу
*
* #param string $key Ключ пользовательских параметров
* #return array
*/
public function run($key)
{
$component = new UserSettingsComponent($key);
return $component->getSettingsWithParams();
}
Piece of yii2 log file:
2018-05-25 18:58:52 [127.0.0.1][1][tsdsfjgmllh43vfb264qimc3fv][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Missing required parameters: key in /var/www/arm/vendor/yiisoft/yii2/web/Controller.php:149
Stack trace:
#0 /var/www/arm/vendor/yiisoft/yii2/base/Action.php(88): yii\web\Controller->bindActionParams(Object(api\actions\users\user_settings\IndexAction), Array)
#1 /var/www/arm/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\Action->runWithParams(Array)
#2 /var/www/arm/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('index', Array)
#3 /var/www/arm/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('v1/users/user-s...', Array)
#4 /var/www/arm/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#5 /var/www/arm/api/web/index.php(15): yii\base\Application->run()
#6 {main}
2018-05-25 18:58:52 [127.0.0.1][1][tsdsfjgmllh43vfb264qimc3fv][info][application] $_GET = [
'args' => ''
]
...
$_SERVER = [
'USER' => 'www-data'
'HOME' => '/var/www'
'HTTP_X_COMPRESS' => 'null'
'HTTP_COOKIE' => 'PHPSESSID=tsdsfjgmllh43vfb264qimc3fv; _csrf=f70915c9bfa9e77535bd94fa3287cb4347f248c120e26332eca5a1cebc7dba4ca%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22mNhgJJk1mrM_luk3c26x-dBOVUY62fpo%22%3B%7D'
'HTTP_ACCEPT_LANGUAGE' => 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
'HTTP_ACCEPT_ENCODING' => 'gzip, deflate'
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
'HTTP_UPGRADE_INSECURE_REQUESTS' => '1'
'HTTP_CACHE_CONTROL' => 'max-age=0'
'HTTP_CONNECTION' => 'keep-alive'
'HTTP_HOST' => 'arm.local'
'REDIRECT_STATUS' => '200'
'SERVER_NAME' => 'arm.local'
'SERVER_PORT' => '80'
'SERVER_ADDR' => '127.0.0.1'
'REMOTE_PORT' => '42354'
'REMOTE_ADDR' => '127.0.0.1'
'SERVER_SOFTWARE' => 'nginx/1.10.3'
'GATEWAY_INTERFACE' => 'CGI/1.1'
'REQUEST_SCHEME' => 'http'
'SERVER_PROTOCOL' => 'HTTP/1.1'
'DOCUMENT_ROOT' => '/var/www/arm'
'DOCUMENT_URI' => '/api/web/index.php'
'REQUEST_URI' => '/api/v1/users/user-settings?key=wagons-array-user-settings'
'SCRIPT_NAME' => '/api/web/index.php'
'CONTENT_LENGTH' => ''
'CONTENT_TYPE' => ''
'REQUEST_METHOD' => 'GET'
'QUERY_STRING' => 'args'
'SCRIPT_FILENAME' => '/var/www/arm/api/web/index.php'
'FCGI_ROLE' => 'RESPONDER'
'PHP_SELF' => '/api/web/index.php'
'REQUEST_TIME_FLOAT' => 1527274732.2266
'REQUEST_TIME' => 1527274732
]
Url manager config:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'/settings' => '/settings',
'/<action>' => '/site/<action>',
'/<controller>' => '/<controller>/<action>',
'/<controller>/<action>' => '/<controller>/<action>',
'/<module>/<action>' => '/<module>/default/<action>',
[
'class' => 'yii\rest\UrlRule',
'controller' => [
# some controllers
'v1/users/user-groups',
'v1/users/user-settings',
],
'pluralize'=>false
],
],
]
section of nginx config
location /api/ {
root /var/www/arm/api/web;
try_files $uri /api/web/index.php?args;
}
Also I see these lines in my nginx log file:
2018/05/25 21:56:21 [error] 27040#27040: *74 FastCGI sent in stderr: "PHP message: PHP Warning: Invalid argument supplied for foreach() in /var/www/arm/vendor/yiisoft/yii2/helpers/BaseArrayHelper.php on line 123" while reading response header from upstream, client: 127.0.0.1, server: arm.local, request: "GET /api/v1/users/user-settings?key=wagons-array-user-settings HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host: "arm.local"
2018/05/25 21:58:52 [error] 27040#27040: *80 FastCGI sent in stderr: "PHP message: PHP Warning: Invalid argument supplied for foreach() in /var/www/arm/vendor/yiisoft/yii2/helpers/BaseArrayHelper.php on line 123" while reading response header from upstream, client: 127.0.0.1, server: arm.local, request: "GET /api/v1/users/user-settings?key=wagons-array-user-settings HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host: "arm.local"
Note
It's began after update yii2 to 2.0.15.1 and php 7.2.5.
I try downgrade to php7.2.3, problem still exists.
Production version my app used yii2 v2.0.13 and php 7.2.3 and I haven`t this problem.
If I downgrade yii2 version to 2.0.13 I get this error:
yiisoft/yii2-gii 2.0.7 requires yiisoft/yii2 ~2.0.14 -> satisfiable by yiisoft/yii2[2.0.x-dev]
resp. if I try downgrade yiisoft/yii2-gii to v2.0.0 I get this error:
The requested package yiisoft/yii2-gii (locked at 2.0.7, required as 2.0.0) is satisfiable by yiisoft/yii2-gii[2.0.7]
server nginx + php-fpm
Yii version 2.0.15.1
php version 7.2.5-1
nginx version 1.10
Someone have any ideas?
You have a typo in your nginx configuration, you missed $ before args:
location /api/ {
root /var/www/arm/api/web;
try_files $uri /api/web/index.php?$args;
}

Error when using SoapClient but not when using the web browser

Using the Chronopost Web Services.
When using this post HTTP request in a web browser (account number and password are hidden there, so you can't test yourself unless you have a Chronopost ID) :
https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS/shippingWithReservationAndESDWithRefClientPC?subAccount=000&accountNumber=ACCOUNT_NUMBER&password=PASSWORD&shipperCivility=E&shipperName=DELBET&shipperName2=RICHARD&shipperAdress1=1%20rue%20des%20accents&shipperZipCode=28500&shipperCity=Ste%20Gemme%20Moronval&shipperCountry=FR&shipperCountryName=France&shipperContactName=Richard%20Delbet&shipperEmail=richard.delbet#telintrans.fr&shipperPhone=0123456789&shipperMobilePhone=0601020304&recipientCivility=E&recipientName=MALKA&recipientName2=DAVID&recipientAdress1=1%20rue%20des%20essais&recipientZipCode=75001&recipientCity=Paris&recipientCountry=FR&recipientCountryName=France&recipientContactName=David%20Malka&recipientEmail=david.malka#telintrans.fr&recipientPhone=0222426789&recipientMobilePhone=0622220304&shipperRef=CMD1&recipientRef=ART1&productCode=01&shipDate=27/07/2010%2010:00:00&shipHour=10&weight=2&service=0&objectType=MAR&modeRetour=1&mode=PDF
I have a valid response with all the correct datas.
When using SoapClient with exactly the same parameters :
$client = new \SoapClient("http://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl");
$data = [
'subAccount' => '000',
'accountNumber' => ACCOUNT_NUMBER,
'password' => PASSWORD,
'shipperCivility' => 'E',
'shipperName' => 'DELBET',
'shipperName2' => 'RICHARD',
'shipperAdress1' => '1%20rue%20des%20accents',
'shipperZipCode' => '28500',
'shipperCity' => 'Ste%20Gemme%20Moronval',
'shipperCountry' => 'FR',
'shipperCountryName' => 'France',
'shipperContactName' => 'Richard%20Delbet',
'shipperEmail' => 'richard.delbet#telintrans.fr',
'shipperPhone' => '0123456789',
'shipperMobilePhone' => '0601020304',
'recipientCivility' => 'E',
'recipientName' => 'MALKA',
'recipientName2' => 'DAVID',
'recipientAdress1' => '1%20rue%20des%20essais',
'recipientZipCode' => '75001',
'recipientCity' => 'Paris',
'recipientCountry' => 'FR',
'recipientCountryName' => 'France',
'recipientContactName' => 'David%20Malka',
'recipientEmail' => 'david.malka#telintrans.fr',
'recipientPhone' => '0222426789',
'recipientMobilePhone' => '0622220304',
'shipperRef' => 'CMD1',
'recipientRef' => 'ART1',
'productCode' => '01',
'shipDate' => '27/07/2010%2010:00:00',
'shipHour' => '10',
'weight' => '2',
'service' => '0',
'objectType' => 'MAR',
'modeRetour' => '1',
'mode' => 'PDF',
];
$response = $client->__soapCall("shippingWithReservationAndESDWithRefClientPC", array($data));
I have an error returned :
object(stdClass)#531 (1) { ["return"]=> object(stdClass)#537 (2) {
["errorCode"]=>
int(1)
["errorMessage"]=>
string(3112) " fr.chronopost.soap.shipping.exception.ValidateException at
fr.chronopost.soap.shipping.util.PopulateUtils.populateSkybill(PopulateUtils.java:355)
at
fr.chronopost.soap.shipping.cxf.ShippingServiceWS.shippingWithReservationAndESDWithRefClientPC(ShippingServiceWS.java:615)
at sun.reflect.GeneratedMethodAccessor1258.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:136)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:82)
at
org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:54)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:56)
at
org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:92)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:220)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:78)
at
org.apache.cxf.transport.servlet.ServletDestination.invoke(ServletDestination.java:92)
at
org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:285)
at
org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:168)
at
org.apache.cxf.transport.servlet.AbstractCXFServlet.invoke(AbstractCXFServlet.java:175)
at
org.apache.cxf.transport.servlet.AbstractCXFServlet.doPost(AbstractCXFServlet.java:153)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at
org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at
org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:776)
at
org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:705)
at
org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:898)
at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:744) " } }
Unfortunately, the error code "1" is described in the documentation as "system error".
One proabably can't help me directly about the Chronopost Web Services, but maybe I'm missing something into the PHP SoapClient object.
Why do I have a correct response when using a web browser and some kind of ValidateException error when using SoapClient ?
When making a SOAP call, you don't need to include URL encoded data strings. Php soapclient encodes the data into XML automatically. So the problem is most likely the validation the service is performing on your data, and it's choking on the % characters. Try changing
'shipDate' => '27/07/2010%2010:00:00'
to
'shipDate' => '27/07/2010 10:00:00'

Privoxy, Tor and cURL using Zend HTTP

I am really stuck in this, and need expert help. Let me explain what I am trying achieve and the setup. I had a script which posts over a https form using Zend_Http_Client. On the server setup I have tor & privoxy running. Everything just worked fine, but now I need to make the code more scalable by running multiple instances of tor & privoxy on the same server.
Hence I shifted the Adapter for Zend from Zend_Http_Client_Adapter_Curl to Zend_Http_Client_Adapter_Proxy . But after changing the adapter I have bumped into a strange error which says - 400 Invalid header received from client and when I dump the object of Zend client, I see the following -
MyWebClientResponse::__set_state(array(
'json' => NULL,
'version' => '1.1',
'code' => 400,
'message' => 'Invalid header received from client',
'headers' =>
array (
'Proxy-agent' => 'Privoxy 3.0.19',
'Content-type' => 'text/plain',
'Connection' => 'close',
),
'body' => 'Invalid header received from client.
',
))
I do not understand what is that I am doing wrong. The code is done in Yii Framework so it is hard to share all the classes and Models, but I am sharing the main parts of the code, which are responsible for this -
$client = MyWebClient::factory();
$adapter = $client->getAdapter();
$adapter->setConfig(array('timeout' => 120,
'proxy_host' => 'localhost',
'proxy_port' => 8124
));
$client->setAdapter($adapter);
$client->setCookieJar(true);
$client->setParameterPost(array(
'name' => 'firstname',
'password' => 'password,
'login' => 'home'
));
$response = $client->setUri('https://www.domain.com/post.php')->requestApi('POST', false);
Here's the constructor of the class MyWebClient, just in case it it required, all other methods are standard.
static public function factory($new = false)
{
if (!isset(self::$client))
{
self::$client = new MyWebClient();
self::$client->setConfig(array(
'adapter' => 'Zend_Http_Client_Adapter_Proxy',
// 'proxy_host' => 'localhost',
// 'proxy_port' => 8118,
'persistent' => false,
'timeout' => 120
));
}
return self::$client;
}
The headers are being set in the requestAPI method and the snippet is -
$headers = array(
'X-PHX' => 'true',
'X-Requested-With' => 'XMLHttpRequest',
'Referer' => 'https://domain.com/index.html',
'User-Agent' => self::getRandomUserAgent()
);
$this->setHeaders($headers);
I would really appreciate help in this regard. Think it's privoxy which is not letting go the request out of the server.
Sachin
Looks like you may need to wrap the user-agent with quotes. Try this when setting the headers and see if that fixes the problem.
$headers = array(
'X-PHX' => 'true',
'X-Requested-With' => 'XMLHttpRequest',
'Referer' => 'https://domain.com/index.html',
'User-Agent' => "'".self::getRandomUserAgent()."'"
);
$this->setHeaders($headers);
Finally I decided to use the native cURL library and the cookieJar which comes with it. It worked like expected.
Cheers,
Sachin

Categories