$_POST is empty in php - php

I have gone through all the responses in this post
print_r($_POST); ===> returns empty array
print_r($_SERVER);
Array ( [HTTP_HOST] => localhost
[HTTP_ACCEPT] => */*
**[HTTP__CONTENT_TYPE]** => application/json; charset=UTF-8"
[CONTENT_LENGTH] => 942
**[CONTENT_TYPE]** => application/x-www-form-urlencoded
[PATH] => /usr/local/bin:/usr/bin:/bin
[SERVER_SIGNATURE] => Apache/2.2.14 (Ubuntu) Server at localhost Port 80
[SERVER_SOFTWARE] => Apache/2.2.14 (Ubuntu)
[SERVER_NAME] => localhost
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 80
[REMOTE_ADDR] => 127.0.0.1
[DOCUMENT_ROOT] => /var/www
[SERVER_ADMIN] => webmaster#localhost
[SCRIPT_FILENAME] => /var/www/slocation.php
[REMOTE_PORT] => 50657
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => POST
[QUERY_STRING] =>
[REQUEST_URI] => /slocation.php
[SCRIPT_NAME] => /slocation.php
[PHP_SELF] => /slocation.php
[REQUEST_TIME] => 1288466907
)
What's the difference between HTTP__CONTENT_TYPE and CONTENT_TYPE?
print_r($HTTP_RAW_POST_DATA); ==> returns correct data posted
file_get_contents('php://input'); ======> returns correct data.
Only $_POST fails.
This is my curl command
$url = "http://localhost/slocation.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('"Content-type: application/json; charset=UTF-8"'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($ch);
UPDATE::::::::::::::::::::::::::::::::::::::::::::::::::
I found a master here

To answer my own question, "What's the difference between HTTP__CONTENT_TYPE and CONTENT_TYPE?"
If you see "HTTP__CONTENT_TYPE", it most probably means you have made mistake in setting the CONTENT-TYPE header field. Probably, when curl doesn't recognize the valid CONTENT_TYPE value, then the wrong value is set to HTTP__CONTENT_TYPE and CONTENT_TYPE takes a default value.

Related

How to authenticate a post request in php

I am trying to implement the HTTP Post Authentication, Which mentioned on this document https://www.clearslide.com/view/mail?iID=YS7LCS8XDPCABFR453DE , I am not able to understand what exactly i have to do to get this working, I tried to dump $_REQUEST and $_SERVER variables.
This is the output i am getting for this $_REQUEST
Array
(
[emailpitchsent] =>
)
And this the output for $_SERVER
Array
(
[HTTP_HMAC] => D4L1ICmRMii32PdCryBkpSNdxY5XDxC_OXsDTEucyzU
[HTTP_DATE] => Thu, 12 Nov 2015 00:50:05 PST
[HTTP_SHA1] => GTRFkX7JYVtDQgvrQeXJmHaCF24=
[CONTENT_LENGTH] => 262
[CONTENT_TYPE] => application/json; charset=UTF-8
[HTTP_HOST] => myhost.com
[HTTP_CONNECTION] => Keep-Alive
[HTTP_USER_AGENT] => Apache-HttpClient/4.5.1 (Java/1.7.0_55)
[PATH] => /sbin:/usr/sbin:/bin:/usr/bin
[SERVER_SIGNATURE] => <address>Apache/2.2.31 (Amazon) Server at myhost.com Port 80</address>
[SERVER_SOFTWARE] => Apache/2.2.31 (Amazon)
[SERVER_NAME] => myhost.com
[SERVER_ADDR] => 0.0.0.0
[SERVER_PORT] => 80
[REMOTE_ADDR] => 0.0.0.1
[DOCUMENT_ROOT] => /var/www/vhosts/myhost.com/httpdocs
[SERVER_ADMIN] => info#myhost.com
[SCRIPT_FILENAME] => /var/www/vhosts/myhost.com/httpdocs/clearslide.php
[REMOTE_PORT] => 47400
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => POST
[QUERY_STRING] => emailpitchsent
[REQUEST_URI] => /clearslide.php?emailpitchsent
[SCRIPT_NAME] => /clearslide.php
[PHP_SELF] => /clearslide.php
[REQUEST_TIME] => 1447318205
)
This i the content of clearslide.php
<?php
$req_dump = print_r($_REQUEST, TRUE);
$ser_dump = print_r($_SERVER,TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fwrite($fp, $ser_dump);
fclose($fp);
What i have to do now to get this thing working, How can i authenticate that request and get the data?.
Thanks
You can get the raw json body with file_get_contents('php://input') or $HTTP_RAW_POST_DATA. Here is a sample of how to verify the signature from the headers. Also, here is a script that can generate a fake request for testing. Let me know if you have any more trouble. :)
Verify the signature
<?php
// https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/Base64#encodeBase64URLSafeString(byte[])
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/', '='), array('-','_',''), $data);
return $data;
}
function extract_message(){
$verb = $_SERVER["REQUEST_METHOD"];
$sha1 = $_SERVER["HTTP_SHA1"];
$content_type = $_SERVER["CONTENT_TYPE"];
$request_time = $_SERVER["HTTP_DATE"];
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
return "$verb\n$sha1\n$content_type\n$request_time\n$path";
}
function calculate_signature($to_sign, $api_key) {
return urlsafe_b64encode(hash_hmac('sha256', $to_sign, $api_key, true));
}
function get_recieved_signature() { return $_SERVER["HTTP_HMAC"]; }
function verify_signature($recieved, $calculated) { return $recieved == $calculated; }
$api_key = "apikey";
$to_sign = extract_message();
$calculated_signature = calculate_signature($to_sign, $api_key);
$recieved_signature = get_recieved_signature();
$matched = verify_signature($recieved_signature, $calculated_signature);
$json_obj = json_decode(file_get_contents('php://input'), TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, print_r(array(
'$_SERVER' => $_SERVER,
"JSON" => $json_obj,
"SIGNATURE INFO" => array(
"To Sign" => str_replace("\n", "\\n", $to_sign),
"Received" => $recieved_signature,
"Calculated" => $calculated_signature,
"Matched" => $matched ? "TRUE" : "FALSE"
)
), TRUE));
fclose($fp);
Make a sample request
<?php
// https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/Base64#encodeBase64URLSafe(byte[])
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='), array('-','_',''), $data);
return $data;
}
$sample_json = '{"company":"Example, Inc","pitchDetailsLink":"https://dev.clearslideng.com/manage/email/details?userVID=6YSZ9BBJWVM3H87PUAPE","senderEmail":"tester#clearslide.com","time":"Fri, 11/13/2015, 10:19 AM PST","recipients":["my#example.com"],"decks":["testing"]}';
$api_endpoint = 'http://localhost';
$verb = "POST";
$sha1 = base64_encode(sha1($sample_json));
$content_type = "application/json; charset=UTF-8";
$request_time = date("D, d M Y H:i:s T");
$path = "/emailpitchsent";
$to_sign = "$verb\n$sha1\n$content_type\n$request_time\n$path";
$api_key = "apikey";
$signature = urlsafe_b64encode(hash_hmac('sha256', $to_sign, $api_key, true));
$ch = curl_init("$api_endpoint$path");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"CONTENT-TYPE: $content_type",
"HMAC: $signature",
"DATE: $request_time",
"SHA1: $sha1"
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sample_json);
$result = curl_exec($ch);
curl_close($ch);
echo "To Sign: ". str_replace("\n", "\\n", $to_sign) ."\n\n";
echo "Response: \n\n$result";
Example Log
Array
(
[$_SERVER] => Array
(
[USER] => vagrant
[HOME] => /home/vagrant
[FCGI_ROLE] => RESPONDER
[QUERY_STRING] => event=emailpitchsent
[REQUEST_METHOD] => POST
[CONTENT_TYPE] => application/json; charset=UTF-8
[CONTENT_LENGTH] => 270
[SCRIPT_FILENAME] => /vagrant/public/index.php
[SCRIPT_NAME] => /index.php
[REQUEST_URI] => /index.php?event=emailpitchsent
[DOCUMENT_URI] => /index.php
[DOCUMENT_ROOT] => /vagrant/public
[SERVER_PROTOCOL] => HTTP/1.1
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_SOFTWARE] => nginx/1.1.19
[REMOTE_ADDR] => 10.0.0.10
[REMOTE_PORT] => 61094
[SERVER_ADDR] => 10.0.0.200
[SERVER_PORT] => 80
[SERVER_NAME] => 192.168.22.10.xip.io
[HTTPS] => off
[REDIRECT_STATUS] => 200
[LARA_ENV] => local
[HTTP_HMAC] => vnQM9g41jE--rJvvwymezRY5VU9pf52Vu9sGhe_Gy-4
[HTTP_DATE] => Thu, 19 Nov 2015 06:24:49 PST
[HTTP_SHA1] => X7hjTy8DUzIUNO05JiuXp1DT3Js=
[HTTP_CONTENT_LENGTH] => 270
[HTTP_CONTENT_TYPE] => application/json; charset=UTF-8
[HTTP_HOST] => 10.0.0.200
[HTTP_CONNECTION] => Keep-Alive
[HTTP_USER_AGENT] => Apache-HttpClient/4.5.1 (Java/1.7.0_91)
[PHP_SELF] => /index.php
[REQUEST_TIME] => 1447943089
)
[JSON] => Array
(
[company] => ClearSlide
[pitchDetailsLink] => https://dev.clearslideng.com/manage/email/details?userVID=YGCD4WNJT377FQ6FTUFH
[senderEmail] => tester#clearslide.com
[time] => Thu, 11/19/2015, 6:24 AM PST
[recipients] => Array
(
[0] => test#example.com
)
[decks] => Array
(
[0] => RockyBeach-720
)
)
[SIGNATURE INFO] => Array
(
[Path] => /index.php
[To Sign] => POST\nX7hjTy8DUzIUNO05JiuXp1DT3Js=\napplication/json; charset=UTF-8\nThu, 19 Nov 2015 06:24:49 PST\n/index.php
[Received] => vnQM9g41jE--rJvvwymezRY5VU9pf52Vu9sGhe_Gy-4
[Calculated] => vnQM9g41jE--rJvvwymezRY5VU9pf52Vu9sGhe_Gy-4
[Matched] => TRUE
)
)
Example of Server Side toSign
POST
X7hjTy8DUzIUNO05JiuXp1DT3Js=
application/json; charset=UTF-8
Thu, 19 Nov 2015 06:24:49 PST
/index.php
Clearslide.com has free tech support for all of their users. You might want to try shooting them an email at support#clearslide.com - They'll be happy to assist with the setup.

404 error - Undefined index: REDIRECT_URL

I don't understand. I set the 404 error in my .htaccess and it is redirected to error.php when I type something like http://{localhost}/mywebiste/xxx/xxx/xxx/xxx/
But I get this error,
Notice: Undefined index: REDIRECT_URL in C:\...
Notice: Undefined index: REDIRECT_STATUS in C:\...
for,
$_SERVER["REDIRECT_URL"];
$_SERVER['REDIRECT_STATUS'];
.htaccess,
RewriteEngine on
ErrorDocument 404 http://{localhost}/projects/.../error.php
error.php,
$redirect_url = $_SERVER["REDIRECT_URL"];
$status = $_SERVER['REDIRECT_STATUS'];
Any ideas?
I have tried the codes from these two sites and none of them work,
1
2
Also, I'm on EasyPHP Devsever. I want to check whether there are
print_r($_SERVER);
I get this,
Array
(
[TMP] => C:/Program Files (x86)/EasyPHP-DevServer-14.1VC11/binaries/tmp
[HTTP_HOST] => localhost
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[HTTP_ACCEPT_LANGUAGE] => en-GB,en;q=0.5
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_COOKIE] => PHPSESSID=204j1jvbinr4j1i0ebg9eq0ue5
[HTTP_CONNECTION] => keep-alive
[PATH] => C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\binaries\php\php_runningversion;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;\;C:\Program Files (x86)\Sony\VAIO Startup Setting Tool;C:\Program Files (x86)\Common Files\Roxio Shared\10.0\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Java\jdk1.8.0_05\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Git\cmd;C:\Users\lau_thiamkok\AppData\Roaming\npm;C:\Program Files\nodejs;C:\Program Files (x86)\Git;C:\PROGRA~2\EASYPH~1.1VC\Apache\bin;C:\PROGRA~2\EASYPH~1.1VC\PHP
[SystemRoot] => C:\Windows
[COMSPEC] => C:\Windows\system32\cmd.exe
[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
[WINDIR] => C:\Windows
[SERVER_SIGNATURE] =>
[SERVER_SOFTWARE] => Apache/2.4.7 (Win32) PHP/5.5.8
[SERVER_NAME] => localhost
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 80
[REMOTE_ADDR] => 127.0.0.1
[DOCUMENT_ROOT] => C:/Program Files (x86)/EasyPHP-DevServer-14.1VC11/data/localweb
[REQUEST_SCHEME] => http
[CONTEXT_PREFIX] =>
[CONTEXT_DOCUMENT_ROOT] => C:/Program Files (x86)/EasyPHP-DevServer-14.1VC11/data/localweb
[SERVER_ADMIN] => admin#127.0.0.1
[SCRIPT_FILENAME] => C:/Program Files (x86)/EasyPHP-DevServer-14.1VC11/data/localweb/projects/tests/php-boilerplate/404/basic/error.php
[REMOTE_PORT] => 55762
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] => code=404
[REQUEST_URI] => /projects/tests/php-boilerplate/404/basic/error.php?code=404
[SCRIPT_NAME] => /projects/tests/php-boilerplate/404/basic/error.php
[PHP_SELF] => /projects/tests/php-boilerplate/404/basic/error.php
[REQUEST_TIME_FLOAT] => 1416567060.231
[REQUEST_TIME] => 1416567060
)
But I don't see REDIRECT_* as in the list here.
Any ideas how I can get REDIRECT_* working in my localhost?
You can avoid using full http:// in ErrorDocument 404 directive to get both values populated like this:
ErrorDocument 404 /projects/full/path/to/error.php
With this you will see both these values populated:
$_SERVER["REDIRECT_URL"]; // /mywebiste/xxx/xxx/xxx/xxx/
$_SERVER['REDIRECT_STATUS']; // 404

Error Sending XML file by CURL to WebServices

I'm trying to send by POST method a XML through of CURL to authenticated webServices, but for some reason the server is rejecting the XML file, me giving me an error 500, however another WebService than by GET method, not have problem. The following code is i'm trying.
<?php
$request_xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<FiltroLicitaciones xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil=\"true\" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>";
//Initialize handle and set options
$username = 'user';
$password = 'pass';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.mercadopublico.cl/movil/licitaciones/porFecha');
//curl_setopt($ch, CURLOPT_URL, "http://localhost/server.php");
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_xml);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
I don't know if will be a error for XML malformed, but server return me a random 500 error with the following header:
HTTP/1.1 500 The server encountered an error processing the request. Please see the server logs for more details.
Cache-Control: private
Content-Length: 1047
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 30 Jul 2012 23:53:05 GMT
I did a test in the local server, for see as the data came, the following the result this is:
HTTP/1.1 200 OK
Date: Mon, 30 Jul 2012 23:41:50 GMT
Server: Apache/2.2.22 (Fedora)
X-Powered-By: PHP/5.3.14
Content-Length: 2450
Connection: close
Content-Type: text/html; charset=UTF-8
Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
[<?xml version] => "1.0" encoding="utf-8" ?>
<FiltroLicitaciones xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil="true" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>
)
[_GET] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
[_ENV] => Array
(
)
[_REQUEST] => Array
(
[<?xml version] => "1.0" encoding="utf-8" ?>
<FiltroLicitaciones xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil="true" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>
)
[_SERVER] => Array
(
[HTTP_HOST] => localhost
[HTTP_ACCEPT] => */*
[CONTENT_LENGTH] => 469
[CONTENT_TYPE] => application/x-www-form-urlencoded
[PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[SERVER_SIGNATURE] => <address>Apache/2.2.22 (Fedora) Server at localhost Port 80</address>
[SERVER_SOFTWARE] => Apache/2.2.22 (Fedora)
[SERVER_NAME] => localhost
[SERVER_ADDR] => ::1
[SERVER_PORT] => 80
[REMOTE_ADDR] => ::1
[DOCUMENT_ROOT] => /var/www/html
[SERVER_ADMIN] => root#localhost
[SCRIPT_FILENAME] => /var/www/html/server.php
[REMOTE_PORT] => 37712
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => POST
[QUERY_STRING] =>
[REQUEST_URI] => /server.php
[SCRIPT_NAME] => /server.php
[PHP_SELF] => /server.php
[PHP_AUTH_USER] => user
[PHP_AUTH_PW] => pass
[REQUEST_TIME] => 1343691710
)
)
I hope can you help me.
Thanks.
Best Regards.
Well I'm not sure if the 500 error is from the xml but, as I see in your code the xml has no url variable :
myxml=<xml></xml>
Because as you can see from the response the url paramenter has become
[<?xml version] => "1.0" encoding="utf-8" ?>
and this is wrong.
If the api docs didn't specified any url parameters then you should probably set the right curl header :
curl_setopt($ch,CURLOPT_HTTPHEADER, Array("Content-Type: application/xml");
Like this the server knows what to expect
Note this part of your sample dump:
[_POST] => Array
(
[<?xml version]
Your XML data was interpreted as a form-type data upload, with a field name of <?xml version. This destroyed your XML's structure, leading to a parse error on the server you're submitting this to.
Read below url first i think this is very use full to you
Sending XML files to a Webservice (Using cURL)
http://softwaredevelopmentindia.wordpress.com/2007/07/09/sending-xml-files-to-a-webservice-using-curl/
or try this
Calling Web Services. Great fun!! … when it works. One of the biggest challenges is to send the XML document and get the response back, an XML document in particular. I have come up with a PHP function that hides all the necessary logic from theuser and handles the posting of the XML document and returns whatever the server responds. It relies on PHP’s cURL library (so you need it properly configured on your server in order to work). All you need to do is create the XML document, choose the URL (and port) to which you want to post the XML document and the function takes care of the rest. Below is the function code. As you can see, the function can handle SSL-enabled servers, something that provides a great advantage, since many Web services run on HTTPS.
// open a http channel, transmit data and return received buffer
function xml_post($post_xml, $url, $port)
{
$user_agent = $_SERVER[’HTTP_USER_AGENT’];
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port); //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
The example below shows how the function works, by posting a XML document of the form
<?xml version=”1.0″ encoding=”iso-8859-1″?>
<Document>
<Message>
Your Name
</Message>
</Document>
to a “listener” script, which takes the XML document and returns a reply (another XML document). In this case, the listener is very simple. All it does is replace the “Message” tag with “Reply” and print the resulting XML. Of course, the listener can do all sorts of things in response to the POST.
<?php
if ( !isset( $HTTP_RAW_POST_DATA ) )
{
$HTTP_RAW_POST_DATA = file_get_contents( ‘php://input’ );
}
$xml = str_replace(”Message”,”Reply” , $HTTP_RAW_POST_DATA);
print((trim($xml)));
?>

retrieve original url of a wordpress page

I know that, wordpress redirects closely matched urls to its original url.However, I need to know the actual url at the very beginning of code execution. Is it possible?
1) If there is any method that takes a url as parameter and returns its original wordpress url
, that would be great, but not sure, whether it exists or not. Is there something like that?
2) where in the code actually does this test and redirection please?
3) Is there any hook that I can use to add a plugin to control this situation?
Thanks in advance.
Example:
Suppose, I have a post on this url: "http://mydomain.com/example-post-page"
Now if I try to access it via "http://mydomain.com/example-post-page/", it will redirect you to original first url. It is true for other several small changes in url, all will redirect you to the actual permalink url.
My goal is to control this redirection. That's why, when I am on "http://mydomain.com/example-post-page/" , I like to know(my code in on root index.php) whether this is the origianl permalink or is that something else, before it redirects.
If you are trying to do this in PHP, you can ask the server what the requested URL was. try accessing $_SERVER[ ] and see if this has what you are looking for.
(protip: to see an entire variable in php, use print_r($_SERVER);)
I executed the command on my wordpress site and got back:
Array
(
[SERVER_SOFTWARE] => Apache
[REQUEST_URI] => /wordpress_NEWURL/cookbook/
[REDIRECT_SCRIPT_URL] => /wordpress_NEWURL/cookbook/
[REDIRECT_SCRIPT_URI] => http://openmdao.org/wordpress_NEWURL/cookbook/
[REDIRECT_HTTPS] => off
[REDIRECT_X-FORWARDED-PROTO] => http
[REDIRECT_X-FORWARDED-SSL] => off
[REDIRECT_STATUS] => 200
[SCRIPT_URL] => /wordpress_NEWURL/cookbook/
[SCRIPT_URI] => http://openmdao.org/wordpress_NEWURL/cookbook/
[HTTPS] => off
[X-FORWARDED-PROTO] => http
[X-FORWARDED-SSL] => off
[HTTP_HOST] => openmdao.org
[HTTP_X_FORWARDED_HOST] => openmdao.org
[HTTP_X_FORWARDED_SERVER] => openmdao.org
[HTTP_X_FORWARDED_FOR] => 128.156.10.80
[HTTP_HTTP_X_FORWARDED_PROTO] => http
[HTTP_HTTPS] => off
[HTTP_X_FORWARDED_PROTO] => http
[HTTP_X_FORWARDED_SSL] => off
[HTTP_CONNECTION] => close
[CONTENT_LENGTH] => 92
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_ORIGIN] => http://openmdao.org
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5
[CONTENT_TYPE] => application/x-www-form-urlencoded
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[HTTP_REFERER] => http://openmdao.org/wordpress_NEWURL/cookbook/
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
[HTTP_COOKIE] => wp-settings-1=m7%3Do%26m11%3Do%26wplink%3D0%26editor%3Dtinymce%26hidetb%3D1%26align%3Dright; wp-settings-time-1=1341576701; wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_7f72de226f3f83cb831f7a36bd420125=admin%7C1342021433%7C1c54f9729f967300e8d1ecc80eea7e38; w3tc_referrer=http%3A%2F%2Fopenmdao.org%2Fwordpress_test%2Fsdk-1.5.6.2%2F_samples%2F; wp-settings-1=m7%3Do%26m11%3Do%26wplink%3D0; wp-settings-time-1=1339595284; greeting_set=True; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1; wordpress_test_cookie=WP+Cookie+check; PHPSESSID=0302b71abfbfd5a8d7854ac168aba2f9; sessionid=7b87104b87d95624cab0fe282079aa07; csrftoken=e72c25d0cdc3a6682c89e4680742ff3b; __utma=192130932.1535996015.1339438190.1341938618.1341945509.58; __utmc=192130932; __utmz=192130932.1339605598.7.2.utmcsr=rss|utmccn=new-website|utmcmd=rss
[HTTP_VIA] => 1.1 www-fw.grc.nasa.gov 8B58912A
[PATH] => /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/home/ph/trunk/python-hosting.com/new_site/monitor:/home/ph/trunk/python-hosting.com/new_site/manual_scripts:/root/bin
[SERVER_SIGNATURE] =>
[SERVER_NAME] => openmdao.org
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 80
[REMOTE_ADDR] => 128.156.10.80
[DOCUMENT_ROOT] => /home/openmdao/webapps/_
[SERVER_ADMIN] => [no address given]
[SCRIPT_FILENAME] => /home/openmdao/webapps/wp_test/index.php
[REMOTE_PORT] => 51907
[REDIRECT_URL] => /wordpress_NEWURL/cookbook/
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.0
[REQUEST_METHOD] => POST
[QUERY_STRING] =>
[SCRIPT_NAME] => /wordpress_NEWURL/index.php
[PHP_SELF] => /wordpress_NEWURL/index.php
[REQUEST_TIME] => 1341948361
[argv] => Array
(
)
[argc] => 0
)
Any one of those paramaters can be accessed by $_SERVER['PARAMATER'] from anywhere in you script.
I hope this was helpful!
Do you mean the_permalink? http://codex.wordpress.org/Function_Reference/the_permalink
Ok, At last I got it done in the following way and seems ok for me:
1) Recieve approx url.
2) Make a cURL request using this approx url.
3) get response url.
4) return the response url.
Code given below:
function get_actual_url($approx_url){
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, $approx_url);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curlObj, CURLOPT_ENCODING , "gzip");
curl_setopt($curlObj, CURLOPT_TIMEOUT,180);
$content = curl_exec($curlObj);
$info = curl_getinfo($curlObj);
curl_close($curlObj);
if(!empty($info) && !empty($info["url"])){
return $info["url"];
}
else {
return $approx_url;
}}

