Special Characters within URL Variable - php

Currently I am trying to fiddle around with the Deezer API and running into a slight issue, I am trying to gather content from this artist.
XYLØ - Nothing Left To Say
https://api.deezer.com/search/track?q=XYLØ - Nothing Left To Say
The page above displays the content in a JSON format, however when I use the following code.
$id = 'XYLØ - Nothing Left To Say';
$h = str_replace(' ', '+', $id);
$json_string = 'https://api.deezer.com/search/track?q='.$h;
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
I get an empty pallet on my image request.
$obj['data'][0]['album']['cover_medium']
Any ideas on how I can get this to work properly?

Use PHP's built in function for query args,
//changed $h to $id (see below)
$json_string = 'https://api.deezer.com/search/track?q='.urlencode($id);
http://php.net/manual/en/function.urlencode.php
This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
You can also do away with this stuff (AKA remove it):
$h = str_replace(' ', '+', $id);
As urlencode does that to!!!.
As a Bonus
You can use
http://php.net/manual/en/function.http-build-query.php
http_build_query — Generates a URL-encoded query string from the associative (or indexed) array provided.
To build the whole query string from an array, which I figure may be useful to someone reading this...

Related

base64_decode showing corrupted characters

I am building a hyperlink that includes a base64 encoded set of parameters as shown below:
$params = base64_encode("member_id={$recipient_id}&api_key=".SECRET_KEY);
$link = HOST_ADDRESS."test.php?k=" . $params;
When the link is executed, the following code runs:
// get the encoded string from the link parameter
$link_parm = $_GET['k'];
$link = substr($link_parm, 0);
// url encode the string to ensure all special characters convert properly - attempt to stop errors
urlencode($link);
// decode the rest of the link
$decoded_link = base64_decode($link);
// get the remaining data elements from the link parameter
$msg_data = preg_split( "/[&=]/", $decoded_link);
On occasion, the $msg data is corrupted and looks like this:
member_id=167œÈ&api_key=secretkey
As you can see the member id is corrupted.
Can someone please help me understand what may be causing this?
Thanks.
For starters, there are a few problems with this beside the issue you describe.
What are you trying to do using $link = substr($link_parm, 0);? This could just be written as $link = $link_parm;. Or, you could of course just do $link = $_GET['k']; or even just use $_GET['k'].
urlencode($link); does nothing as you're not catching its result. The argument is not passed by reference.
Your "attempt to stop errors" should probably be handled differently. By throwing an error when you're receiving unexpected input, for instance.

save the last part of url in variable

I want to get the last part of an url that looks like this:
http://localhost:8888/blog/public/index.php/categories/Horror
I've tried it with
$endOfUrl = end(explode('/',$url));
but the thing is I get a notice that "Only variables should be passed by reference"
I need this "Horror" to get it's ID in my database and get all the posts with this id, since I'm trying to code a blog to get experience with php.
Another question linked to this: Is it possible to make it dynamic so it can be used for all the other categories as well? Or do I have to do this for every single category?
I'm new to the world of php so I would really appreciate it if someone could help me on this.
Try like this way for end() but If I were you I will try basename() to get my job done.
<?php
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
$exploded = explode('/',$url);
$endOfUrl = end($exploded);
echo $endOfUrl;
?>
Reason why it is not working on single line:
end() requires a reference, because it modifies the internal
representation of the array (i.e. it makes the current element pointer
point to the last element).The result of explode('.', $url) cannot be
turned into a reference and this is a restriction in the PHP language itself.
DEMO: https://3v4l.org/ttKui
Using basename(),
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
echo basename($url);
DEMO: https://3v4l.org/pt2cQ

PHP URL Variable Appending

