PHP - Display results from this 'Detect' array? - php

re: Home Site = http://mobiledetect.net/
re: this script = Mobile_Detect.php
Download script here: https://github.com/serbanghita/Mobile-Detect
This script functions perfectly detecting the different parameters of a user's device.
However, this is how I am currently detecting these parameters:
// each part of the IF statement is hard-coded = not the way to do this
if($detect->isiOS()){
$usingOS = 'iOS';
}
if($detect->isAndroidOS()){
$usingOS = 'Android';
}
echo 'Your OS is: '.$usingOS;
My goal is to use a FOREACH to iterate thru the various arrays in this script to determine a user's device's parameters. I would need to have the "($detect->isXXXXOS())" be dynamic... (which, would be based upon the KEY). The results would display the KEY. But the detection would be based upon the VALUE.
Also, since my web page uses a REQUIRE to access this script... in the Mobile_Script.php script, the arrays are "protected." I think this is also causing me problems (but I don't know for sure).
Any help is appreciated.

In foreach loop you can call dynamic method look like this :
$array = array('Android','Windows','Linux','Mac');
foreach( $array as $value) {
$method = "is{$value}OS";
if($detect->$method()) {
$os = $value;
echo "Your OS is : {$os}";
}
}
Please rearrange your code what you want. I give you an example.

you can try to use somethin like this:
$OSList = $detect->getOperatingSystems();// will give array of operating system name => match params
foreach($OSList as $os_name=>$os_params/*unused*/)
{
$method = 'is'.$os_name;
if($detect->$method())
{
$usingOS = $os_name;
}
}

Related

How to get variables from a different PHP file without executing the code?

I am trying to loop through all the php files listed in an array called $articleContents and extract the variables $articleTitle and $heroImage from each.
So far I have the following code:
$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();
if (require_once('../articles/'.$articleContents[$x])) {
ob_end_clean();
$entry = array($articleContents[$x],$articleTitle,$heroImage);
array_push($articlesInfo, $entry);
}
The problem is, the php files visited in the loop have html, and I can't keep it from executing. I would like to get variables from each of these files without executing the html inside each one.
Also, the variables $articleTitle and $heroImage also exist at the top of the php file I'm working in, so I need to make sure the script knows I'm calling the variables in the external file and not the current one.
If this is not possible, can you please recommend an alternative method?
Thanks!
Don't do this.
Your PHP scripts should be for your application, not for your data. For your data, if you want to keep it file-based, use a separate file.
There are plenty of formats to choose from. JSON is quite popular. You can use PHP's built-in serialization as well, which has support for more PHP-native types but is not as portable to other frameworks.
A little hacky but seems to works:
$result = eval(
'return (function() {?>' .
file_get_contents('your_article.php') .
'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);
Where your_article.php is something like:
<?php
$articleTitle = 'hola';
$heroImage = 'como te va';
The values are returned in the $result array.
Explanation:
Build a string of php code where the code in your article scripts are wrapped inside a function that returns an array with the values you want.
function() {
//code of your article.php
return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}
Maybe you must do some adaptations to the strings due <?php ?> tags placements.
Anyway, this stuff is ugly. I'm very sure that it can be refactored in some way.
Your problem (probably) comes down to using parentheses with require. See the example and note here.
Instead, format your code like this
$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
ob_start();
if (require '../articles/' . $file) { // note, no parentheses around the path
$articlesInfo[] = [
$file,
$articleTitle,
$heroImage
];
}
ob_end_clean();
}
Update: I've tested this and it works just fine.

Hiding part of the url in Zend Framework

I was thinking if there is a way to hide part of the url in PHP/ Zend Framework 2. Something like this:
sitename.com/something/?inviter=1234&id=1
But I'd like to hide the part with the &id=1 somehow, so that when the url is copied and entered by the user, it would look like this:
sitename.com/something/?inviter=1234
And on the other side I can do something like this:
$id = $_GET["id"])
Is this possible to do, if so, how? Maybe there is something close to what I'm looking for to achieve?
You can hide it only with Cookie or Session techniques. But it will work only for one user during one session.
You can parse and rebuild the url using parse_url, http_build_url, with parse_str, and http_build_str.
For example:
/**
* Transform a url using a whitelist of query-string keys
*/
function transformUrlKeepQueryKeys($url, array $whitelist)
{
// Break the given url into parts
$parts = parse_url($url);
// Break the parts into key-value pairs
$query = $parts['query'];
parse_str($query, $queryParts);
// Unset all unwanted keys
foreach (array_keys($queryParts) as $k) {
if (!in_array($k, $whitelist)) {
unset($queryParts[$k]);
}
}
// rebuild the url
$parts['query'] = http_build_query($queryParts);
// return
return http_build_url('', $parts);
}
Invocation should be:
$url = 'http://sitename.com/something/?inviter=1234&id=1';
$whitelist = [
'inviter'
];
$expectedUrl = 'http://sitename.com/something/?inviter=1234';
$actualUrl = transformUrlKeepQueryKeys($url, $whitelist);
assert($expectedUrl == $actualUrl);
Alternatively, you could implement something similar using a blacklist of keys to remove.
The only problem with this is that the function http_build_url is not included in core PHP, but is part of the PECL HTTP extension. If you are unable to install that extension in your environment, then you can use a pure PHP implementation of that function, for example here.