Https causing redirect loop?

I am using code igniter, our server is behind some funky config.
I want certian pages to be behind https, certian pages to be behind http, and others I don't care about.
So below is my setup,
If I go to http://test.example.com (which has a call to disable_ssl()) the page loads fine
If I go to https://test.example.com/login (which has a call to require_ssl()) the page loads fine.
If I go the http://test.example.com/login I get redirected to the https version. which is good.
If I go to https://test.example.com then I get hit with a redirect loop...
For some reason the header keeps getting set to https instead of http, even though I explicitly write http.
My $_SERVER array on an http request looks like looks like
Array
(
[REDIRECT_STATUS] => 200
[HTTP_HOST] => test.example.com:80
[HTTP_X_REAL_IP] => 119.224.22.142
[HTTP_X_FORWARDED_FOR] => 119.224.22.142
[HTTP_X_URL_SCHEME] => http
[HTTP_CONNECTION] => close
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_USER_AGENT] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8,en-NZ;q=0.6
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
[HTTP_COOKIE] => [...]
[PATH] => /usr/local/bin:/usr/bin:/bin
[SERVER_SIGNATURE] =>
Apache/2.2.14 (Ubuntu) Server at test.example.com Port 8080
[SERVER_SOFTWARE] => Apache/2.2.14 (Ubuntu)
[SERVER_NAME] => test.example.com
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 8080
[REMOTE_ADDR] => 127.0.0.1
[DOCUMENT_ROOT] => /var/www
[SERVER_ADMIN] => webmaster#localhost
[SCRIPT_FILENAME] => /var/www/index.php
[REMOTE_PORT] => 54833
[REDIRECT_URL] => /
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.0
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /
[SCRIPT_NAME] => /index.php
[PATH_INFO] => /
[PATH_TRANSLATED] => redirect:/index.php/
[PHP_SELF] => /index.php/
[PHP_AUTH_USER] => ******
[PHP_AUTH_PW] => ******
[REQUEST_TIME] => 1308972068
)
and on a https request it looks like
Array
(
[REDIRECT_STATUS] => 200
[HTTP_HOST] => test.example.com:443
[HTTP_X_REAL_IP] => 119.224.22.142
[HTTP_X_FORWARDED_FOR] => 119.224.22.142
[HTTP_X_URL_SCHEME] => https
[HTTP_X_FORWARDED_PROTO] => https
[HTTP_CONNECTION] => close
[HTTP_USER_AGENT] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8,en-NZ;q=0.6
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
[HTTP_COOKIE] => [...]
[PATH] => /usr/local/bin:/usr/bin:/bin
[SERVER_SIGNATURE] =>
Apache/2.2.14 (Ubuntu) Server at test.example.com Port 8080
[SERVER_SOFTWARE] => Apache/2.2.14 (Ubuntu)
[SERVER_NAME] => test.example.com
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 8080
[REMOTE_ADDR] => 127.0.0.1
[DOCUMENT_ROOT] => /var/www
[SERVER_ADMIN] => webmaster#localhost
[SCRIPT_FILENAME] => /var/www/index.php
[REMOTE_PORT] => 54841
[REDIRECT_URL] => /
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.0
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /
[SCRIPT_NAME] => /index.php
[PATH_INFO] => /
[PATH_TRANSLATED] => redirect:/index.php/
[PHP_SELF] => /index.php/
[PHP_AUTH_USER] => ********
[PHP_AUTH_PW] => ********
[REQUEST_TIME] => 1308972250
)
and my .htaccess looks like
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ %1/$1 [R=301,L]
RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico|css|images|js)
RewriteRule ^(.*)$ index.php/$1 [L]
So at the very top of my index.php I have
$_SERVER['SERVER_PORT'] = explode(':', $_SERVER['HTTP_HOST']);
$_SERVER['HTTP_HOST'] = $_SERVER['SERVER_PORT'][0];
$_SERVER['SERVER_PORT'] = $_SERVER['SERVER_PORT'][1];
if($_SERVER['SERVER_PORT'] == 443)
$_SERVER['HTTPS'] = 'On';
else
$_SERVER['HTTPS'] = 'Off';
And on pages where I want HTTPS I call
function require_ssl(){
if($_SERVER['HTTPS'] == 'Off') {
$host = explode(':', $_SERVER['HTTP_HOST']);
header('location: https://' . $host[0] . $_SERVER['REQUEST_URI']);
exit;
}
}
And on pages where I want only HTTP I call
function disable_ssl(){
if($_SERVER['HTTPS'] == 'On') {
$host = explode(':', $_SERVER['HTTP_HOST']);
header('location: http://' . $host[0] . $_SERVER['REQUEST_URI']);
exit;
}
}
So, after hours of painful debugging we finally worked out the issue.
Nginx
Yep, the load balancer was doing it's own redirects.
In the nginx setup this line existed proxy_redirect http:// https://;
So, what was happening?
Well,
My code was saying "this page should not be https, redirect"
Then nginx was saying "this request is not https, redirect"
Then my code was...
boom redirect loop.
So, by changing proxy_redirect http:// https://; to proxy_redirect Off; we fixed the problem :)
The function that you posted for disable_ssl() shows:
if($_SERVER['HTTPS'] == '0n') {
Is the 0 ('zero') a copy/paste error? I assume that you meant:
if($_SERVER['HTTPS'] == 'On') {
If I'm following your logic correctly, this function is invoked when you goto https://test.example.com, and so if this typo exists, it is probably not doing what you think it should.
We've addressed the accurate fix for Nginx (and other reverse proxies) here:
http://www.sonassi.com/knowledge-base/magento-kb/magento-https-redirect-loop/
This avoids the necessity to have that code in your index.php file. All you needed to do was add this to your Nginx config,
fastcgi_param HTTPS on;
You might consider using .htaccess rules instead, something like:
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} (optional pattern additional url matching)
RewriteRule ^(.*)$ https://test.example.com/$1 [L]
if you want to force http just replace 80 with 443 and https with http.

Categories