Hoping this is a simple and easy question. I've seen multiple examples of, and know how to append variables to the URL (i.e. mydomain.com/index.php?id=1&stat=0), but my question is this:
If I have a page on my site that already has variables in the URL (i.e. mydomain.com/tickets.php?stat=Open), how can I append a page number to the end of that URL (i.e. mydomain.com/tickets.php?stat=Open&page=2). This is for pagination purposes of a table with values from my database, that includes a search and select function (select open, closed, or all tickets, and search for a specific ticket number).
I've done several searches with google, and came up dry, as most topics regarding this have you hardcode the url with variables from the get go, and not append them. I may just be using the wrong search parameters as well, and am not sure what to search for exactly.
Any help or insight on this would be greatly appreciated, thank you.
Please note I wish to do this solely in PHP, HTML, and MySQLi. I want to refrain from using javascript or ajax if possible for my clients that may have those features disabled on their browsers.
Using this way:--
<?php
$domain = "mydomain.com";
$page = "tickets.php?";
$full_page_url = $domain.'/'.$page;
$arr = array('stat' => 'Open', 'page' =>2);
$add= http_build_query($arr);
$correct_url = $full_page_url. $add;
echo $correct_url;
?>
output:--mydomain.com/tickets.php?stat=Open&page=2
I would do it like this:
$page = 2;
$url = 'mydomain.com/tickets.php?stat=Open';
if( false !== strpos($url, '?')){
//if url has a ? split it.
$arr_url = explode('?', $url);
//convert query string to array, $array=['stat'=>'Open']
parse_str($arr_url[1], $array);
//add or replace page by array key
$array['page'] = $page;
//convert it back to a query string.
$query = http_build_query($array);
print_r($query);
}
Outputs
stat=Open&page=2
It's a simple matter of putting $query back with $arr_url[0] I'll leave this up to you. But I will give you a hint $arr_url[0].'?'.$query
The advantage here is that you don't have to worry about getting into a situation where you are adding page after page after page after...
Like this:
mydomain.com/tickets.php?stat=Open&page=1&page=2&page=3
You can't simply concatenate it onto the end of the url, and it's probably just as hard to remove it as it is to parse the query string.
As a side note, you could just use $_GET but where is the fun in that, as $_GET is the query string already parsed as an array ( so you could skip parse_str). But it may not be on a request, such as if you were just building the link from a string.
So I thought I would show it with parse_str to cover the "harder" case.
One last thing if you are just building a bunch of urls all the same except the page part. The obvious answer is to setup a base url and then just loop out the numbers.
$url = 'mydomain.com/tickets.php?stat=Open';
$pagedUrls = [];
$numberPages = 10;
for($i=1; $i<=$nubmerPages; $i++){
$pagedUrls[] = $url.='&page='.$i;
}
Or what have you for the number of pages.
It's really not that clear in your question exactly what you are trying to do..
Hope that helps.

Extract JSON from HTML using PHP

I'm reading source code of an online shop website, and on each product page I need to find a JSON string which shows product SKUs and their quantity.
Here are 2 samples:
'{"sku-SV023435_B_M":7,"sku-SV023435_BL_M":10,"sku-SV023435_PU_M":11}'
The sample above shows 3 SKUs.
'{"sku-11430_B_S":"20","sku-11430_B_M":"17","sku-11430_B_L":"30","sku-11430_B_XS":"13","sku-11430_BL_S":"7","sku-11430_BL_M":"17","sku-11430_BL_L":"4","sku-11430_BL_XS":"16","sku-11430_O_S":"8","sku-11430_O_M":"6","sku-11430_O_L":"22","sku-11430_O_XS":"20","sku-11430_LBL_S":"27","sku-11430_LBL_M":"25","sku-11430_LBL_L":"22","sku-11430_LBL_XS":"10","sku-11430_Y_S":"24","sku-11430_Y_M":36,"sku-11430_Y_L":"20","sku-11430_Y_XS":"6","sku-11430_RR_S":"4","sku-11430_RR_M":"35","sku-11430_RR_L":"47","sku-11430_RR_XS":"6"}',
The sample above shows many more SKUs.
The number of SKUs in the JSON string can range from one to infinity.
Now, I need a regex pattern to extract this JSON string from each page. At that point, I can easily use json_encode().
Update:
Here I found another problem, sorry that my question was not complete, there is another similar json string which is starting with sku- , Please have a look at source code of below link you will understand, the only difference is the value for that one is alphanumeric and for our required one is numeric. Also please note our final goal is to extract SKUs with their quantity, maybe you have a most straightforward solution.
Source
#chris85
Second update:
Here is another strange issue which is a bit off topic.
while I'm opening the URL content using below code there is no json string in the source!
$html = file_get_contents("http://www.dresslink.com/womens-candy-color-basic-coat-slim-suit-jacket-blazer-p-8131.html");
But when I'm opening the url with my browser the json is there! really confused about this :(
Trying to extract specific data from json directly with regexp is normally always a bad idea due to the way json is encoded. The best way is to regexp the whole json data, then decode using the php function json_decode.
The issue with the missing data is due to a missing required cookie. See my comments in the code below.
<?php
function getHtmlFromDresslinkUrl($url)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//You must send the currency cookie to the website for it to return the json you want to scrape
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Cookie: currencies_code=USD;',
));
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$html = getHtmlFromDresslinkUrl("http://www.dresslink.com/womens-candy-color-basic-coat-slim-suit-jacket-blazer-p-8131.html");
//Get the specific arguments for this js function call only
$items = preg_match("/DL\.items\_list\.initItemAttr\((.+)\)\;/", $html, $matches);
if (count($matches) > 0) {
$arguments = $matches[1];
//Split by argument seperator.
//I know, this isn't great but it seems to work.
$args_array = explode(", ", $arguments);
//You need the 5th argument
$fourth_arg = $args_array[4];
//Strip quotes
$fourth_arg = trim($fourth_arg, "'");
//json_decode
$qty_data = json_decode($fourth_arg, true);
//Then you can work with the php array
foreach ($qty_data as $name => $qtty) {
echo "Found " . $qtty . " of " . $name . "<br />";
}
}
?>
Special thanks to #chris85 for making me read the question again. Sorry but I couldn't undo my downvote.
You will want to use preg_match_all() to perform the regex matching operation (documentation here).
The following should do it for you. It will match each substring beginning with "sku" and ending with ",".
preg_match_all("/sku\-.+?:[0-9]*/", $input)
Working example here.
Alternatively, if you want to extract the entire string, you can use:
preg_match_all("/{.sku\-.*}/, $input")
This will grab everything between the opening and closing brackets.
Working example here.
Please note that $input denotes the input string.
A simple /'(\{"[^\}]+\})'/ will match all these JSON strings. Demo: https://regex101.com/r/wD5bO4/2
The first element of the returned array will contain the JSON string for json_decode:
preg_match_all ("/'(\{\"[^\}]+\})'/", $html, $matches);
$html is the HTML to be parsed, the JSON will be in $matches[0][1], $matches[1][1], $matches[2][1] etc.

