Encode portion of path using PHP - php

I need to encode only part of the $delete path. Only the # in the email address and # in the property. I know how to use urlencode for the whole thing but not on just that. The way it works, is it loops through to get the properties and most of them include # in the name. Anyone who can help modify so that this works would be greatly appreciated!
The delete:
$delete = "http://admin:12345#192.168.245.133/#api/deki/DELETE:users/$user_id/properties/%s";
Here you can see $user_id this will be an email address BUT the # symbol needs to be encoded.
The properties which follow at the very end, has a # within the name, this needs to also be encoded. For example, one property name userprofile#external.created_date
Here is the code so far:
<?php
$user_id="john_smith#ourwiki.com";
$url=('http://admin:12345#192.168.245.133/#api/deki/users/=john_smith#ourwiki.com/properties');
$xmlString=file_get_contents($url);
$delete = "http://admin:12345#192.168.245.133/#api/deki/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name']; // the name is stored in the attribute
curl_fetch(sprintf($delete, $name),'admin','12345');
}
?>

Have you tried this? str_replace($string, array('#', '#'), array('%40', '%23'));
The urlencode function does not allow you to limit it to a subset of characters.

Related

Display last numbers of REDIRECTED link

How i can display the last numbers of a redirected url in php?
with redirected, i mean something like this
$nick=$_GET['nickname'];
$url='http://es.cheese.formice.com/mouse/' . $nick . '';
For example, if the url is script.php?nickname=Skyleter, will be http://es.cheese.formice.com/mouse/Skyleter, the problem here is it redirects to http://es.cheese.formice.com/mouse/Skyleter.17529827, (try yourself) so i want to display the numbers of the redirected url.
Wich, for me is 17529827
Is this possible?
Please dont say "the last 8 digits" like $variable = substr($url, -8); , so every nick has different ID.
Also ill like to display a custom error when input is value. [script.php and not script.php?nick=nick]
It displays "undefinex index" by default.
Thanks!
If it's always going to be numbers, you could use filter_var to easily pull them out.
$url = 'http://es.cheese.formice.com/mouse/Skyleter.17529827';
$id = filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $id; // 17529827
If the nickname contains numbers though, this won't work. If the format stays that way (always ending with a dot and a set of numbers), then I guess you could use pathinfo and read that as the extension of your path.
$urlParts = pathinfo('http://es.cheese.formice.com/mouse/Skyleter1111.17529827');
echo $urlParts['extension'];
Since this url will redirect you, you will need to use curl to get the next one.
This will work:
<?php
$nick='Skyleter'; //$_GET['nickname'];
$url='http://es.cheese.formice.com/mouse/' . $nick;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
$l = trim($r[1]);
$user_id = end((explode('.', $l)));
echo $user_id;
?>
It explodes the string at the last dot (.), which is what comes right before the ID.

Google maps response's language issue

I'll try to be short: if you need more info, I'll tell you.
I'm using this code to get infos from Google Maps:
<?php
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'http://maps.google.com/maps/geo?output=xml&q=' . urlencode($startPlace);
$url = 'http://maps.google.com/maps/api/geocode/json?sensor=false&gl=IT&address=' . urlencode($startPlace);
$xml = simplexml_load_string($this->getData($this->url)) or die("Error loading xml data");
$points = $xml->Response->Placemark->Point->coordinates;
$provincia = $xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;
$regione =$xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
echo $regione."<br>";
preg_match_all("/-*[0-9.]*(?=,)/", $points[0], $matches);
$longitude = $matches[0][0];
$latitude = $matches[0][2];
The code is used to retrieve infos about italian locations and till three days ago, all worked fine, but this morning I saw something strange: $regione returned by code ($xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;) had an english name.
Let's say the location found be a little town in Lombardia (where 'Lombardia' is the name of the Administrative Area), the Administartive Area name returned by Google Maps was no more 'Lombardia' but 'Lombardy'.
Since this data is used to search in a local database other places in the Administrative area and since the name used in the database is obviously italian name, application doesnìt work anymore.
I'll be grateful for any advice
The problem is solved using a different url, specifying language parameter:
'http://maps.google.com/maps/api/geocode/xml?sensor=false&language=IT&address=' . urlencode($startPlace);
This url type return correct results but defferently formed so it is necessary change the code to access the infos and put them into variables, but this solved my problem

Decoding JSON after sending using PHP cUrl

I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the &quot and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.

Problem with CURL fetch function

I've created a php script that will allow the removal of user properties. The script first finds all properties associated with a user and then loops to remove all of them.
When I run this for a certain user, it gets down to the foreach loop and it prints out all the the properties ($name2) but it seems to get stuck on the curl_fetch part. When I then try to pull the properties, they still exist for the user. Any ideas why this is happening? The code is below for you to take a look. Thanks in advance.
<?php
$user=$_GET['userid'];
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print "User-id: $user";
print "<br /><br />";
$url=("https://admin:password#oursite.com/#api/users/=$user_id/properties");
$xmlString=file_get_contents($url);
$delete = "https://admin:password#oursite.com/#api/users/=$user_id/properties/";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
print "The following properties have been removed: ";
print "<br />";
if(!count($xml->property)) die('No properties exist for this user');
foreach($xml->property as $property) {
$name = $property['name'];
$name2=str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
print "<br />";
curl_fetch($delete . $name2,'admin','password');
}
?>
You're hitting that URL as a GET query. Are you sure doing a delete-type call wouldn't at least require a POST? Think of the chaos that would ensue if a web spider got a list of urls and innocently nuked your entire site by simply indexing it?
My bad, didn't notice that DELETE was the default method in your curl function.
I'd suggest echoing out the complete URL from within the curl function, and verifying that it is being built properly. I can't see anything else obviously wrong with the code, so I'm guessing the URL's incorrect.

sprintf warning - encoding issue

I'm using the following code to find all properties for a user and in turn delete them. My problem is that I'm getting a warning: Warning: sprintf(): Too few arguments for each of the properties.
However, when I manually enter the $user_id for the delete string as first_last%%40ourwiki.com it works!
Seems like sprintf requires double '%' but not sure why. Is there a way to get around this? Also, I'm using the same variable for file_get_contents and this works fine.
The Code:
$user="first_last#ourwiki.com";
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print $user_id;
$url=("http://admin:password#172.16.214.133/#api/users/=$user_id/properties");
$xmlString=file_get_contents($url);
$delete = "http://admin:password#172.16.214.133/#api/users/=$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name'];
$name2=str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
curl_fetch(sprintf($delete, $name2),'admin','password');
}
Thanks in advance!
% is a special character in sprintf(). So you have to escape all % before processing it, %% is a literal %s.
$delete = str_replace("http://admin:password#172.16.214.133/#api/users/=$user_id/properties/", '%', '%%').'%s';
You do not have to use sprintf here, you can use the concatenation operator too, like:
$delete = "http://admin:password#172.16.214.133/#api/users/=$user_id/properties/";
curl_fetch( $delete . $name2, 'admin', 'password' );

Categories