How to make a php variable based on two variable that vary

So i have this code, $value2 is an array of values that I edit.
I have .txt document for each of the variable in the array.. for exemple
sometext_AA.txt
sometext_BB.txt
I currently have over 50 text files, and it make a BIG BIG BIG php files because i have the following code made for each of the files for exemple sometext_AA.txt...
I would like to make one script(the following) so that one script will work for all of my $value2(I do not delete the old texts files when the value are changed so i am unable to just make script to read all different text file, it has to be done that it read the active $value2 and process them...
I am not even sure if I am on the good way but i really hope someone can help me out.
Thank you!
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_' .$value3' as $random2_' .$value3') {
$random3_' .$value3' = 'sometext_.$value3'.txt;
$random4_' .$value3' = json_encode(file_get_contents($random3_' .$value3'));
echo $random4_' .$value3';
}
}
This is a exemple of current text i have in my file, I have a very big php file, and, id like a code to make it simple
foreach($random1_AA as $random2_AA) {
$random3_AA = 'sometext_AA.txt;
$random4_AA = json_encode(file_get_contents($random3_AA));
echo $random4_AA;
}
foreach($random1_BB as $random2_BB) {
$random3_BB = 'sometext_BB.txt;
$random4_BB = json_encode(file_get_contents($random3_BB));
echo $random4_BB;
}
foreach($random1_CC as $random2_CC) {
$random3_CC = 'sometext_CC.txt;
$random4_CC = json_encode(file_get_contents($random3_CC));
echo $random4_CC;
}
foreach($random1_DD as $random2_DD) {
$random3_DD = 'sometext_DD.txt;
$random4_DD = json_encode(file_get_contents($random3_DD));
echo $random4_DD;
}
I think that this is what you are looking for, using the $var_{$var_in_var} syntax that PHP allows (so you can include a variable in a variable name).
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_{$value3} as $random2_{$value3}) {
$random3_{$value3} = 'sometext_'.$value3.'.txt';
$random4_{$value3} = json_encode(file_get_contents($random3_{$value3}));
echo $random4_{$value3};
}
}
However, I stongly advise you to consider the following points in order to make your code maintainable:
Use appropriate variable names representing the real content of each variable (you shoud never use "value1", "value2", etc. as the name tells nothing about the variable content).
Don't use variables in variable names unless absolutely necessary, which is not your case. You can use arrays, which are better suited for doing that.
In fact, I don't even know what $random1_XX and $random2_XX are supposed to be. I don't see you defining them in the code sample you posted.
Here is an example of how clear and concise you code may be if you use my advice and if all you need to read all the files and print them in JSON format (which is the only thing the program sample you posted would be doing after corrections).
$file_codes = array('AA', 'BB', 'CC');
foreach($file_codes as $file_code) {
echo json_encode(file_get_contents('sometext_'.$file_code.'.txt'));
}
Of course, if you have anything else in your program (maybe some code using the variables $random3_XX and $random4_XX?), I cannot guess what it is so I can't really offer you help to optimize this code.