PHP get request returning nothing

Using window.location.hash (used to pass in ID for page) returns something like the following:
Also, for people asking why I used window.location.hash instead of window.location.href is because window.location.href started looping infinitely for some reason, and .hash does not. I don't think this should be a big deal, but let me know if it is and if I need to change it.
http://website.com/NewPage.php#?name=1418019307305
[The string of numbers is actually epoch system time]
When using PHP to try to retrieve this variable It is not picking up any text in the file It's supposed to write to.
<?php
$myfile = fopen("File1.txt","w");
echo $_GET['name'];
fwrite($myfile, $_GET['name']);
fclose($myfile);
?>
Try to print $_SERVER variable and it will give you the array and in the desired key you can get the values. It can help you to find that variable in the string.
If you want to get the value after the hash mark or anchor, that isn't possible with "standard" HTTP as this value is never sent to the server. However, you could parse a URL into bits, including the fragment part, using parse_url().
This should do the trick:
<?php
$name_query = parse_url("http://website.com/NewPage.php#?name=1418019307305");
$get_name = substr($name_query['query'], strpos($name_query['query'], "=") + 1);
echo $get_name;
?>
Working example: http://codepad.org/8sHYUuCS
Then you can use $get_name to store "name" value in a text file.
The hash tag is a fragment that never gets processed by the server, but rather the user-agent, i.e. the browser, so JavaScript may certainly access it. (See https://www.rfc-editor.org/rfc/rfc3986#section-3.5). PHP does allow you to manipulate a url that contains a hash tag with parse_url(). Here's another way to get the info:
<?php
$parts = parse_url("http://website.com/NewPage.php#?name=1418019307305");
list(,$value) = explode("=",$parts['fragment']);
echo $value; // 1418019307305
The placement of the hash tag in this case wipes out the query string so $_SERVER['QUERY_STRING'] will display an empty string. If one were to rewrite the url following best practice, the query string would precede the hash tag and any info following that mark. In which case the script for parsing such a url could be a variation of the preceding, as follows:
<?php
$bestPracticeURL = "http://website.com/NewPage.php?name=1418019307305#more_data";
$parts = parse_url( $bestPracticeURL );
list(,$value) = explode("=", $parts['query']);
$hashData = $parts['fragment'];
echo "Value: $value, plus extra: $hashData";
// Value: 1418019307305, plus extra: more_data
Note how in this case parse_url was able to capture the query string as well as the hash tag data. Of course, if the query string had more than one key and value, then you might need to explode on the '&' into an array and then explode each array element to extract the value.

Categories