Can I retry file_get_contents() until it opens a stream?

I am using PHP to get the contents of an API. The problem is, sometimes that API just sends back a 502 Bad Gateway error and the PHP code can’t parse the JSON and set the variables correctly. Is there some way I can keep trying until it works?
This is not an easy question because PHP is a synchronous language by default.
You could do this:
$a = false;
$i = 0;
while($a == false && $i < 10)
{
$a = file_get_contents($path);
$i++;
usleep(10);
}
$result = json_decode($a);
Adding usleep(10) allows your server not to get on his knees each time the API will be unavailable. And your function will give up after 10 attempts, which prevents it to freeze completely in case of long unavailability.
Since you didn't provide any code it's kind of hard to help you. But here is one way to do it.
$data = null;
while(!$data) {
$json = file_get_contents($url);
$data = json_decode($json); // Will return false if not valid JSON
}
// While loop won't stop until JSON was valid and $data contains an object
var_dump($data);
I suggest you throw some sort of increment variable in there to stop attempting after X scripts.
Based on your comment, here is what I would do:
You have a PHP script that makes the API call and, if successful, records the price and when that price was acquired
You put that script in a cronjob/scheduled task that runs every 10 minutes.
Your PHP view pulls the most recent price from the database and uses that for whatever display/calculations it needs. If pertinent, also show the date/time that price was captured
The other answers suggest doing a loop. A combo approach probably works best here: in your script, put in a few loops just in case the interface is down for a short blip. If it's not up after say a minute, use the old value until your next try.
A loop can solve this problem, but so can a recursive function like this one:
function file_get_contents_retry($url, $attemptsRemaining=3) {
$content = file_get_contents($url);
$attemptsRemaining--;
if( empty($content) && $attemptsRemaining > 0 ) {
return file_get_contents_retry($url, $attemptsRemaining);
}
return $content;
}
// Usage:
$retryAttempts = 6; // Default is 3.
echo file_get_contents_retry("http://google.com", $retryAttempts);

Persistent HTTP GET variables in PHP

Let's say I have some code like this
if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz.
I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.
Here's one way....
//get passed params
//(you might do some sanitizing at this point)
$params=$_GET;
//morph the params with new values
$params['bar']='xyz';
//build new query string
$query='';
$sep='?';
foreach($params as $name=>$value)
{
$query.=$sep.$name.'='.urlencode($value);
$sep='&';
}
If you are updating the query string you need ot make sure you don't do something like
$qs="a=1&b=2";
$href="$qs&b=4";
$href contains "a=1&b=2&b=4"
What you really want to do is overwrite the current key if you need to .
You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bugged)
function getUpdateQS($key,$value)
{
foreach ($_GET as $k => $v)
{
if ($k != $key)
{
$qs .= "$k=".urlencode($v)."&"
}
else
{
$qs .= "$key=".urlencode($value)."&";
}
}
return $qs
}
View report
Just set the link that changes bar to xyz to also have foo=abc if foo is already set.
$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';
?>
Click Me
You would have to render out the links with the proper URL querystring to make that happen. This is a design decision that you would need to make on your end depending on how your system is setup.
I have some sites that have this issue, and what I do is setup a querystring global variable that sets the current page data the top of the page request.
Then when I am rendering the page, if I need to make use of the current query string I do something like:
echo '<a href="myurl.php' . querystring . '&bar=foo';
It's not the cleanest, but it all depends on how your system works.
Save some code and use the built-in http_build_query. I use this wrapper in one of my projects:
function to_query_string($array) {
if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here
else $query = http_build_query($array);
return '?'.$query;
}
Also, though it isn't often used, you can have $_GET on the left-hand side of an assignment:
$_GET['overriden_or_new'] = 'new_value';
echo 'Yeah!';
Other than that, just do what Paul Dixon said.

Categories